2013-02-26 106 views
0

我通过使用try/catch块来掌握错误捕获的基本知识,但是我的陷印方法使用户在输入无效字符后重新启动程序。错误捕获/异常处理

有人可以演示如何在允许程序运行的同时制作有效的错误陷阱吗?

代码:

import java.io.*; //Input/Output command; this part is ESSENTIAL 

class FindingTheSurfaceAreaOfAPyramid2 
{ 
    public static void main (String[] args) throws IOException 
    { 
     BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in)); //Loading the Text Box 

     //Defining variables and string 'nicknames' 
     String stringBaseLength, stringBaseWidth, stringTriangleHeight; //named strings for organization's sake 
     double convertToNumL, convertToNumW, convertToNumH, total1, total2, total3; //'double' is nessesary for decimal answers as they commonly happen, using 'int' will round the result; inaccurate! 
     //used in 'if' statements 
     boolean realNumber = true; 
     boolean realNumber2 = true; 
     boolean realNumber3 = true; 

     //First message and notice 
     System.out.println ("Note: This program is compatible with ONLY rectangular based pyramids."); 

     //Question 1: Units 
     System.out.println ("First off, what unit is this pyramid in? (ex. cm, mm, in, ft. etc.)"); 
     String Units = myInput.readLine(); 

     //Question 2: Length 
     System.out.println ("1) Please enter the length of the base."); 
     stringBaseLength = myInput.readLine(); 
     try 
     { 
      Integer.parseInt (stringBaseLength); 
      System.out.println ("Your base length is " + stringBaseLength + " " + Units + "."); //this line is restating the the input as well as the unit of measurement 
     } 
     catch (NumberFormatException e) 
     { 
      //If they catch anything other than numbers, it would tell the user 
      System.out.println ("That was either a smart remark, a negative number or jibberish."); 
      System.out.println ("As a consequence, you have to restart the program."); 
      realNumber = false; 


     } 
     if (realNumber) 
     { 
      //Question 3: Width 
      System.out.println ("2) Please enter the width of the base"); 
      stringBaseWidth = myInput.readLine(); 


      try 
      { 
       Integer.parseInt (stringBaseWidth); 
       System.out.println ("Your base width is " + stringBaseWidth + " " + Units + "."); 

      } 
      catch (Exception e) 
      { 
       System.out.println ("That was either a smart remark, a negative number or jibberish."); 
       System.out.println ("As a consequence, you have to restart the program."); 
       realNumber2 = false; 

      } 
      if (realNumber2) 
      { 
       //Question 4: Height 
       System.out.println ("3) Please enter the height of the triangle face."); 
       stringTriangleHeight = myInput.readLine(); 

       try 
       { 
        Integer.parseInt (stringTriangleHeight); 
        System.out.println ("Your triangle height is " + stringTriangleHeight + " " + Units + "."); 
       } 
       catch (Exception e) 
       { 
        System.out.println ("That was either a smart remark, a negative number or jibberish."); 
        System.out.println ("As a consequence, you have to restart the program."); 
        realNumber3 = false; 
       } 
       if (realNumber3) 
       { 

        //Converting the input to 'double' to express the answer(s) in decimal format 
        convertToNumH = Double.parseDouble (stringTriangleHeight); 
        convertToNumL = Double.parseDouble (stringBaseLength); 
        convertToNumW = Double.parseDouble (stringBaseWidth); 
        total1 = convertToNumL * convertToNumW;   //base area, length x width 
        total2 = convertToNumL * convertToNumH/2;  //triangle area using sidelength 'length', base x height/2 
        total3 = convertToNumW * convertToNumH/2;  //triangle area using sidelength 'width , base x height/2 

        //Calculations and concluding sentences 
        System.out.println ("The area of the triangle with base length " + convertToNumL + " cm is " + total2 + Units + "^2."); 
        System.out.println ("The area of the triangle with base length " + convertToNumW + " cm is " + total3 + Units + "^2."); 
        System.out.println ("The base area is " + total1 + " " + Units + "^2."); 
        System.out.println ("The total surface area is " + (total1 + total2 + total2 + total3 + total3) + " " + Units + "^2."); 
       } 
      } 
     } 
    } 
} //end 
+3

