2017-03-27 10 views
0

私は、ユーザーが自分の名前やものを入力できるプログラムを持っています。その大規模な試し括弧isnised。最後に、ユーザが数字の代わりに文字を入力したときにキャッチがあります。無効な入力を警告します。無効な3倍の場合、プログラムが終了します。tryとcatchブロック内で入力検証を行うにはどうすればよいですか?

これまでのところ私はこれを持っています。私はunnecesarryコードの一部をommitedが、重要な部分は、ちょうど試みで、あなたのオプションの下部に、他を追加する必要がループ

public static void main(String[] args) throws FileNotFoundException { 
    try{ 
     Scanner input = new Scanner(System.in); 

    String input_option = "1"; 

    // calling option method 
     print_options(); 
     int attempt= 0; 
      boolean authenitcated = false; 
do{ 
      input_option = input.nextLine(); 

     if (input_option.equals("0")) { 

      System.out.println("Enter your first name "); 
      String firstnameopt0 = input.nextLine(); 

      System.out.println("Enter your last name "); 
      String lastnameopt0 = input.nextLine(); 

      type.println("Annual Income: " + income); 
      type.println("Tax: " + opt0tax); 
      myfile.exists(); 
      type.close(); 
     } 

     else if (input_option.equals("1")) { 
      System.out.println("Enter your first name "); 
      String firstnameopt1 = input.nextLine(); 


      type.close(); 
     } 

     else if (input_option.equals("2")) { 
      System.out.println("Enter your first name "); 
      String firstnameopt2 = input.nextLine(); 


      myfile.exists(); 
      type.close(); 
     } 

     //extra_options(); 


    input.close(); 
    catch(InputMismatchException exi){ 
     System.out.println("you must enter a double"); 
     attempt++; 
    } 
}while(attempts < 3 && authenticated == false) 
    } 
+0

あなたはオプションでelseステートメントが欠落しているたとえばinputOptionは4、または10 – Beri

+0

スキャナになるとき、選択.nextLineは常に文字列を返します。 InputMismatchException(IME)がスローされることはありません。 –

答えて

0
  • は、一部を選択しながら行います。
  • これはint型にキャストすることをお勧めします。なぜなら、ユーザーはリードスペースでゼロを入力できますが、これはまだ有効です。
  • 次にfinallyブロック(近くにすべて閉鎖可能なリソース)でキャッチした後、ファイルを閉じ

    int attempt = 0; 
    boolean authenticated = false; 
    do { 
        input_option = input.nextLine(); 
        try { 
         Integer option = Integer.valueOf(input_option); 
         switch (option) { 
          case 0: 
           System.out.println("Enter your first name "); 
           String firstnameopt0 = input.nextLine(); 
    
           System.out.println("Enter your last name "); 
           String lastnameopt0 = input.nextLine(); 
           break; 
          case 1: 
           System.out.println("Enter your first name "); 
           String firstnameopt1 = input.nextLine(); 
           break; 
          case 2: 
           System.out.println("Enter your first name "); 
           String firstnameopt2 = input.nextLine(); 
           break; 
          default: 
           attempt++; 
           System.out.println("you must enter a int"); 
         } 
    
        } catch (Exception ex) { 
         System.out.println("you must enter a int"); 
         attempt++; 
        } 
    } while (attempt < 3 && authenticated == false); 
    
関連する問題