2

我的程序实际上有问题。实际上我在学校学习(11年级 - 大专)所以请用非常简单的语言解释我。我正在开发一个测验,非常基本的学校项目,所以程序像这样继续......我希望用户通过输入 1-4 的数字来输入他/她的选择。我不希望用户输入字母、字母或特殊字符或任何其他号码。除了1-4。我尝试使用 try 和 catch,但我的程序在抛出异常后停止。我希望程序代码即使在显示错误消息 System.out.println(" Invalid input. Please enter a number between 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(谷歌“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();   
    }
}
}

在您要转换为整数的地方试一下。如果您的代码给出异常,它将进入异常块并处理您希望的值。在这里,我将其设置为 0,您也可以将其设置为 -1。

如果此代码有用或没有帮助,请恢复。

于 2012-11-24T20:18:21.990 回答
0

这是解决此问题的更优雅的解决方案。不涉及尝试捕获。

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 回答