Java 如何仅为字符串值设置异常?

Java 如何仅为字符串值设置异常?,java,string,exception,exception-handling,Java,String,Exception,Exception Handling,我从用户那个里获取输入,它应该是字符串,但代码并没有像我期望的那个样工作。这是我的密码` while(true){ try{ System.out.print("Enter test string"); str=sc.nextLine(); break; } catch(InputMismatchException e) { System.out.println("Please enter String value");

我从用户那个里获取输入,它应该是字符串,但代码并没有像我期望的那个样工作。这是我的密码`

while(true){
    try{
      System.out.print("Enter test string");
      str=sc.nextLine();
      break;
    }
    catch(InputMismatchException e) {
     System.out.println("Please enter String value");
     continue;
    }
  }
  System.out.println(str);
`

如果我给出的是整数值,它应该再次询问,但这里它正在打印整数值。如果您试图直接解析整数值,那么您将得到一个更有意义的异常

String str = "";
Scanner sc = new Scanner(System.in);
while (true) {
    try {
        System.out.print("Enter test string");
        str = sc.nextLine();
        Integer.parseInt(str);
        System.out.println("Please enter String value");
    } catch (NumberFormatException e) {
        // You *didn't* get a number; you actually have a String now.
        // You can terminate the loop here.
        break;
    }
}
System.out.println(str);
将所有内容都视为字符串,因此没有例外。尝试使用这样的语句

int num; 
  &
num=sc.nextInt();
您将发现异常将被捕获,因此代码没有问题

假设用户将输入
“这是一个字符串”
,即使它包含整数,但仍然是一个字符串。即使用户每次输入
“43728”
仍将其视为字符串,也同样适用

以下是你如何实现目标的方法

while(true){
              System.out.print("Enter test string");
              str=sc.nextLine();
              Pattern pattern = Pattern.compile("\\d");
              Matcher matcher = pattern.matcher(str);
              if (matcher.find()) {
                  //System.out.println(matcher.group(0));
                 continue; 
              }
              break;
          }

检查字符串是否不是这样的数字:

while(true){
        try{
            System.out.print("Enter test string");
            str=sc.nextLine();

            if(isNumeric(str)) {
                continue;
            }
            break;
        }
        catch(InputMismatchException e) {
            System.out.println("Please enter String value");
            continue;
        }
    }
    System.out.println(str);
}

public static boolean isNumeric(String str)
{
    for (char c : str.toCharArray())
    {
        if (!Character.isDigit(c)) return false;
    }
    return true;
}

如果您只是尝试检查字符串是否不是数字,则可以尝试

String str = sc.nextLine();
if (StringUtils.isNumeric(str))
    System.out.println(str);
但是,如果您的数字有小数点或其他数字,此方法将不起作用

检查


对于类似的答案

a
字符串
可以包含数字ascii字符。。。为什么“123”是非法的?试试这个
str=sc.nextLine();如果(str.matches(“\\d”){continue;}中断
您提供的代码从不抛出
输入不匹配异常
[teach me]
当用户键入12345时,它是一个字符串。它也可以被解释为整数、浮点值、十六进制整数,并且可能以其他方式解释,但首先它是一个字符串。考虑不使用名为“STR”的变量,这是一个int。这只是对读者撒谎。我试着不改变语法以方便提问者。如果stackoverflow认为它不好,我会编辑它,再也不会这样做了。我们对代码约定都有自己的看法,它们只是:意见。你应该写尽可能清晰的代码。也就是说,一个不可辩驳的事实是,使用
nextInt
不会给OP带来他们想要的东西。他们需要一次消耗整行数据,即使这意味着他们将有一个带有“d1234”的字符串(也可以称为“字符串”)。我知道这不会解决他的问题。这里我只是想告诉他,代码没有问题,问题在于代码的逻辑
String str = sc.nextLine();
if (StringUtils.isNumeric(str))
    System.out.println(str);