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

标签 java

我想使用下面的代码片段来允许用户一次输入四个值,并用空格分隔,在这种情况下,它们将被单独捕获并分配给变量。或者,用户可以一次输入一个值,同时等待每个值之间的提示。如果 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/

相关文章:

java - Selenium 网络驱动程序 : Unable to access elements of a drop down list (un-ordered list)

过滤器中的 Java OutOfMemory 错误

java - @Transactional 不回滚

java - 创建新工件时出现错误 "MANIFEST.MF already exists in VFS"

java - Gson反序列化时失败 "understand"泛型类型

java - 随机选择 4 种颜色?

java - 将两个正则表达式合并为一个

java - RecyclerView 重新计算 WRAP_CONTENT

java - 更改 ArrayList<List<String>> 中的 String 元素正在更改 ArrayList 中的两个列表

java - 将java项目部署到远程glassfish服务器