2

i added a while loop so that if the user enters an invalid value, the code will re-prompt the user to put in a valid value. but the when the user puts in an invalid value, the code goes in an infinite loop. any help would be much appreciated !!

public static void main(String[] args) {
    System.out.println("Usage : enter a, b, & c from a quadratic equation");
    System.out.println("        aX^2 +bX + c = 0");
    System.out.println("        Result will be 2 values for X");

    Scanner in = new Scanner(System.in);
    double a = 0;
    double b = 0;
    double c = 0;
    double x1 = 0 ;
    double x2 = 0;
    double discriminant = 0;

    System.out.println("Please enter values for a , b, and c ");

    while(true){
        try
        {
            a = in.nextDouble();
            break;
        }
        catch(java.util.InputMismatchException E)
        {
            System.out.println("wrong input, try again");

        }
    }
    while(true){
        try
        {
            b = in.nextDouble();
            break;
        }
        catch(java.util.InputMismatchException E)
        {

            System.out.println("wrong input, try again");
        }
    }
    while(true){
        try
        {
            c = in.nextDouble();
            break;
        }
        catch(java.util.InputMismatchException E)
        {

            System.out.println("wrong input, try again");
        }
    }
    //x1 = (-b+sqrt(b*b - 4ac))/2a
    //x2 = (-b+sqrt(b*b - 4ac))/2a

    discriminant = b*b -4.0 * a * c;
    x1 = (-b + Math.sqrt(discriminant))/2.0*a;
    x2 = (-b - Math.sqrt(discriminant))/2.0*a;

    System.out.println("The two values for X are " + x1 + " and "  + x2);
}
MadConan
  • 3,749
  • 1
  • 16
  • 27

2 Answers2

5

When the nextDouble method throws an InputMismatchException, it doesn't consume the bad input that caused the exception.

This method will throw InputMismatchException if the next token cannot be translated into a valid double value. If the translation is successful, the scanner advances past the input that matched.

You should advance beyond the bad input, or else nextDouble will continue to read the same bad input over and over again.

Consume the bad input and discard it with in.next(), e.g.:

catch(java.util.InputMismatchException E)
{
    in.next();
    System.out.println("wrong input, try again");
}
rgettman
  • 176,041
  • 30
  • 275
  • 357
0

The above suggested will work. However, you need to check the discriminant. You are not handling the case when discriminant is less than zero. You will get NaN as the roots if the discriminant is negative. Please refer to Math.sqrt() documentation for more details.

//x1 = (-b+sqrt(b*b - 4ac))/2a
//x2 = (-b+sqrt(b*b - 4ac))/2a

discriminant = b*b -4.0 * a * c;
x1 = (-b + Math.sqrt(discriminant))/2.0*a;
x2 = (-b - Math.sqrt(discriminant))/2.0*a;
gaurav gupta
  • 147
  • 3