2011-02-27 83 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可以阻止。

相關問題