Java 在另一个 nextLine 后输入 nextLine

标签 java input

代码:

public void addTest(int idUser) throws IOException {

    String date = null;
    String tec = null;

    System.out.println("Enter name for test file :");
    String file = input.next(); //Name of file

    System.out.println("Enter date formatted as dd/mm/yyyy hh:mm :");
    date = input.nextLine(); //String 2 parts
    input.next();

    System.out.println("Enter technician name :");
    tec = input.nextLine(); // String 2+ parts
    input.next();

    String path = "C:\\Test\\Sample\\" + file;
    String chain = readFile(path);

    ClinicalTest test = new ClinicalTest(chain, date, idUser, tec);
    System.out.println(test.getDate()+"\n" + test.getTec());

    createTest(test);
}

当输入日期12-12-2018 13:45和技术名称Mark Zus时,尝试创建测试失败。 sysout 仅显示13:45

enter image description here

我在每个 nextLine() 下尝试了 input.next(),因为如果我不这样做,永远不会让我完成日期字段。

enter image description here

如果仅对每个条目使用nextLine(),就会发生这种情况

最佳答案

我建议您阅读JavaDoc这对使用方法很有帮助。正如 nextLine() 方法上面所写:

This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

这意味着通过使用 next() 方法,您正在读取输入的第一部分,然后当您使用 nextLine() 时,它会捕获该行的其余部分在您的输入示例中为 13:45

所以你不需要input.next()。以下代码完美运行:

public static void main(String[] args){
    Scanner input = new Scanner(System.in);

    String date = null;
    String tec = null;

    System.out.println("Enter name for test file :");
    String file = input.nextLine();

    System.out.println("Enter date formatted as dd/mm/yyyy hh:mm :");
    date = input.nextLine(); //String 2 parts

    System.out.println("Enter technician name :");
    tec = input.nextLine(); // String 2+ parts
}

关于Java 在另一个 nextLine 后输入 nextLine,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53678607/

相关文章:

java - Gwt NavigableSet 找不到源

java - 自定义 `JOptionPane.YES_NO_OPTION`

python - Pygame:图形输入+文本输入

python - 按 enter 键退出 while 循环而不阻塞。我该如何改进这种方法?

python - 简单的 python 代码不起作用

angularjs - iOS/安卓 : Open numeric keyboard on password-type input field

Java:通过资源加载 SSL keystore

java - 如何在主java方法中添加额外的代码?

java - cvc-复杂类型.3.2.2 : Attribute xsi:schemaLocation is not allowed to appear in <people> in Java DOM

c - 如何只检查一次输入,而不是挂起等待输入