我想接受來自用戶的3個整數輸入。如何忽略行中第一個整數之後的任何內容?例如,當我輸入1 2 3
或1 abc 3
時,int test[]
變量將只接受1
,而該行的其餘部分將被忽略。Java如何忽略空白後的任何輸入?
目標:忽略(或清除)第一個整數之後的任何內容(從第一個空格開始),包括任何空格或字符。如果可能的話,向用戶發出警告以警告用戶不能在輸入中輸入空白將是非常好的。我沒有找到從同一行讀取多個整數的解決方案。
這是我有:
private final int[] test = new int[4]; // I just use 1-3
Scanner input = new Scanner(System.in);
System.out.print("1st Integer: ");
test[1] = input.nextInt();
System.out.print("2nd Integer: ");
test[2] = input.nextInt();
System.out.print("3rd Integer: ");
test[3] = input.nextInt();
對於上面的代碼中,如果我簡單輸入的整數例如1 enter 2 enter 3 enter
,沒關係。但是,當我輸入類似1 2 3
(3個整數之間的空白),它只是輸出是這樣的:
1st Integer: 1 2 3
2nd Integer: 3rd Integer:
我想我的代碼是這樣的:
1st Integer: 1
2nd Integer: 2
3rd Integer: 3
閱讀'Scanner'文檔,看看是否有方法可以讀取一行的剩餘內容。如果是這樣,那就使用它。 – Tom
改爲使用'Scanner.readLine()'來實現你的驗證。 –
[如何從Java中的標準輸入讀取整數值]可能的重複(http://stackoverflow.com/questions/2506077/how-to-read-integer-value-from-the-standard-input-in- java) –