Try to catch in a do while loop

The program asks for user input for double num 1 and double num 2 and if there is an exception I want it to ask again for number 1 and number 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 to execute the code, if it catches exceptions by typing a string in num1 or num 2, I have 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

0


source to share


7 replies


You need to reset the variable error

inside the loop



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

      

+3


source


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

      

+1


source


There is no need to use exception handling. Just use the method Scanner.hasNextDouble()

to see if the actual user input is double, otherwise continue looping.

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

      

+1


source


You probably want to check if there is an error:

}while(error != 1);

      

or

}while(error == 0);

      

0


source


You will need an input method that 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 a different way.

0


source


it may look ugly, but here's 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(...)

      

0


source


You need to add sc.next();

inside the block catch

.

nextDouble

the method does not clear the buffer in case of an exception. So the next time you call it you will get the same error because the old input is still in the buffer.

Also you need to reset your flag error

at the beginning of the loop.

0


source







All Articles