2

私は実際に私のプログラムに問題を抱えています。実は私は学校(11年生-短期大学)で勉強しているので、とても簡単な言葉で説明してください。私はクイズ、非常に基本的な学校のプロジェクトを開発しているので、プログラムはこのように進行します...ユーザーに1から4までの数字を入力して自分の選択を入力してもらいたいです。ユーザーにアルファベット、文字、特殊文字、またはその他の番号を入力してほしくない。1-4以外。try and catchを使用してみましたが、例外をスローした後、プログラムが停止します。エラーメッセージSystem.out.println( "無効な入力。1〜4の数字を入力してください");を表示した後でもプログラムコードを実行したい。 サンプルプログラム

import java.io.*;
  import java.lang;
  public class
  { 
   public static void main()throws IOException
   { 
     InputStreamReader read =new InputStreamReader (System.in);
     BufferedReader in =new BufferedReader (read);
     System.out.println(" Select your category");
     System.out.println(" 1. Food");
     System.out.println(" 2. National");
     System.out.println("");
     System.out.println(" Enter your choice"); 
     int choice=Integer.parseInt(in.readLine());
     if(choice==1)//food category
     { 
       int score = 0;
       System.out.println("what are dynamites made?");
       System.out.println("1. peanuts");System.out.println("2. grapes");
       System.out.println("3. flaxseeds");System.out.println("4. fish");
       System.out.println(" Enter your choice");
       int food1= Integer.parseInt(in.readline()); 
      if(c1=1)
      { System.out.println(" Correct answer");
        score=score+10
      }
       else
      { 
      System.out.println(" Wronge answer");
        score=score+0
      }
      //then i have the second question with the same format
     } 
      if(choice==2)//natioanl category with the same format as above
      {//two question with if else statements in them }
     }
}// also help me where to add the try and catch statements
4

3 に答える 3

3

プログラムがクラッシュしている場所は次のとおりです。

int food1= Integer.parseInt(in.readline()); 
if(c1=1)
{ System.out.println(" Correct answer");
  score=score+10
}

「c1」は定義済み変数ではないため、これを使用すると、ユーザーが何を入力してもプログラムがクラッシュします。「c1」を「food1」に置き換える必要があります。また、代入演算子「=」を比較演算子「==」に置き換える必要があります。

Integer の javadoc (google "Integer javadoc") を確認すると、

public static int parseInt(String s)
                throws NumberFormatException

したがって、NumberFormatException をキャッチする必要があります。また、プログラムの実行時にスタック トレースを確認することで、どの例外がどこでスローされたかを確認できます。

例外がスローされるたびに、エラーの後と次の「}」の前のすべてがスキップされます。ほとんどのコードはエラー後に正常に実行されるはずなので、try-catch を小さく保ちたいと考えています。

try {
    int choice=Integer.parseInt(in.readLine());
} catch (NumberFormatException ex) {
    //Not a number
}

変数「choice」は、try の外でアクセスできるようにする必要があるため、try の外で宣言します。

int choice;

try {
    choice=Integer.parseInt(in.readLine());
} catch (NumberFormatException ex) {
    //Not a number
}

ただし、NumberFormatException は、ユーザーが 1 ~ 4 以外の数字を入力したかどうかを通知しません。したがって、独自の検証を追加する必要があります。

int choice;

try {
    choice=Integer.parseInt(in.readLine());
    if(choice<1 || choice>4) ; //Not 1-4
} catch (NumberFormatException ex) {
    //Not a number
}

最後に、入力が有効かどうかを追跡し、必要に応じてループする必要があります。

boolean valid=false;

while(!valid) {

    int choice;

    try {
        choice=Integer.parseInt(in.readLine());
        if(choice<1 || choice>4) valid=false; //Not 1-4
        else valid=true;
    } catch (NumberFormatException ex) {
        //Not a number
        valid=false;
    }

    if(valid) {
         //Handle valid response here
    } else {
         System.out.println(" Invalid input. Please enter a number between 1-4");
    }
}

