1

Im trying to write a code that will read a character from the user. If they enter "y" it will perform the loop and calculate a square root. My square root function works fine. I need the loop to run until something other than "y" is entered. I keep getting this error

Exception in thread "main" java.lang.AssertionError: Violation of: input is in double format at components.simplereader.SimpleReaderSecondary.nextDouble(Unknown Source) at Newton2.main(Newton2.java:58)

This is my code

    while (true) {
        out.print("Enter 'y' to calculate a square root: ");
        char a = in.read();
        if (a == 'y') {
            out.print("Enter a number to take square root of: "); //prompt the user
            double x = in.nextDouble(); //input a value to take the root of
            double answer = sqrt(x); //use the sqrt method to evaluate
            out.println("Estimate of square root: " + answer); //print the result
        } else {
            break;
        }
    }

    /*
     * Close input and output streams
     */
    in.close();
    out.close();
}

1 Answers1

0

The likely problem is that you're inputting the number on the next line, but because you previously only read a single char, the number parser is choking on the newline character. Try this:

char a = in.read();
in.nextLine();  // move cursor to the next line

Related: Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods

Community
  • 1
  • 1
shmosel
  • 42,915
  • 5
  • 56
  • 120