2016-01-24 51 views
0

我在写一个简单的分割程序。用户输入分子和分母。如果用户没有输入整数,分子和分母将抛出异常。另外,如果用户输入0,分母应该抛出异常。错误应该告诉用户每次他们做错了什么,并继续循环直到输入正确的输入。然后它应该在值正确时退出。多个用户输入的多个异常处理

为什么当用户输入不正确的分母时,它会再次请求分子?

import java.util.InputMismatchException; 
import java.util.Scanner; 

public static void main(String[] args) 
{ 
    // TODO Auto-generated method stub 
    System.out.printf("Welcome to Division \n"); 

    Scanner div = new Scanner(System.in); 
    boolean continueLoop = true; 
do 
{ 
    try 
    { 
    System.out.println("\nEnter a numerator:\n"); 
    int num1 = div.nextInt(); 
    System.out.println("Enter a denominator:"); 
    int num2 = div.nextInt(); 

    int result = quotient(num1, num2); 
    System.out.printf("The Answer is: %d/%d = %d%n",num1,num2,result); 
    } 
    catch(InputMismatchException inputMismatchException) 
    { 
     System.err.printf("\n Exception \n",inputMismatchException); 
     div.nextLine(); 
     System.out.printf("You must enter integers"); 

    } 
    catch(ArithmeticException arithmeticException) 
    { 
     System.err.printf("\n Exception \n",arithmeticException); 
     System.out.printf(" Zero is an invalid entry"); 
    } 
} while (continueLoop); 

    System.out.printf("\n GOODBYE \n"); 
} 

} 
+0

你有一个单一的循环,所以它会通过所有步骤每次运行。在调试器中逐步运行代码并亲自查看。 –

回答

1

您捕捉到的异常,但continueLoop的值永远不会更新

0

你需要一个嵌套while循环了点。这是你的斜体问题的答案。它再次要求分子,因为你的while循环从输入分子开始。

+0

我试着添加一个if语句,但它不会编译。 – MsSheta

+0

你必须开始2做循环。我在C++中这样做。首先,开始做,并尝试输入分子。之后是一个捕获。那么在那里呢,再输入一个分母。然后另一个捕获。现在你已经写完美的2,而最后的陈述。首先是分母输入,如果你有正确的while语句,循环会回到那个点。第二次将再次从顶部开始循环。现在 - 如果你试图错误的分子输入,它必须再次跳回顶部。 –

0

如果你想程序停止的时候抛出一个异常,你可以这样做:

 try { 
      do { 

       System.out.println("\nEnter a numerator:\n"); 
       int num1 = div.nextInt(); 
       System.out.println("Enter a denominator:"); 
       int num2 = div.nextInt(); 

       int result = quotient(num1, num2); 
       System.out.printf("The Answer is: %d/%d = %d%n", num1, num2, result); 
      } while (continueLoop); 
     } catch (ArithmeticException arithmeticException) { 
      System.err.printf("\n Exception \n", arithmeticException); 
      System.out.printf(" Zero is an invalid entry"); 
     } catch (InputMissMatchException inputMismatchException) { 
      System.err.printf("\n Exception \n", inputMismatchException); 
      div.nextLine(); 
      System.out.printf("You must enter integers"); 

     } 
     System.out.printf("\n GOODBYE \n"); 

但现在你抓住是while循环内,并且你的程序异常打印信息,并再次继续。如果你想继续这种方式,你可以在异常后输入一个验证,如果这个人想继续运行你的程序或类似的东西,你可以连接到你的continueLoop

+0

谢谢。但我希望它建议用户输入分母的整数,而不是全部开始 – MsSheta

+0

然后您可以创建两个单独的try catch块,并且带分母的块应该处于do-while循环,直到成功输入。你可以为一个有效的输入做一个布尔值,并在catch块中向用户显示你的消息make valid = false。当它进入while条件时,它会看到布尔值为false,并且会再次返回分母消息。 –