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");
}
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.
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");
}
}
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.