简体   繁体   中英

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;
    } 
}

当您更换应固定equalsmatches ,因为等于要检查如果字符串字面\\d+ ,这不是正则表达式。

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;
                } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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