首页 > 解决方案 > 如果用户输入数字而不是字符串,JAVA如何编写异常?

问题描述

请解释一下我对 do while 有点困惑。如果我第一次输入城市名称,一切正常。但是如果我输入一个数字,我会收到相应的消息,当我第二次尝试输入城市名称时,它会给出相同的消息.(关于无效数据)

String town=scanner.nextLine();
boolean tryagain = false;

do {
        if (town.charAt(0) >= '0' && town.charAt(0) <= '9'){
            System.out.println("You probably entered an invalid data format");
            scanner.nextLine();
        tryagain = true;}
        else {
            tryagain = false;
        }           
    }while (tryagain);

我也尝试了 try and catch 选项,但如果用户输入数字而不是字符串,我无法编写异常。它不起作用。请帮忙。

try {
    System.out.println("enter the name of the city");
    town = scanner.nextLine();
    
} catch (InputMismatchException e) {
    
    System.out.println ("You probably entered an invalid data format ");
    scanner.nextLine();
}

标签: javaexceptiontry-catch

解决方案


将其放在 try 块中并尝试将其解析为 Integer

   try{
             Integer.parseInt(town)
    }catch(NumberFormatException nfe){
              //this is a string otherwise it would be number
    }

推荐阅读