2015-11-23 40 views
0

我想創建一個計算器的菜單,其中用戶將輸入1,2,3,4來選擇他們想要的操作#4是該部門。 我試圖讓它當secondN(我要求2個輸入分隔一個空格),這是第二個值是0,它會說「你不能用0除數。請輸入另一個號碼:「並且將允許用戶再次輸入兩個號碼。但是因爲除以零自然會給無窮大,所以我很難完成這個任務。試圖打印內的東西,以便當其中一個輸入爲0時,它顯示的東西

我試過如果如果...其他內部嘗試,但我無法得到它的工作。 我的代碼目前如下。

if(inputInt == 4){ do { 
       System.out.print("Please enter two floats to divide, separated by a space: "); 
       try { firstN = readInput.nextFloat(); 
        secondN = readInput.nextFloat(); 
        break; 
       } 
       catch (final InputMismatchException e) { 
        secondN = readInput.nextFloat(); 
        System.out.println ("You have entered invalid value(s). Please enter valid value(s)."); 
        readInput.nextLine(); 
        continue; 
       } 
       }while (true); 
        System.out.printf("Result of dividing %5.2f by %5.2f is %5.2f", firstN, secondN, firstN/secondN); 
        System.out.println("\n \nPlease press enter to return to the main menu."); 
        Scanner keyboard = new Scanner(System.in); 
        keyboard.nextLine();  

    } 

回答

0

一個快速和廉價的方式來增加這個功能(可能是有點非正統)是在try塊檢查0,並拋出自己的InputMismatchException時。

do { 
    System.out.print("Please enter two floats to divide, separated by a space: "); 
    try { 
     firstN = readInput.nextFloat(); 
     secondN = readInput.nextFloat(); 
     if(secondN == 0) { 
      System.out.println("The denominator cannot be 0."); 
      throw new InputMismatchException(); 
     } 
     break; 
    } catch (final InputMismatchException e) { 
     System.out.println("You have entered invalid value(s). Please enter valid value(s)."); 
     readInput.nextLine(); 
    } 
} while (true); 

有一件事你也應該提防的是你對你的追趕塊內線secondN = readInput.nextFloat();。您可能會進入catch塊,因爲try-block中的語句secondN = readInput.nextFloat();不起作用(因此再次執行該操作會引發另一個異常。)