0

This code keeps asking the user for double values till the user enters an empty line. When a user enters a non double value such as a string, an Invalid input message is displayed. Currently, even when the user enters an empty line, the invalid input message shows up, and I understand why. What would be the best way to get Invalid input to not show up when I enter a blank line. I'm not sure if there's a way using try-catch or if I just need to use something else.

System.out.println("Type in the polynomials in increasing powers.");
Scanner prompt = new Scanner(System.in);
String input = " ";
double parsed;
int counter = 0;

while (!(input.equals("")) & counter < 10) {
    input = prompt.nextLine();
    try {
        parsed = Double.parseDouble(input);
        expression.addCoefficient(parsed);
        counter++;
    }
    catch (NumberFormatException e) {
        System.out.println("Invalid input");
    }
    
  • You can either write a `tryParseDouble` method that encapsulates the try/catch block, or use [this](https://stackoverflow.com/questions/1102891/how-to-check-if-a-string-is-numeric-in-java). – Robert Harvey May 07 '21 at 00:17

2 Answers2

0
while (counter < 10 && !(input = prompt.nextLine()).equals(""))) {
    try {
        parsed = Double.parseDouble(input);
        expression.addCoefficient(parsed);
        counter++;
    }
    catch (NumberFormatException e) {
        System.out.println("Invalid input");
    }
 }

Note, the test on counter needs to appear first. Once the user has made 10 mistakes, quit asking.

something
  • 174
  • 4
0

You can use the following to skip when the user hits an enter:

public static void main(String[] args) {
        System.out.println("Type in the polynomials in increasing powers.");
        String NEW_LINE = "\n";
        Scanner sc = new Scanner(System.in);
        String input = sc.next();
        double parsed;
        int counter = 0;

        while (counter < 10) {

            if (input.equals(NEW_LINE)){
                continue;
            }
            try {
                parsed = Double.valueOf(input);
                //expression.addCoefficient(parsed);
                System.out.println(parsed);
                counter++;
            }
            catch (NumberFormatException e) {
                System.out.println("Invalid input");
            }
        }
Yati Sawhney
  • 1,372
  • 1
  • 12
  • 19