幸運を!

于 2012-11-24T20:30:20.103 に答える
1

ちょっとここにあなたが実行できるコードがあります。

import java.io.*;

import java.lang.*;

public class TestTryCatch
{ 

public static void main(String args[])
{
    try
    {
        InputStreamReader read =new InputStreamReader (System.in);
        BufferedReader in =new BufferedReader (read);
        System.out.println(" Select your category");
        System.out.println(" 1. Food");
        System.out.println(" 2. National");
        System.out.println("");
        System.out.println(" Enter your choice"); 
        int choice=0;
        try
        {
            choice =  Integer.parseInt(in.readLine());
        }
        catch(Exception e)
        {
            choice=0;
        }
        if(choice==0)
        {
            System.out.println("Invalid Input");         
        }
        if(choice==1)//food category
        { 
            int score = 0;
            System.out.println("what are dynamites made?");
            System.out.println("1. peanuts");System.out.println("2. grapes");
            System.out.println("3. flaxseeds");System.out.println("4. fish");
            System.out.println(" Enter your choice");
            int food1= Integer.parseInt(in.readLine()); 
            if(food1==1)
            { System.out.println(" Correct answer");
            score=score+10;
            }
            else
            { 
                System.out.println(" Wronge answer");
                score=score+0;
            }

        } 
        if(choice==2)
        {
        }
    }
    catch(Exception e)
    {
        e.printStackTrace();   
    }
}
}

整数に変換する場所に try catch を配置します。コードで例外が発生した場合は、例外ブロックに入り、必要に応じて値を処理します。ここでは、-1 を代入できる 0 としています。

このコードが役立つかどうかは元に戻してください。

于 2012-11-24T20:18:21.990 に答える
0

この問題に対するより洗練された解決策を次に示します。try-catch は関係ありません。

import java.io.*;
  import java.lang;
  public class
  { 
     //Compares response to the string representations of all numbers between 1 and numOptions, inclusive. 
     //Returns the matching integer or -1 otherwise.
     public static int parseResponse(String response, int numOptions) 
     {
          for(int i=1;i<=numOptions;i++) {
              if(response.equals(Integer.toString(i))) return i;
          }
          return -1;
     }

     public static void main()throws IOException
     { 
         InputStreamReader read =new InputStreamReader (System.in);
         BufferedReader in =new BufferedReader (read);
         System.out.println(" Select your category");
         System.out.println(" 1. Food");
         System.out.println(" 2. National");
         System.out.println("");
         System.out.println(" Enter your choice");

         //New code
         int choice=-1;
         while(choice==-1) {
             choice=parseResponse(in.readLine(),2);
             if(choice==-1)
             {
                 System.out.println(" Invalid input. Please enter a number between 1-2");
             }
         }


         if(choice==1)//food category
         { 
             int score = 0;
             System.out.println("what are dynamites made?");
             System.out.println("1. peanuts");System.out.println("2. grapes");
             System.out.println("3. flaxseeds");System.out.println("4. fish");
             System.out.println(" Enter your choice");

             //New code
             int food1=-1;
             while(food1==-1) {
                 food1=parseResponse(in.readLine(),4);
                 if(food1==-1)
                 {
                     System.out.println(" Invalid input. Please enter a number between 1-4");
                 }
             }

             if(food1==1)
             { System.out.println(" Correct answer");
               score=score+10
             }
             else
             { 
               System.out.println(" Wronge answer");
               score=score+0
             }
             //then i have the second question with the same format
        } 
        if(choice==2)//natioanl category with the same format as above
        {//two question with if else statements in them 
        }
    }
}// also help me where to add the try and catch statements

わからない場合:

 if(response.equals(Integer.toString(i))) return i;

と同じです

 if(response.equals(Integer.toString(i)))
 {
      return i;
 }
于 2012-11-25T18:03:35.480 に答える