gpt4 book ai didi

java - 需要一个不满足的 if 语句来转到代码开头

转载 作者:行者123 更新时间:2023-11-30 05:29:05 27 4
gpt4 key购买 nike

我正在尝试设置一些 if 语句,以确保用户输入不会超出我设置的范围(如果我希望 if 语句将它们返回到主代码的开头)。

String animal = JOptionPane.showInputDialog("Enter In Animal Name"); // Asking for user to enter a animal
String fruit = JOptionPane.showInputDialog("Enter In A Fruit Name"); // Asking user to enter a fruit
int days = Integer.parseInt(JOptionPane.showInputDialog("Enter In How Many Days Between 1 And 10"));
// Above integer is asking the user to enter the amount of days.

// Below if statements are basically error checking to ensure the user stays between the
// range asked for when they are asked to enter in days between 1 and 10.

if (days <= 0) { // Ensures that negative numbers cannot be entered.
JOptionPane.showMessageDialog(null, "Error, Please enter a number between 1 and 10");
return;
}
if (days >= 10) { // Ensures nothing over 10 can be entered.
JOptionPane.showMessageDialog(null, "Error, Please enter a number between 1 and 10");
return;
}

如果 if 语句说它是一个错误,它应该返回要求他们重新输入天数

最佳答案

使用 do-while 循环,该循环将至少执行一次,如果 days 不满足条件,则每次循环返回。

public static void main(String[] args) 
{
do {
//Your other code
String animal = JOptionPane.showInputDialog("Enter In Animal Name"); // Asking for user to enter a animal
String fruit = JOptionPane.showInputDialog("Enter In A Fruit Name"); // Asking user to enter a fruit

int days = askForInput();

if (days <= 0 || days >= 10) { // Ensures that negative numbers cannot be entered.
JOptionPane.showMessageDialog(null, "Error, Please enter a number between 1 and 10");
}

} while (days <= 0 || days >= 10);
}

//Pass whatever parameters you might need
public static int askForInput() {
int days = Integer.parseInt(JOptionPane.showInputDialog("Enter In How Many Days Between 1 And 10"));
//Any other code you want
return days;
}

我还将它提取到一个方法中,这可能是不必要的,但如果需要,它可以让您添加更多功能。

如果您不想每次都询问该问题,也可以将 animalfruit 移到 do 之外。

关于java - 需要一个不满足的 if 语句来转到代码开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57926859/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com