一般,java的輸入類一般用Scanner,其方法next(),nextInt()和nextLine()的區別如下:
nextInt()只讀取數值,剩下"\n"還沒有讀取,所以光標還在本行中;
next() 方法遇見第一個有效字符(非空格,非換行符)時,開始掃描,直到遇見第一個分隔符或結束符(空格或換行符)時,結束掃描,光標還是在本行。
nextLine()掃描到一行內容當作是字符串處理,所以光標在下一行首部。
一般來說,next(),nextInt() 不推薦和 nextLine()混合使用,因爲nextLine()會讀取next他們遺留下的結束符(換行)直接結束讀取。如果非要使用,可以在next()/nextInt() 和 nextLine() 之間用一個 nextLine() 過濾掉結束符。
最好,nextLine() 自己單獨使用。下面是我自己習慣使用的輸入格式
情況一:不知道有多少行輸入(或者多測試用例)。如果是先獲取所有輸入,再集中處理,使用ctrl+D結束輸入。
輸入:11001
11111
Scanner sc = new Scanner(System.in);
ArrayList<String> arrayList = new ArrayList<>();
while (sc.hasNext()){
arrayList.add(sc.next());//nextLine()/next()看情況使用
}
情況二:一行輸入,略
情況三:輸入爲0結束輸入
while ((num = sc.nextInt()) != 0){
.....
}
情況四:空行結束輸入
while (true){
String s = sc.nextLine();
if(s.equals(""))
break;
}
情況五,你知道有幾行輸入
Scanner in = new Scanner(System.in);
int n =in.nextInt();//n表示下面的輸入行數
ArrayList<String> arr = new ArrayList<>();
While(n-- > 0){
arr.add(in.next());
}
情況六? 記得有次輸入以空行結束,但是輸入必須下面這樣,我也不懂
Scanner sc = new Scanner(System.in);
ArrayList<String> arrayList = new ArrayList<>();
while (sc.hasNext()){
String s = sc.nextLine();
if(s.equals("EOF"))
break;
arrayList.add(s);
}