java - 如何在 Java 中使用 try 和 catch 进行异常处理后恢复代码

标签 java try-catch

我的程序实际上遇到了问题。实际上我在学校学习(11年级-大专)所以请用非常简单的语言解释我。我正在开发一个测验,一个非常基本的学校项目,所以程序像这样进行......我希望用户通过输入 1-4 的数字来输入他/她的选择。我不希望用户输入字母、字母或特殊字符或任何其他数字。除了1-4之外。我尝试使用 try 和 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

最佳答案

你的程序崩溃的地方在这里:

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
}

我们需要在 try 之外访问变量“choice”,因此我们将在 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");
    }
}

祝你好运!

关于java - 如何在 Java 中使用 try 和 catch 进行异常处理后恢复代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13544871/

相关文章:

javascript - 在 firebase onCall 云函数上使用 async/await 内的 try/catch 进行错误处理

java - 在双数组中尝试并捕获未按我的预期工作

javascript - 使用嵌套的try/catch block 时错误的错误处理

c++ - 在 C++ 中捕获 const char* 异常

java - Flink + Kafka + JSON - Java 示例

java - Maven 模型<modelVersion> 版本控制?

python - 在 try/except block 中创建变量是否被认为是一种不好的做法?

java - 通常,当 java 返回 "The parameter is incorrect"时,这意味着什么

java - 将 gradle 应用程序部署到 Heroku

java - Elasticsearch 全局搜索对多个索引的不同过滤器