如何在java中使用try-and-catch处理异常后恢复代码

如何在java中使用try-and-catch处理异常后恢复代码,java,try-catch,Java,Try Catch,实际上,我的程序有问题。事实上,我在11年级大专学校学习,所以请用非常简单的语言向我解释。我正在开发一个测验,一个非常基本的学校项目,所以项目就这样继续下去。。。。我希望用户通过输入1-4之间的数字来输入他/她的选择。我不希望用户输入字母表、字母或特殊字符或除1-4以外的任何其他编号。我尝试使用try-and-catch,但我的程序在抛出异常后停止。我希望程序代码在显示错误消息System.out.println Invalid input后仍能运行。请输入一个介于1-4之间的数字; 示例程序

实际上,我的程序有问题。事实上,我在11年级大专学校学习,所以请用非常简单的语言向我解释。我正在开发一个测验,一个非常基本的学校项目,所以项目就这样继续下去。。。。我希望用户通过输入1-4之间的数字来输入他/她的选择。我不希望用户输入字母表、字母或特殊字符或除1-4以外的任何其他编号。我尝试使用try-and-catch,但我的程序在抛出异常后停止。我希望程序代码在显示错误消息System.out.println Invalid input后仍能运行。请输入一个介于1-4之间的数字; 示例程序


嘿,这是你可以运行的代码。

在要转换为整数的位置放置一个try-catch。若您的代码给出异常,它将进入异常块并按您的意愿处理值。在这里,我把它设为0,你也可以设为-1


如果此代码有帮助或没有帮助,请返回。

嘿,这是您可以运行的代码。

在要转换为整数的位置放置一个try-catch。若您的代码给出异常,它将进入异常块并按您的意愿处理值。在这里,我把它设为0,你也可以设为-1


如果此代码有帮助或没有帮助,请返回。

程序崩溃的地方如下:

int food1= Integer.parseInt(in.readline()); 
if(c1=1)
{ System.out.println(" Correct answer");
  score=score+10
}
c1不是定义的变量,因此无论用户输入什么,使用它都会导致程序崩溃。你应该用food1替换c1。此外,赋值运算符=,应替换为比较运算符=

查看整数的javadoc谷歌整数javadoc,你会发现

public static int parseInt(String s)
                throws 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");
    }
}

祝你好运

程序崩溃的地方是:

int food1= Integer.parseInt(in.readline()); 
if(c1=1)
{ System.out.println(" Correct answer");
  score=score+10
}
c1不是定义的变量,因此无论用户输入什么,使用它都会导致程序崩溃。你应该用food1替换c1。此外,赋值运算符=,应替换为比较运算符=

查看整数的javadoc谷歌整数javadoc,你会发现

public static int parseInt(String s)
                throws 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");
    }
}

祝你好运

对于这个问题,这里有一个更优雅的解决方案。不涉及试捕

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;
 }

对于这个问题,这里有一个更优雅的解决方案。不涉及试捕

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;
 }

请帮帮我。。。它没有帮助可能我对使用try-and-catch感到困惑,因为我得到了这个错误选择可能还没有初始化请发布包含try-and-catch的代码,我可以直接复制和粘贴,或者简化使用try-and-catch-with-if-else语句的步骤你复制粘贴评论?因为我已经开始选择了。复制粘贴上述代码将正常运行。我也重新上菜了。请帮帮我。。。它没有帮助可能我对使用try-and-catch感到困惑,因为我得到了这个错误选择可能还没有初始化请发布包含try-and-catch的代码,我可以直接复制和粘贴,或者简化使用try-and-catch-with-if-else语句的步骤你复制粘贴评论?因为我已经开始选择了。复制粘贴上述代码将正常运行。我也重新上菜了。请帮帮我。。。它没有帮助可能我对使用try-and-catch感到困惑,因为我得到了这个错误选择可能还没有初始化。请发布包含try-and-catch的代码,我可以直接复制和粘贴,或者使用s简化
关于使用try-and-catch-with-if-else语句的步骤–因此警告,choice可能尚未初始化不应阻止您编译,但答案只是显式初始化它,即:int-choice=0;你需要练习阅读和排除这样的错误请帮助我。。。可能我对使用try-and-catch感到困惑,因为我得到的错误选择可能尚未初始化。请发布包含try-and-catch的代码,我可以直接复制和粘贴,或者简化使用if-else语句的try-and-catch的步骤–因此警告,选项可能尚未初始化,但不应阻止您编译,但答案只是显式初始化它,即:int choice=0;您需要练习阅读和排除这样的错误