gpt4 book ai didi

Java 在另一个 nextLine 后输入 nextLine

转载 作者:行者123 更新时间:2023-11-30 05:52:19 25 4
gpt4 key购买 nike

代码:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com