[英]How to resume code even after exception handling with try and catch in java
我的程序实际上遇到了麻烦。 实际上,我在学校(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
程序崩溃的位置在这里:
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”在我们的尝试之外可以访问,因此我们将在我们的尝试之外进行声明。
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 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();
}
}
}
在要转换为Integer的位置放置一个try catch。 如果您的代码给出了异常,它将进入异常块并根据需要处理值。 在这里,我将其设置为0,您也可以设置-1。
如果此代码是否有用,请还原。
这是解决此问题的更优雅的方法。 不涉及尝试捕获。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.