先上代碼
public class ComplexNumber {
public static void main(String[] args) {
//ArrayList<Complex> arrayList = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
String orders[] = new String[n];
for(int i = 0;i < 3;i ++){
System.out.println("第" + i + "次輸入");
orders[i] = scanner.nextLine();
}
for(int i = 0;i < 3;i ++){
System.out.println("第" + i + "次輸出");
System.out.println(orders[i]);
}
}
}
我就敲了一個3我的輸入循環竟然執行了一次,按理說還沒到循環哪裏,怎麼就這樣呢?
實際情況是這樣的
nextInt方法根據分隔符(回車,空格等)只取出輸入的流中分割的第一部分並解析成Int,然後把後面的字節傳遞下去。
所以,第二種情況鍵盤實際輸入是“3+回車”,nextInt讀出了“3”,並留下了“回車”,
接着netxLine讀到了一個“回車”,這是字符串的結束判定符啊,所以讀到的字符串就是空字符串“”。
所以只能再次讀一下將那個回車消化掉
注意事項
最好不要再nextInt()後面有nextLine(),忘記消化回車,容易翻車。。。