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

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

ユーザー入力が の場合は、メソッドStringを使用して整数として解析することができます。これは、入力が有効な数値文字列でない場合に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 に答える
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 に答える