2016-09-20 68 views
-1

我想接受來自用戶的3個整數輸入。如何忽略行中第一個整數之後的任何內容?例如,當我輸入1 2 31 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 
+0

閱讀'Scanner'文檔,看看是否有方法可以讀取一行的剩餘內容。如果是這樣,那就使用它。 – Tom

+0

改爲使用'Scanner.readLine()'來實現你的驗證。 –

+0

[如何從Java中的標準輸入讀取整數值]可能的重複(http://stackoverflow.com/questions/2506077/how-to-read-integer-value-from-the-standard-input-in- java) –

回答

0

這將工作正常。

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(); 
input.nextLine(); 

System.out.print("2nd Integer: "); 
test[2] = input.nextInt(); 
input.nextLine(); 

System.out.print("3rd Integer: "); 
test[3] = input.nextInt(); 
input.nextLine(); 
+0

它也可以。但是實際上'input.nextLine();'做了什麼? – PzrrL

+0

輸入。nextLine()將此掃描器推進到當前行並返回跳過的輸入。可以通過https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()進一步閱讀。 –

0

這個簡單的方法,您可以將數字轉換爲字符串數組,並將其轉換爲整數。

Scanner scanner = new Scanner(System.in); 
String[] array = scanner.nextLine().split(" "); 
int[] intArray = new int[array.length]; 

for(int i = 0; i < array.length; i++){ 
    intArray[i] = Integer.parseInt(array[i]); 
} 

,你可以找到很多好這裏的答案; Read integers separated with whitespace into int[] array

+0

我只需要一行輸入的第一個整數,其餘的輸入應該忽略(或清除)。用戶需要在下次出現的提示中輸入新值。這就是爲什麼我需要在第一個空白區域後忽略所有內容。 – PzrrL

0

嘿使用此代碼,這將生成您所需的輸出,

int[] tes = new int[4];// I just use 1-3 
    System.out.println("Warning : Whitespace cannot be enter in the input"); 
    Scanner input = new Scanner(System.in); 
    System.out.println("1st Integer: "); 
    tes[1] = Integer.parseInt(input.nextLine().replaceAll("\\s.+", "")); 
    System.out.println("2nd Integer: "); 
    tes[2] = Integer.parseInt(input.nextLine().replaceAll("\\s.+", "")); 
    System.out.println("3rd Integer: "); 
    tes[3] = Integer.parseInt(input.nextLine().replaceAll("\\s.+", "")); 
    System.out.println("Output : "+tes[2]); 

輸出:

Warning : Whitespace cannot be enter in the input 
1st Integer: 
456 ddf 477 
2nd Integer: 
33 dfgf ddddds rrsr 566 
3rd Integer: 
2 4 4 4 
Output : 33 

工作:

  • 最初,它讀取單個線作爲串。
  • 然後使用正則表達式刪除空格後面的所有字符。
  • 最後將字符串轉換爲整數。

希望這會有幫助,如有任何澄清,請在下方留言。