下面的代码要求用户输入一个数字。然后它会提示用户输入更多数字。当他们退出程序时,他们会显示输入的最大数字。我如何转换此代码来询问一个人的性别然后年龄。那么程序的输出将表明女孩的最高年龄是 ____,男孩的最高年龄是 _______?目前它是性别中立的,只符合最高年龄。
import javax.swing.JOptionPane;
public class largestNumb{
public static void main(String[] args) {
int highestNumber;
boolean firstNumberEntered = false;
int firstNumber;
do {
String firstNumberInput = JOptionPane.showInputDialog("Enter the first number: ");
try {
firstNumber = Integer.parseInt(firstNumberInput);
firstNumberEntered = true;
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Invalid number! Please try again.");
firstNumber = 0;
firstNumberInput = JOptionPane.showInputDialog("Enter the first number: ");
}
} while (!firstNumberEntered);
highestNumber = firstNumber;
String numberInput = JOptionPane.showInputDialog("Enter another number, or Q to quit");
while (!numberInput.equalsIgnoreCase("Q")) {
int number;
try {
number = Integer.parseInt(numberInput);
if (number > highestNumber) {
highestNumber = number;
}
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Invalid number!");
}
numberInput = JOptionPane.showInputDialog("Enter another number, or Q to quit");
}
JOptionPane.showMessageDialog(null, "The highest number was: " + highestNumber);
}
}
最佳答案
- 您可以在另一个
showInputDialog
方法中询问性别。 - 将
showInputDialog
从 int 更改为值的集合,它可以是一个长度为 2 的数组,用于存储性别的最高年龄,它可以是一个映射,其中键为性别,极限就是天空 - 您需要进行验证:
- 如果您询问年龄,那么在询问数据时不应该说明这一点吗?
- 如果用户输入负数会发生什么?
- 您能接受 1345 岁的年龄吗?
- 如果文本为空,即与“q”不同的字符怎么办?
关于java - 如何将嵌套循环插入到2个while循环中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39939972/