Krystian
Krystian

Reputation: 71

Java scanner check if string or int

I have a scanner running where the user can input either strings or integers. There are only specific characters the user can enter such as a,e,u,r and the number can be anything. The check runs if its a letter but fails if the user enters a number.

String temp = scanner.next();
String[] validToken = {"x","e","u","r","+","-","/","*",};
for (String validToken1 : validToken) {
    if (temp.equals(validToken1) || temp.equals("\\d+")) {
        tokenCheck = true;
    } 
}

Upvotes: 0

Views: 1342

Answers (2)

Raghav
Raghav

Reputation: 4638

Change equals to matches. matches is used to check whether or not string matches a particular regular expression.

if (temp.equals(validToken1) || temp.matches("\\d+")) {
                     tokenCheck = true;
                } 

Upvotes: 2

Cr4xy
Cr4xy

Reputation: 179

It should be fixed when you replace equals with matches, because with equals you are checking if the string is literally \d+, it's not regex.

Upvotes: 2

Related Questions