【发布时间】:2011-07-05 03:36:10
【问题描述】:
我想使用下面代码的 sn-p 来允许用户一次输入四个由空格分隔的值,在这种情况下,它们将被单独捕获并分配给变量。或者,用户可以一次输入一个值,同时等待每个值之间的提示。如果 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();
}
【问题讨论】:
标签: java