6

在我的程序中,我想要用户输入一个整数。我希望在用户输入不是整数的值时显示错误消息。我怎样才能做到这一点。我的程序是找到圆的面积。用户将在其中输入半径值。但是,如果用户输入一个字符,我希望显示一条消息说输入无效。

这是我的代码:

int radius, area;
Scanner input=new Scanner(System.in);
System.out.println("Enter the radius:\t");
radius=input.nextInt();
area=3.14*radius*radius;
System.out.println("Area of circle:\t"+area);
4

6 回答 6

25

如果您使用 获取用户输入Scanner,您可以执行以下操作:

if(yourScanner.hasNextInt()) {
    yourNumber = yourScanner.nextInt();
}

如果不是,则必须将其转换为int并捕获NumberFormatException

try{
    yourNumber = Integer.parseInt(yourInput);
}catch (NumberFormatException ex) {
    //handle exception here
}
于 2013-11-12T09:14:33.563 回答
6

你可以试试这个方法

 String input = "";
 try {
   int x = Integer.parseInt(input); 
   // You can use this method to convert String to int, But if input 
   //is not an int  value then this will throws NumberFormatException. 
   System.out.println("Valid input");
 }catch(NumberFormatException e) {
   System.out.println("input is not an int value"); 
   // Here catch NumberFormatException
   // So input is not a int.
 } 
于 2013-11-12T09:18:50.453 回答
1
        String input = "";
        int inputInteger = 0;
        BufferedReader br    = new BufferedReader(new InputStreamReader (System.in));

        System.out.println("Enter the radious: ");
        try {
            input = br.readLine();
            inputInteger = Integer.parseInt(input);
        } catch (NumberFormatException e) {
            System.out.println("Please Enter An Integer");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        float area = (float) (3.14*inputInteger*inputInteger);
        System.out.println("Area = "+area);
于 2013-11-12T09:29:31.250 回答
1

您可以使用 try-catch 块来检查整数值

例如:

字符串形式的用户输入

try
{
   int num=Integer.parseInt("Some String Input");
}
catch(NumberFormatException e)
{
  //If number is not integer,you wil get exception and exception message will be printed
  System.out.println(e.getMessage());
}
于 2013-11-12T09:18:47.413 回答
1

使用 Integer.parseIn(String),您可以将字符串值解析为整数。如果输入字符串不是正确的数字,您还需要捕获异常。

int x = 0;

try {       
    x = Integer.parseInt("100"); // Parse string into number
} catch (NumberFormatException e) {
    e.printStackTrace();
}
于 2013-11-12T09:12:50.710 回答
1

如果用户输入是 aString那么您可以尝试使用方法将其解析为整数,当输入不是有效的数字字符串时parseInt抛出:NumberFormatException

try {

    int intValue = Integer.parseInt(stringUserInput));
}(NumberFormatException e) {
    System.out.println("Input is not a valid integer");
}
于 2013-11-12T09:13:13.490 回答