【问题标题】:java hasNext method for checking scanner for more tokensjava hasNext 方法用于检查扫描仪是否有更多令牌
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 感谢您的想法,我切换到 split("\\s+") 使用数组(测试数组长度)来捕获令牌和/或相应地提示尚未输入的令牌。我不得不使用大量的 IF ELSE IF ELSE 来最终将用户顺序输入排列与拆分和数组放在一起,但它现在可以工作了。再次感谢您的建议——我放弃了 if(in.hasNext()) 因为我看不到让扫描仪认为它是空的方法。
    【解决方案2】:

    有一个InputStream.available()方法,返回可以读取多少个字符而不阻塞;但是,这并不能确定是否有完整的数字或行。 Scanner 类的文档明确指出 hasNext 可以阻止。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-15
      • 2014-06-15
      • 1970-01-01
      相关资源
      最近更新 更多