使用Java对话框查找最小值和最大值
所以我的任务是
请用户输入一个数字。您应该使用输入对话框进行此输入。确保将对话框中的字符串转换为实数。程序需要记录用户输入的最小数字和输入的最大数字。询问用户是否要输入其他号码。如果是,重复该过程。如果否,则输出用户输入的最小和最大数字
当用户想要退出时,该程序在程序结束时输出最大和最小的数字
此外,您的程序应该考虑用户只输入一个数字的情况。在这种情况下,最小值和最大值将是相同的
我很难做到这一点,如果用户只输入1个数字,那么两个值都将被设置,但同时只要用户说是,它就会循环
public static void main(String[] args)
{
int maxNum = Integer.MAX_VALUE;
int minNum = Integer.MIN_VALUE;
String repeat;
String firstResponseString = JOptionPane.showInputDialog("Enter a Number ");
maxNum = Integer.parseInt(firstResponseString);
minNum = Integer.parseInt(firstResponseString);
String userRepeat = JOptionPane.showInputDialog(" Would you like to input another number? Y/N");
while(userRepeat.equalsIgnoreCase("Y"))
{
String num1String = JOptionPane.showInputDialog("Enter a Numer: ");
int num1 = Integer.parseInt(num1String);
if(num1 > maxNum)
{
maxNum = num1;
}
if(num1 < minNum)
{
minNum = num1;
}
userRepeat = JOptionPane.showInputDialog(" Would you like to input another number? Y/N");
}
JOptionPane.showMessageDialog(null, "Largest Number: " + maxNum + "\nSmallest Number: " + minNum, "Find Min and Max", JOptionPane.INFORMATION_MESSAGE);
}
我想我现在可以用这个代码了
# 1 楼答案
字符串repeat没有任何用途,因为它不是在任何地方使用的,而是在声明中指定maxNum=。。。而米努姆=。。。。没有必要,因为您正在解析maxNum和minNum,以便JOptionpane可以识别它们
# 2 楼答案
您可以在声明中设置
int minNum = Integer.MIN_VALUE
和int maxNum = Ingerer.MAX_VALUE