[英]while true try catch nested
I'm new to Java. 我是Java新手。 I want the code to repeat at the point where the user input is the wrong type rather than starting from the beginning. 我希望代码在用户输入错误类型的地方重复,而不是从头开始。 When at "enter b: " or "Enter c: " it goes back to the beginning "Enter a: ". 在“输入b:”或“输入c:”时,它返回到开头的“输入a:”。 I want it to repeat only, where the user input is a, b, c. 我只想重复一次,用户输入是a,b,c。 Thanks in advance. 提前致谢。
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!");
}
}
}
Introduce a method that asks for a number and call it three times. 介绍一种要求输入数字的方法,然后调用它三次。 Inside the method you'll have the while
loop with try-catch
. 在方法内部,您将使用try-catch
进行while
循环。
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!");
}
}
}
You can try by simple null checking if you want as below, this is raw code and may require change 您可以通过以下方法进行简单的空检查尝试,这是原始代码,可能需要更改
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.