0

Using a scanner, how would I be able to tell if the String I am scanning only contains 2 integers in Java?

I have already using the hasNext() method, but I'm unsure what to use. I know I can use hasNextInt(), but my program requires that nothing else was in the String.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
nNn
  • 21
  • 2

3 Answers3

1

I assume that "only contains two integers" means "contains two tokens, both of which are integers". I would probably do this with a regular expression, but if you want to do it by scanning, something like this should do the work:

public boolean hasTwoIntegers(String s){
  Scanner sc = new Scanner(s);
  if (!scanner.hasNextInt()) return false;
  scanner.nextInt();
  if (!scanner.hasNextInt()) return false;
  if (scanner.hasNext()) return false;
  return true; 


}

Generalized to handle N ints:

public boolean hasNIntegers(String s, int n){
  Scanner sc = new Scanner(s);
  for (int i = 0; i <n; i++){
    if (!scanner.hasNextInt()) return false;
    scanner.nextInt();
  }
  if (scanner.hasNext()) return false;
  return true; 

}
Jon Kiparsky
  • 7,499
  • 2
  • 23
  • 38
1

You can just do it with a pattern:

import java.util.regex.Pattern;

public class Patternizer {
    public static void main(String[] args){
        Pattern p=Pattern.compile("\\d+ \\d+");
        System.out.print("1000 10000".matches(p.pattern()));
        System.out.print("mmd 10000".matches(p.pattern()));
        System.out.print("1000.0 10000".matches(p.pattern()));
    }
}
0

hasNext has variation hasNext(regex) which can be applied to check if next token matches regex, but it is limited to only one token. You would have to use delimiter which could allow you to have tokens build from two worlds. Such delimiter can look like this

sc.useDelimiter("(?<!\\G\\S+)\\s+");//delimiter representing "every second space"

(you can find explanation of this regex in Extracting pairs of words using String.split() ).

This will allow you to use hasNext("\\d+\\s+\\d+") which will check if next token is number, space, number.

After your test is complete you can set delimiter to standard one if you are interested in reading single word tokens later.

Code example

String data = "foo 12 32 bar";

Scanner sc = new Scanner(data);
Pattern delimiter = sc.delimiter();//default delimiter

System.out.println(sc.next());//foo
sc.useDelimiter("(?<!\\G\\S+)\\s+");//delimiter representing "every second space"

System.out.println(sc.hasNext("\\d+\\s+\\d+"));//TRUE

sc.useDelimiter(delimiter);//reset delimiter

System.out.println(sc.nextInt());//12
System.out.println(sc.nextInt());//32
System.out.println(sc.next());//bar

but my program requires that nothing else was in the String.

If you are interested in checking if entire string (not just some part of it) is two numbers than you can simply use

yourString.matches("\\d+\\s+\\d+")
Community
  • 1
  • 1
Pshemo
  • 122,468
  • 25
  • 185
  • 269