public class Test1 {我这样,输入如果用字母的话就直接死循环了,求教
public void main(String... args) {
Scanner scanner = new Scanner(System.in);
double a, b, c;
a = b = c = 0;
boolean isWrongInput = true;
do {
try {
System.out.print("Please input a,b and c:");
a = scanner.nextDouble();
b = scanner.nextDouble();
c = scanner.nextDouble();
isWrongInput = false;
} catch (InputMismatchException e) {
System.out.println("Wrong input!Please try again.");
scanner.reset();
} catch (Exception e) {
e.printStackTrace();
throw e;
}
} while (isWrongInput == true);
double delta = b * b - 4 * a * c;
double x1, x2;
if (delta == 0) {
x1 = x2 = (-b) / (2 * a);
System.out.println("x1=x2=" + x1);
} else if (delta > 0) {
x1 = (-b + Math.sqrt(delta)) / (2 * a);
x2 = (-b - Math.sqrt(delta)) / (2 * a);
System.out.println("x1=" + x1);
System.out.println("x2=" + x2);
} else {
double real, imagine;
real = -b / (2 * a);
imagine = Math.sqrt(-delta) / (2 * a);
System.out.printf("x1=%s\nx2=%s\n",
"" + real + "+" + imagine + "i", "" + real + "-" + imagine
+ "i");
}
}
}
------解决思路----------------------
把scanner = new Scanner(System.in);拿到do-while循环里面去
------解决思路----------------------
先用hasNextDouble()判断一下,再nextDouble()
------解决思路----------------------
scanner.reset();改为scanner.nextLine();