简体   繁体   English

如何使用Scanner.hasNextInt()检查下一个3输入是否为int并仅在Java中循环

[英]How to check if the next 3 input is an int by using Scanner.hasNextInt() and loop only in java

How can I check if the next three input user is giving is an int value, like let's say there is three variables, 如何检查接下来的三个输入用户给出的是一个int值,比如说有三个变量,

  • var1 VAR1
  • var2 VAR2
  • var3 VAR3

And I am taking input as, 我认为,

Scanner sc = new Scanner (System.in); var1 = sc.nextInt(); var2 = sc.nextInt(); var3 = sc.nextInt();

Now if I want to use while(sc.hasNextInt()) to determine if the next input is an int or not then it will only check if the next input for var1 is int or not and won't check for the other to variables, var2 , var3 . 现在,如果我想使用while(sc.hasNextInt())确定下一个输入是否为int,则它将仅检查var1的下一个输入是否为int,而不检查其他to变量。 , var2var3 One thing can be done by using while loop with if (condition) . 通过将while loopif (condition)一起使用可以完成一件事。 For example, 例如,

Scanner sc = new Scanner (System.in);
while (sc.hasNextInt()) {
   var1 = sc.nextInt();
   if (sc.hasNextInt()) {
      var2 = sc.nextInt();
      if (sc.hasNextInt()) {
         var3 = sc.nextInt();
      }
   }
 }

But this looks lengthy and needs a lot to write. 但这看起来很冗长,需要大量编写。 For similar issue I have seen for Language C there is a method for scanf() which can do the trick. 对于我在语言C中看到的类似问题,有一种可以解决问题的scanf()方法。 For example, 例如,

while(scanf("%d %d %d", &var1, &var2 & var3) == 3) { // Statements here }

So my question is there any such features available in java's Scanner.hasNextInt or Scanner.hasNext("regex") . 所以我的问题是Java的Scanner.hasNextIntScanner.hasNext("regex")是否有可用的此类功能。

I have also tried sc.hasNext("[0-9]* [0-9]* [0-9]*") but didn't worked actually. 我也尝试过sc.hasNext("[0-9]* [0-9]* [0-9]*")但实际上没有用。

Thank you in advance. 先感谢您。

hasNext(regex) tests only single token. hasNext(regex)仅测试单个令牌。 Problem is that default delimiter is one-or-more-whitespaces so number number number can't be single token (delimiter - space - can't be part of it). 问题在于默认分隔符是一个或多个空格,因此number number number不能是单个标记(分隔符-空格-不能是其中的一部分)。 So sc.hasNext("[0-9]* [0-9]* [0-9]*") each time will end up testing only single number . 因此sc.hasNext("[0-9]* [0-9]* [0-9]*")每次只会测试单个number BTW in your pattern * should probably be + since each number should have at least one digit. 模式中的BTW *可能应该为+因为每个数字都应至少包含一位数字。

To let spaces be part of token we need to remove them from delimiter pattern. 为了让空格成为令牌的一部分,我们需要将它们从定界符模式中删除。 In other words we need to replace delimiter pattern with one which represents only line separators like \\R ( more info ). 换句话说,我们需要用只代表\\R这样的行分隔符的定界符模式代替( 更多信息 )。 This way if user will write data in one line (will use enter only after third number) that line would be seen as single token and can be tested by regex. 这样,如果用户将数据写在一行中 (仅在第三个数字之后才使用enter),则该行将被视为单个令牌,并且可以由正则表达式进行测试。

Later you will need to set delimiter back to one-or-more-whitespaces ( \\s+ ) because nextInt also works based on single token, so without it we would end up with trying to parse string like "1 2 3" . 稍后,您将需要将定界符设置回一个或多个空格( \\s+ ),因为nextInt也基于单个标记工作,因此,如果没有分隔符,我们将最终尝试解析诸如"1 2 3"类的字符串。

Scanner sc = new Scanner(System.in);
sc.useDelimiter("\\R");
System.out.print("Write 3 numbers (sepate them with space): ");
while(!sc.hasNext("\\d+ \\d+ \\d+")){
    String line = sc.nextLine();//IMPORTANT! Consume incorrect values
    System.out.println("This are not 3 numbers: "+line);
    System.out.print("Try again: ");
}
//here we are sure that there are 3 numbers
sc.useDelimiter("\\s+");//nextInt can't properly parse "num num num", we need to set whitespaces as delimiter

int var1 = sc.nextInt();
int var2 = sc.nextInt();
int var3 = sc.nextInt();

System.out.println("var1=" + var1);
System.out.println("var2=" + var2);
System.out.println("var3=" + var3);

Possible problem with this solution is fact that \\d+ will let user provide number of any length, which may be out of int range. 此解决方案可能存在的问题是\\d+将允许用户提供任意长度的数字,而该长度可能超出int范围。 If you want to accept only int take a look at Regex for a valid 32-bit signed integer . 如果只想接受int请查看Regex以获取有效的32位带符号整数 You can also use nextLong instead, since long has larger range, but still it has max value. 您也可以使用nextLong ,因为long范围更大,但仍然具有最大值。 To accept any integer, regardless of its length you can use nextBigInteger() . 要接受任何整数,无论​​其长度如何,都可以使用nextBigInteger()

I tried with nextLine method and usage of Pattern . 我尝试了nextLine方法和Pattern用法。 Regex is matching with 3 numbers which is separeted with space. 正则表达式匹配3个数字,并用空格分隔。 So it can be like this i think ; 我想就是这样。

Scanner scanner = new Scanner(System.in);

Pattern p = Pattern.compile("[0-9]+\\s[0-9]+\\s[0-9]+$");
while(!p.matcher(scanner.nextLine()).find()){
    System.out.println("Please write a 3 numbers which is separete with space");
}
System.out.println("Yes i got 3 numbers!");

I hope this helps you. 我希望这可以帮助你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM