nextInt()不會消耗\ n(新行),然後nextLine將消耗\ n字符的數量行(由nextInt左邊)。您可以在nextInt()之後立即使用Integer.parseInt(in1.nextLine())或另一個in1.nextLine()來消耗\ n字符。
跟蹤代碼的
Scanner in1 = new Scanner(System.in);
int t = in1.nextInt(); // read a number (let say 3)
int n=0, m=0;
String input[] = new String[t];
for (int i = 0; i<t; i++){
input[i] = in1.nextLine(); // the first time nextLine will read the \n char
// The second time an 1 (for example)
// And the third time a 2 (for example)\
}
// Finally you will have an array like this
// input[0] = "\n"
// input[0] = "1"
// input[0] = "2"
FIX
Scanner in1 = new Scanner(System.in);
int t = Integer.parseInt(in1.nextLine());
int n=0, m=0;
String input[] = new String[t];
for (int i = 0; i<t; i++){
input[i] = in1.nextLine();
}
你能定義「多輸入」嗎? – TheLostMind
輸入可以以任意數量的行給出。第一個輸入顯示接下來會有多少個輸入,所以如果我給3作爲第一個輸入,這意味着我將再給出3個輸入 – Mahesh
然後使用'nextLine'讀取數據並使用'\\ s +'分割。第一個令牌將是輸入值的數量,下面的令牌將是實際的輸入值。 – TheLostMind