首页 > 解决方案 > 如何仅对字符串值设置异常?

问题描述

我正在接受用户的输入,它应该只是字符串,但代码没有按我预期的那样工作。这是我的代码`

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);
`

如果我给出的整数值比它应该再次询问但这里它正在打印整数值。也没有特殊字符

标签: javastringexceptionexception-handling

解决方案


如果你试图直接解析整数,那么你会得到一个更有意义的异常来捕获。

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

推荐阅读