I am using Scanner class to take input. I am trying to get all the words in a line using in.next(). I know it can be done using nextLine() but i want to understand how in.next() and in.hasNext() works.
System.out.println("What is designation");
String desg = in.next();
while(in.hasNext()){
desg+=in.next();
}
给出输出为
What is designation
member technical staff\n
^Z
Hello abhishek kumarNext year you will be 22Salary is 30000.0Designation is membertechnicalstaff
但是如果我使用
System.out.println("What is designation");
String desg = in.next();
if(in.hasNext()){
desg+=in.next();
}
它的输出为
What is designation
member technical staff
Hello abhishek kumarNext year you will be 22Salary is 44254.0Designation is membertechnical
In the first case i am getting all the words but it keeps asking for next input and i have to specify end of input using CTRL+Z. But in second case i am not getting the last word(staff). Please explain.
最佳答案
第一个代码在 while
循环中读取输入 - 即直到找到 in.hasNext() == false
。
第二个代码使用 if
条件 - 它最多读取 in.next()
一次(在初始读取之后)。
因此,第二个代码并不是“等待新输入”,因为它只要求 in.next()
一次,并且直到输入耗尽为止,这与第二个代码快照不同。
附注请注意,String desg = in.next();
行(在第一个代码快照中)是一种不好的做法,原因有两个:
- 如果输入为空,则会失败。
- 这是与 while 循环内容重复的代码。
关于java - in.next() 在做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14659838/