代码重复是你的敌人。代码重复是你的敌人。代码重复是...哦,等等。笑话分开:请提取阅读输入到一种方法的说明...错误信息很有趣,我很欣赏这一点。但读3次就像听同样的笑话3次。修改更糟糕...... – ppeterka 2013-02-26 19:39:52

+2

你需要添加一个循环,像'while(entryNotValid){askForANumber(); }',或'while(true){askForANumber();}打破; //只有在前一行没有被抛出的时候达到}'... – assylias 2013-02-26 19:40:45

回答

4

你张贴了大量的代码,但是对于一个错误之后持续一个模式是相当简单的。在伪代码:

boolean validInput = false; 
while (!validInput) { 
    // Read some input from the user 
    // If it's of the right format, set validInput to true 
    // Else print an error message, and don't change validInput 
} 

循环将继续执行,直到用户输入有效的东西(或杀死的程序,当然)。

0

您需要循环回来,直到用户进入实数

boolean realNumber = false; 
     while(!realNumber) 
     { 

    BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in)); //Loading the Text Box 

      //Defining variables and string 'nicknames' 
      String stringBaseLength, stringBaseWidth, stringTriangleHeight; //named strings for organization's sake 
      double convertToNumL, convertToNumW, convertToNumH, total1, total2, total3; //'double' is nessesary for decimal answers as they commonly happen, using 'int' will round the result; inaccurate! 
      //used in 'if' statements 

      boolean realNumber2 = true; 
      boolean realNumber3 = true; 

      //First message and notice 
      System.out.println ("Note: This program is compatible with ONLY rectangular based pyramids."); 

      //Question 1: Units 
      System.out.println ("First off, what unit is this pyramid in? (ex. cm, mm, in, ft. etc.)"); 
      String Units = myInput.readLine(); 

      //Question 2: Length 
      System.out.println ("1) Please enter the length of the base."); 
      try 
        { 
         Integer.parseInt (stringBaseLength); 
         System.out.println ("Your base length is " + stringBaseLength + " " + Units + "."); //this line is restating the the input as well as the unit of measurement 
realNumber = true; 
        } 
        catch (NumberFormatException e) 
        { 
         //If they catch anything other than numbers, it would tell the user 
         System.out.println ("That was either a smart remark, a negative number or jibberish."); 
         System.out.println ("As a consequence, you have to restart the program."); 
         realNumber = false; 


        } 
     } 
+0

你需要一个'realNumber = true;'某处...... – assylias 2013-02-26 19:41:26

+0

你也不需要在循环中创建'BufferedReader'。 – 2013-02-26 21:14:34

0

您需要重构代码并删除重复。 你的代码,如果你比较下面是很多messier,并容易在他们的错误。 根据需要和可以重复使用的功能来缩小功能。重用应该是重中之重。你如何消除不必要的步骤?

public class Test{ 

static String Units=null; 
static BufferReader myInput 
public static void main (String[] args){ 
//Your Main function 
//Initialize the BufferReader and Read the UNITS 
// Sysouts with your questions 
    convertToNumL=readDimension(); 
// Sysouts with your questions 
    convertToNumW=readDimension(); 
// Sysouts with your questions 
    convertToNumH=readDimension(); 

    //Your Calculations 

    } 

    public static Double readDimension() 
    { 
     String temp=null; 
     while(true) { 

      temp=myInput.readLine(); 
      while(verifyDimension(temp)){ 

      return Double.parseDouble(temp); 

      } 

     } 


    }  

    public static boolean verifyDimension(String temp){ 

    boolean verify=true; 

     try{ 

     Double.parseDouble(temp) ; 

     }catch(NumberFormatException e){ 

     verify=false; 

     //Your Statements 
     } 
     return verify; 

    }    


} 
+0

我不一定理解这种方法,我应该提到我在11年级学习计算机proraming/science的入门课程。 – 2013-02-28 00:21:18