2016-09-20 146 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 

工作:

  • 最初,它读取单个线作为串。
  • 然后使用正则表达式删除空格后面的所有字符。
  • 最后将字符串转换为整数。

希望这会有帮助,如有任何澄清,请在下方留言。