我正在嘗試從用戶那里獲取字符和字符串。但它只獲取字符而沒有獲取字符串。 Scanner in=new Scanner(System.in); String s; System.out.println("Enter a string"); char c = in.next().charAt(0); System.out.println(c); s = in.nextLine(); System.out.println(s);
2 回答

茅侃侃
TA貢獻1842條經驗 獲得超21個贊
當您next()使用掃描器調用時,您將獲得整個字符串,直到下一個完整的令牌。下次你打電話時nextLine(),你要找的字符串就不見了。假設你想要的字符在字符串的開頭,你應該獲取字符串,然后從字符串中獲取字符。
s = in.nextLine();
char c = s.charAt(0);

慕的地8271018
TA貢獻1796條經驗 獲得超4個贊
試試這個:
public static void main(String args[]) // start of main
{
Scanner in=new Scanner(System.in);
String s;
System.out.println("Enter a char");
char c = in.next().charAt(0);
System.out.println(c);
System.out.println("Enter the String");
s = in.next();
System.out.println(s);
}
添加回答
舉報
0/150
提交
取消