java hasNext方法,用于检查扫描程序是否有更多令牌

时间:2011-02-27 06:49:52

标签: 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(); 
  }

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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