0

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;
    } 
}
2
  • Couldn't you just use a try catch? Commented Nov 25, 2016 at 17:33
  • Using a Set instead of a String[] will enable you to do this: validToken.contains(temp) and like @iNam said, if you want to check a String agains a regex use matches(....) Commented Nov 25, 2016 at 17:39

2 Answers 2

2

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;
                } 
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.