如何在尝试try和catch块的同时使用循环进行输入验证,以捕获输入不匹配异常?
这是我的主要方法
import java.util.InputMismatchException;
import java.util.Scanner;
public class labBookFortyThree {
public static void main(String[] args) {
Scanner myInput = new Scanner(System.in);
double circle, rect1, rect2, cyl1, cyl2;
int input = 0;
System.out.println("Press 1 to calc circle, 2 for rect, 3 for cyln");
try {
input = myInput.nextInt();
} catch (InputMismatchException e) {
System.out.println("Please enter a proper value");
}
if (input == 1) {
System.out.println("enter radius");
circle = myInput.nextDouble();
System.out.println("area of circle is " + areas.area(circle));
} else if (input == 2) {
System.out.println("enter length and height");
rect1 = myInput.nextDouble();
rect2 = myInput.nextDouble();
System.out.println("area of rect is " + areas.area(rect1, rect2));
} else if (input == 3) {
System.out.println("enter rad, height");
cyl1 = myInput.nextDouble();
cyl2 = myInput.nextDouble();
int useless = 0;
System.out.println("Area of cyl is " + areas.area(cyl1, cyl2, useless));
}
}
}
这是我的课区
public class areas {
public static double area(double rad) {
double area = 3.14 * (rad * rad);
return area;
}
public static double area(double width, double height) {
double area = width * height;
return area;
}
public static double area(double rad, double height, int useless) {
double area = (3.14 * (rad * rad) * height);
return area;
}
}
我应该在哪里进行输入验证循环?有没有更好的办法?而我该如何在创意中做些什么呢?
代替
try {
input = myInput.nextInt();
} catch (InputMismatchException e) {
System.out.println("Please enter a proper value");
}
一种可能的方法是使用循环并检查您期望的输入(例如int
1到3之间),
int input = 0;
while(input < 1 || input > 3) {
if (myInput.hasNextInt()) {
input = myInput.nextInt();
} else if (myInput.hasNext()) {
System.out.println("Please enter a proper value");
myInput.next();
} else {
System.err.println("No more input");
System.exit(1);
}
}
// input is 1,2 or 3. Or the program ended.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句