java - in.next() 在做什么?

标签 java io java.util.scanner

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(); 行(在第一个代码快照中)是一种不好的做法,原因有两个:

  1. 如果输入为空,则会失败。
  2. 这是与 while 循环内容重复的代码。

关于java - in.next() 在做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14659838/

相关文章:

java - 如何在Android中像ios中的NSMutableDictionary一样使用字典?

c - 重定向标准输出,不理解行为

java - 扫描仪 next() 输入不匹配异常 ..在 nextInt() 之后使用 nextLine()

java - Market Place 在 Eclipse Luna 中不起作用

java - Getter方法使用

java - 从Java中的随机数生成器获取字符

haskell - 用 Haskell 编写的简单解释器,将打印输出保存到最后,而不是遇到打印语句时

java - 使用 fileinputstream 从文件中读取字节以查找丢失的图像

从 findWithinHorizo​​n 返回的 Java 大字符串转换为 InputStream

java - 如何让程序在循环内获取变量? ( java )