2016-09-06 9 views
-1
public static void main(String[] args) { 

    { 
     Scanner reader = new Scanner(System.in); 
     System.out.println("Enter your name: "); 
     String n = reader.nextLine(); 
     System.out.println("You chose: " + n); 
    } 

    { 
     Scanner reader = new Scanner(System.in); 
     System.out.println("Enter your age: "); 
     int n = reader.nextInt(); 
     System.out.println("You chose: " + n); 
    } 

    { 
     Scanner reader = new Scanner(System.in); 
     System.out.println("Enter your email: "); 
     String n = reader.nextLine(); 
     System.out.println("You chose: " + n); 
    } 
} 

Enter your ageの下に何か他のものを置くと、入力が正しくないと尋ねることができますか?Javaの不正入力

+0

正しい入力が最初に入力されたことを確認するには、whileループが必要です。あなたがその番号を得るまで、入力のためのプロンプトを続ける。あなたがそれらに慣れていない場合、 'while'ループのチュートリアルを見てください。 – Orin

+0

また、 'nextInt()'は行末の文字を消費しないことに注意してください。詳細については、[this post](http://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo)を参照してください。 –

答えて

0
  1. 文字列のnextLine();と、それほど頻繁に単に一度
  2. ケアを変数スキャナを宣言する必要はありません。空白の問題を提示し、入力がどのような私でないとき不一致入力型の例外がある例外をキャッチする.next();

使用do-while

do 
    { 
    //input 
    } 
    while(condition);//if it is true the condition returns to do otherwise leaves the cycle 

使用ブロックtry{ .. }catch(Exception){..}

をアドバイスこの例では予想される数字のときに文字を入力してください

 Scanner reader = new Scanner(System.in); 
     int n=0; 
     do 
     { 
       System.out.println("Enter your age: "); 
      try { 
       n = reader.nextInt(); 
      } 
     catch (InputMismatchException e) { 
      System.out.print("ERROR NOT NUMBER"); 
      } 

     } 
     while(n<0 && n>100);//in this case if the entered value is less than 0 or greater than 100 returns to do 


     System.out.println("You chose: " + n); 
1

あなたは、次のようdo/while loopInteger.parseInt(String)を使用して、それを解析し、ユーザーが提供する行を取得することができます:

Scanner reader = new Scanner(System.in); 
Integer i = null; 
// Loop as long as i is null 
do { 
    System.out.println("Enter your age: "); 
    // Get the input from the user 
    String n = reader.nextLine(); 
    try { 
     // Parse the input if it is successful, it will set a non null value to i 
     i = Integer.parseInt(n); 
    } catch (NumberFormatException e) { 
     // The input value was not an integer so i remains null 
     System.out.println("That's not a number!"); 
    } 
} while (i == null); 
System.out.println("You chose: " + i); 

https://stackoverflow.com/a/3059367/1997376に基づいてExceptionをキャッチ避けるより良いアプローチを。

Scanner reader = new Scanner(System.in); 
System.out.println("Enter your age: "); 
// Iterate as long as the provided token is not a number 
while (!reader.hasNextInt()) { 
    System.out.println("That's not a number!"); 
    reader.next(); 
    System.out.println("Enter your age: "); 
} 
// Here we know that the token is a number so we can read it without 
// taking the risk to get a InputMismatchException 
int i = reader.nextInt(); 
System.out.println("You chose: " + i); 
関連する問題