2012-11-24 69 views
2

我实际上遇到了我的程序问题。其实我在学校学习(11年级 - 大专),所以请用非常简单的语言来解释我。我正在开发一个测验,非常基础的学校项目,所以程序就这样继续下去......我希望用户通过输入1-4的数字输入他/她的选择。我不希望用户输入字母,字母或特殊字符或任何其他编号。除了1-4之外。我尝试使用try和catch,但是我的程序在抛出异常后停止。即使在显示错误信息System.out.println(“输入无效,请在1-4之间输入一个数字”)之后,我想让程序代码运行。 示例程序如何在java中尝试并捕获异常处理后恢复代码

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 

回答

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

谢谢!这真的很有帮助! –

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。

如果此代码有帮助还原,请回复。

+0

请帮我...它没有帮助,也许我感到困惑使用try和catch因为我得到这个错误选择可能还没有初始化请发布代码尝试并捕获它,我可以直接复制和粘贴或简化步骤使用try和catch if else语句 –

+0

hav你是否复制粘贴评论?因为我已经在选择。上面的代码复制粘贴会正常运行。我也反复测试过。 – Javadotnet

+0

请尝试让我知道它是否为你工作 – Javadotnet

3

程序发生崩溃的地方就在这里:

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

“C1”不是一个定义的变量,所以使用它会导致程序,无论用户输入什么崩溃。您应该将“c1”替换为“food1”。此外,赋值运算符“=”应替换为比较运算符“==”。

退房整数的Javadoc(谷歌“整型的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 
} 

我们需要的变量,“选择”是我们尝试的访问之外,让我们拭目以待在我们的尝试之外声明它。

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

祝你好运!

+0

请帮助我...它不帮助,也许我对使用try和catch感到困惑,因为我得到这个错误选择可能还没有初始化请发布代码尝试和赶上在其中我可以直接复制和粘贴或简化步骤使用try和catch if else语句 - –

+0

因此,警告“选择可能尚未初始化”不应阻止您编译,但答案很简单显式初始化它,即:int choice = 0; (你需要练习阅读和排除故障) – NewEndian