try catch in a do while loop

别等时光非礼了梦想. 提交于 2020-01-07 06:52:11

问题


The program asks for the user input for the double num 1 and double num 2 and if there is an exception I want it to ask again for the input of num 1 and num 2

public static void main (String[] args) {
    Scanner sc = new Scanner(System.in);
    double num1, num2;
    int error = 0;
    int text;
    System.out.print("Enter 4 ");
        text = sc.nextInt();

    do{

        try{

    if(text == 4){
            System.out.print("Enter number 1: ");
            num1 = sc.nextDouble();
            System.out.print("Enter number 2: ");
            num2 = sc.nextDouble();
            double quotient = num1/num2;
            System.out.println("The Quotient of "+num1 + "/" +num2+ " = "+quotient);
            }
        }catch(Exception ex){ 
            System.out.println("You've entered wrong input");
                error = 1;
        }                                  

          }while(error == 1);
}

then when I try the code if it will catch the exceptions by inputing string in the num1 or num 2 I'm having this infinite loop : Enter number 1: You've entered wrong input Enter number 1: You've entered wrong input Enter number 1: You've entered wrong input Enter number 1: You've entered wrong input Enter number 1: You've entered wrong input


回答1:


You need to reset the error variable inside the loop

do {
    error = 0;
    //...
} while(error == 1);



回答2:


It is not necessary to utilize exception handling. Just use Scanner.hasNextDouble() method to find out if actual user input is double, otherwise continue the cycle.

package com.company;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        double num1, num2;
        num1 = readDouble(1, sc);
        num2 = readDouble(2, sc);
        double quotient = num1/num2;
        System.out.println("The Quotient of " + num1 + "/" + num2 + " = " + quotient);
    }

    private static double readDouble(int i, Scanner sc) {
        while (true) {
            System.out.print("Enter number " + i + ": ");
            if (!sc.hasNextDouble()) {
                System.out.println("You've entered wrong input");
                sc.next();
                continue;
            }
            break;
        }
        return sc.nextDouble();
    }
}



回答3:


Its in C# but relatively similar :)

public class Program
{
  private static double ReadUserInput (string message) 
  {
    // This is a double
    // The '?' makes it nullable which is easier to work with
    double? input = null;

    do 
    {
      // Write message out
      Console.Write(message);
      // Read answer
      var inputString = Console.ReadLine();
      // Temp variable for the number
      double outputNumber = 0;
      // Try parse the number
      if (double.TryParse(inputString, out outputNumber))
      {
        // The number was parsable as a double so lets set the input variable
        input = outputNumber;
      }
      else
      {
        // Tell the user the number was invalid
        Console.WriteLine("Sorry bud, but '" + inputString + "' is not a valid double");
      }
    } 
    while (input == null); // Keep running until the input variable is actually set by the above

    // Return the output
    return (double)input;
  }

  public static void Main()
  {
    // Read a number
    var num1 = ReadUserInput("Enter number 1:");
    // Read another number
    var num2 = ReadUserInput("Enter number 2:");
    // Show the calculation
    Console.WriteLine("Answer: " + (num1*num2));
  }
}

Demo

And for the actual code (in JAVA):

public class JavaFiddle 
{
  public static void main (String[] args) 
  {
    // Read a number
    Double num1 = ReadUserInput("Enter number 1:");
    // Read another number
    Double num2 = ReadUserInput("Enter number 2:");
    // Show the calculation
    System.out.println("Answer: " + (num1*num2));
  }

  public static Double ReadUserInput (String message) 
  {
    java.util.Scanner inputScanner = new java.util.Scanner(System.in);
    Double input = null;

    do 
    {
      // Write message out
      System.out.println(message);
      // Read answer
      String inputString = inputScanner.nextLine();
      try 
      {
        // Try parse the number
        input = Double.parseDouble(inputString);
      } 
      catch (NumberFormatException e) 
      {
        // Tell the user the number was invalid
        System.out.println("Sorry bud, but '" + inputString + "' is not a valid double");
      }
    } 
    while (input == null); // Keep running until the input variable is actually set by the above

    // Return the output
    return input;
  }
}



回答4:


You probably want to test if there is no error:

}while(error != 1);

or

}while(error == 0);



回答5:


You'll need a method for the input which calls itself, if the input is invalid.

double getInput(Scanner sc) {
    try {
        double num = sc.nextDouble();
        return num;
    } catch(Exception ex) { 
        System.out.println("You've entered wrong input");
        return getInput(sc);
    }    
}

And call this method twice in your other method.




回答6:


it may look ugly , but here is a way to do it

  do
  {
    if(...)
    {

      boolean successReading = false;
      while(!successReading)
      {
        try
        {
          System.out.print("Enter number 1: ");
          num1 = sc.nextDouble();
          System.out.print("Enter number 2: ");
          num2 = sc.nextDouble();

          successReading = true;

          double product = num1*num2;
        }
        catch(Exception e)
        {
          successReading = false;  
        }
      }

    }
  }while(...)



回答7:


You need to add sc.next(); inside catch block.

nextDouble method doesn't clear buffer in case of exception. So next time you invoke it you get same error because old input is still in buffer.

Also you need to reset your error flag in the beginning of the loop.



来源:https://stackoverflow.com/questions/45348919/try-catch-in-a-do-while-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!