检查String的用户输入

时间:2014-06-09 04:00:27

标签: java string input

如何检查以确保用户输入仅为字符串?

System.out.println("What kind of crust would you like?");
     crust = scan.next();
     while( !crust.equals(scan.hasNext())) <===(PROBLEM, THIS DOES NOT WORK)
      {
         System.out.println("Pick a valid choice.");
         crust = scan.next

1 个答案:

答案 0 :(得分:0)

扫描仪将使用.next()方法读取字符串。下一个标记将自动读取为处理为字符串。如果你在程序要求地壳时输入123这样的东西,地壳变量将保持字符串&#34; 123&#34;不是123号。

你的while循环不起作用,因为.hasNext()函数返回一个布尔值,而crust总是一个字符串。

如果你想确保&#34; crust&#34;没有数字字符,要么使用正则表达式,要么更简单地循环遍历字符串的每个字符并检查字符是否为数字

boolean containsNumber = false;
for (int i = 0; i < crust.length(); i++) {
    if (Character.isDigit(crust.charAt(i))) {
        containsNumber = true;
        break;
    }
}

如果字符串包含数字,那么containsNumber布尔值将为true,如果不包含数字,则为false。