2016-03-07 32 views
-5

我正在製作一個程序並使用用戶輸入。當我得到一個字符串時,我總是使用.nextLine(),但我也使用了.next(),它也做了同樣的事情。有什麼不同?.nextLine()和.next()之間的區別是什麼?

Scanner input = new Scanner(System.in); 
String h = input.nextLine(); 
String n = input.next(); 

有什麼區別?

+5

你閱讀文件? –

+0

https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html –

+1

不要讓StackOverflow爲您閱讀手冊。 –

回答

0

爲了使長話短說:

nextLine - 讀取整個行。

next - 直到第一個空間讀取。

舉個例子:

// Input : Barack Obama 
String st = in.next(); // st holds the String "Barack" 
String st2 = in.nextLine(); //st2 holds the String "Barack Obama" 
+0

我也在for循環中使用它們,並注意到如果你在String之前輸入一個數字,那麼它會跳過下一個線路,並且不會跳過下一個線路。爲什麼是這樣? – TravisTeague01

相關問題