gpt4 book ai didi

java hasNext 方法用于检查扫描仪是否有更多标记

转载 作者:行者123 更新时间:2023-12-01 15:55:35 31 4
gpt4 key购买 nike

我想使用下面的代码片段来允许用户一次输入四个值,并用空格分隔,在这种情况下,它们将被单独捕获并分配给变量。或者,用户可以一次输入一个值,同时等待每个值之间的提示。如果 if(in.hasNext()) 像我希望的那样工作,则可以使用下面的代码轻松实现此解决方案,但我了解到 hasNext 显然总是评估为 TRUE,即使在流,因此程序会阻塞并等待输入。有没有办法调整此代码以获得所需的结果? (月、日和年是字符串,稍后会在程序中解析为整数。)谢谢

Scanner in = new Scanner(System.in); 
System.out.println("Please enter your first name, last name, or full name:");
traveler = in.nextLine();

System.out.println("Please enter your weight, birth month, birth day of month, and birth year as numbers.\nYou may enter all the numbers at once -- right now -- or you may enter them one at a time as the prompts appear.\nOr, you may also enter them in any combination at any time, so long as weight (at least) is entered now and the remaining \nthree numbers are eventually entered in their correct order:");
pounds = in.nextInt();

if (in.hasNext()) {
month = in.next();
} else {
System.out.println("Please enter your birth month, or a combination of remaining data as described previously, so long as the data you enter now begins with birth month:");
month = in.next();
}
if (in.hasNext()) {
day = in.next();
} else {
System.out.println("Please enter your birth day of month, or a combination of remaining data as described previously, so long as the data you enter now begins with birth day of month:");
day = in.next();
}
if (in.hasNext()) {
year = in.next();
} else {
System.out.println("If you've made it this far, then please just enter your birth year:");
year = in.next();
}

最佳答案

一次读取一行,然后调用 split("") 来确定用户输入的数量和值。

关于java hasNext 方法用于检查扫描仪是否有更多标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5131875/

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