我是Java的新手。我希望代码在用户输入错误类型的位置重复,而不是从头开始。当在“输入b:”或“输入c:”时,它会回到开头“输入:”。我希望它只重复,用户输入是a,b,c。提前谢谢。
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
boolean itsANumber = true;
while (itsANumber)
{
System.out.print("Enter a: ");
try
{
a = Double.parseDouble(sc.nextLine());
System.out.print("Enter b: ");
try
{
b = Double.parseDouble(sc.nextLine());
System.out.print("Enter c: ");
try
{
c = Double.parseDouble(sc.nextLine());
if (a == 0)
{
aZero();
} else
{
aNotZero();
}
} catch (NumberFormatException nfe)
{
System.out
.println("That's not a number, please try again!");
}
} catch (NumberFormatException nfe)
{
System.out
.println("That's not a number, please try again!");
}
} catch (NumberFormatException nfe)
{
System.out.println("That's not a number, please try again!");
}
}
}
答案 0 :(得分:3)
介绍一个要求输入数字的方法并将其调用三次。在方法内,您将while
循环try-catch
。
public static void main(String... args) {
Scanner sc = new Scanner(System.in);
double
a = askForDouble(sc, "a"),
b = askForDouble(sc, "b"),
c = askForDouble(sc, "c");
}
static double askForDouble(Scanner sc, String varName) {
for (;/*ever*/;) {
System.out.format("Enter %s: ", varName);
System.out.flush();
try {
return Double.parseDouble(sc.nextLine());
} catch (NumberFormatExcetpion() {
System.out.println("That's not a number, please try again!");
}
}
}
答案 1 :(得分:0)
您可以尝试通过简单的空值检查,如果您需要,如下所示,这是原始代码,可能需要更改
Double a = null;
Double b = null;
Double c = null;
Scanner sc = new Scanner(System.in);
while(true){
if(a != null){
System.out.println("Enter a :");
a = readFromInStream(sc, "a");
if(a == null) continue;
}
if(b != null){
System.out.println("Enter b :");
b = readFromInStream(sc, "b");
if(b == null) continue;
}
if(c != null){
System.out.println("Enter c :");
c = readFromInStream(sc, "c");
if(c == null) continue;
}
if(a != null && b != null && c != null){
break;
}
}
private Double readFromInStream(Scanner sc, String varStr){
Double temp = null;
try
{
temp = Double.parseDouble(sc.nextLine());
}catch(NumberFormatException e){
System.out.println("Invalid value for :"+varStr);
}
return temp;
}