2011-02-27 84 views
0

我想使用下面的代码片段来允许用户一次输入四个值,以空格分隔,在这种情况下,它们将被单独捕获并分配给变量。或者,用户可以一次输入一个值,同时等待每个值之间的提示。如果if(in.hasNext())像我所希望的那样工作,这个解决方案可以很容易地用下面的代码实现,但是我已经知道hasNext显然总是评估为TRUE,即使在下面的代码中没有额外的标记流,所以程序会阻塞并等待输入。有没有办法调整这些代码以获得所需的结果? (月,日和年是得到解析为整数后面的程序字符串。)谢谢java hasNext方法用于检查扫描程序是否有更多的令牌

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

回答

1

一次读取一行,然后调用split(" ")确定有多少和哪些值输入的用户。

+0

感谢这个想法,我使用数组(测试数组长度)切换到split(“\\ s +”)来捕获令牌和/或相应地提示未输入的令牌。我不得不使用一整套IF ELSE IF ELSE来最终将用户顺序输入排列组合到一起,然后将其分割和排列,但它现在起作用了。再次感谢您的建议 - 我放弃了if(in.hasNext()),因为我看不到让扫描器认为它是空的方法。 – finlander 2011-02-27 13:13:18

0

有一个InputStream.available()方法返回可以不阻塞地读取多少个字符;然而,这并不能确定是否有完整的号码或线路。尽管如此,Scanner类的文档明确表示hasNext可以阻止。

相关问题