[英]Trouble using two Scanners for different input
當使用Scanner
從標准輸入中讀取時,換行符會進入,而原本打算讀取的內容不會被占用,從而給后續輸入帶來麻煩。 可以使用exampleScanner.nextLine()
。 但是,我嘗試使用以下兩種不同的掃描儀,但無法解決問題。 我知道在Scanner
有很多與此類型的問題有關的問題和答案,但是我似乎仍然找不到我特定問題的答案。 我的問題是否可以解決,或者我必須使用一台Scanner
? 這是一些代碼:
import java.util.Scanner;
import java.util.NoSuchElementException;
public class ScannerTest {
public static void main(String[] args) {
char sym = ' ';
int x = 0;
/* scan for char (string) */
Scanner scanForSym = new Scanner(System.in);
System.out.print("Enter a symbol: ");
try {
sym = scanForSym.next().charAt(0);
} catch (NoSuchElementException e) {
System.err.println("Failed to read sym: "+e.getMessage());
}
scanForSym.nextLine(); // makes no diff when using different Scanner
scanForSym.close();
/* scan for int with different scanner */
Scanner scanForX = new Scanner(System.in);
System.out.print("\nEnter an integer: ");
try {
x = scanForX.nextInt();
//x = scanForSym.next(); // this works fine (comment out the close above)
} catch (NoSuchElementException e) {
System.err.println("Failed to read x: "+e.getMessage());
}
scanForX.close();
System.out.println("sym: "+sym);
System.out.println("x: "+x);
}
}
錯誤與此行相關:
scanForSym.close();
在InputStream中關閉System.in。 所以這個電話
x = scanForX.nextInt();
由於scanForX
試圖從已經關閉的InputStream讀取,所以引發IOException。
嘗試移動
scanForSym.close();
在某處
x = scanForX.nextInt();
盡管(從注釋中重述),但不清楚為什么要在多個Scanner實例都與System.in
關聯時使用它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.