java - System.out.println 重复自身

标签 java eclipse

谁能指出正确的方向,为什么当我使用 for 循环时 println 函数在输出中出现两次。谢谢

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    System.out.println("Enter the number of employees to calculate:");
    int numberEmployees = scan.nextInt();

    for(int i=0; i<numberEmployees; i++){               
            System.out.println("Enter First Name:");
            name = scan.nextLine();
            System.out.println("Enter Last Name:");
            last = scan.nextLine();
            System.out.println("Enter Document #:");
            document = scan.nextInt();
            System.out.println("Enter Basic Salary");
            basicSalary = scan.nextInt();
            System.out.println("Enter # of Hours");
            hours = scan.nextInt();
    }
}

输出

Enter the number of employees to calculate:
1
Enter First Name:
Enter Last Name:
daniel
Enter Document #:

最佳答案

问题是,当您输入带有新行的 1 时,nextInt() 函数不会删除您在 1 中输入的换行符。将对 scan.nextInt() 的调用更改为 Integer.parseInt(scan.nextLine()) 并且它应该按照您想要的方式运行。

进一步解释;这是来自 Java API 的内容。

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

The next() and hasNext() methods and their primitive-type companion methods (such as nextInt() and hasNextInt()) first skip any input that matches the delimiter pattern, and then attempt to return the next token. Both hasNext and next methods may block waiting for further input.

所以,显然发生的事情(我在页面上没有看到任何东西可以证实)是在 next()hasNext() 及其相关的之后方法读入一个标记后,它们会立即返回它,而不会吞噬它后面的定界符(在我们的例子中是空格)。因此,在它读入您的 1 之后,换行符仍然存在,因此以下对 nextLine() 的调用有一个换行符需要吞噬并这样做了。

关于java - System.out.println 重复自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11750060/

相关文章:

Java - 模式匹配但未能捕获

java - 使用 Java EE 和 Tomcat 定位创建的文件

android - 如何在 appium 测试用例中运行 android shell 命令?

android - 如何在 Eclipse 的 Android 应用程序模板中编辑内容?

java - 获取java.lang.IllegalStateException : This call must happen in the AWT Event Dispatch Thread! 请引用

java - 保持游戏中运行总数的最佳方法

java - 获取资源时的NPE

java - 为什么我的 Eclipse Java 包被视为文件夹?

android - 在eclipse中设置NDK目录的路径

java - Eclipse如何添加文件夹库?