简体   繁体   中英

try catch in a do while loop

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

You need to reset the error variable inside the loop

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

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

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

You probably want to test if there is no error:

}while(error != 1);

or

}while(error == 0);

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.

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(...)

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.

You have to put sc.next(); in the catch so it will clear your scanner variable and it will ask for an input

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM