2016-02-14 62 views

回答

1

如何讓控制檯掃描儀再次使用最後一次輸入?

不要。將最後一個輸入保存在一個變量或集合中,並以此方式訪問它。

1
y=scanner.nextInt();//user inputs 5 
    y=5;// You can reuse y 
    x=y;// assign same input to another value 
1

我希望我下次使用掃描儀使用上一行相同的輸入,我該怎麼做?

有沒有辦法使Scanner做到這一點。 Scanner API不提供任何回溯到上次成功讀取操作前的點的方法。試圖通過「尋找」底層數據流來實現這一點不太可能是因爲掃描儀的內部緩衝。

我能想到的是一個通用的解決方案,最好是這樣的:

Scanner scanner = new Scanner(...) 
while (scanner.hasNext()) { 
    String line = scanner.nextLine(); 
    Scanner lineScanner = new Scanner(line); 
    // read tokens from lineScanner 
    // to "reset" to the start of the line, discard lineScanner 
    // and create a new one. 
} 

另一種方法可能只是保存您掃描的東西,在更高層次上做復位。但是,如果您需要以不同的方式重新掃描行,則不起作用;例如使用nextInt()調用代替next()調用。

相關問題