我的目标是输入三个数字并让程序吐出中间数字。这适用于System.out.println
,但是当我必须使用JOptionPane
时,它开始变得混乱。
这是我得到的代码:
public class ReturnMiddle {
public static void main(String[] args) {
int num1 = 0;
int num2 = 0;
int num3 = 0;
int smallest = returnMiddle(num1, num2, num3);
String inputValue = JOptionPane.showInputDialog("What is your first number?");
num1 = (Integer.parseInt(inputValue));
inputValue = JOptionPane.showInputDialog("What is your second number?");
num2 = (Integer.parseInt(inputValue));
inputValue = JOptionPane.showInputDialog("What is your third number?");
num3 = (Integer.parseInt(inputValue));
JOptionPane.showMessageDialog(null, smallest);
}
public static int returnMiddle(int num1, int num2, int num3) {
//Returns the smaller of num1 and num2.
int middle12 = Math.min(num1, num2);
//Returns the smaller of num2 and num3.
int middle23 = Math.min(num2, num3);
//Returns the smaller of num1 and num3.
int middle13 = Math.min(num1, num3);
//Returns the larger of middle12 and middle13.
int middleNumber1 = Math.max(middle12, middle13);
//Returns the larger of middleNumber1 and middle23, which
//ends up being the middle of the original 3 numbers.
int middleNumber2 = Math.max(middleNumber1, middle23);
//Makes the method "returnMiddle" return middleNumber2.
return middleNumber2;
}
}
当我输出三个数字时,我每次都得0。这是在两种不同方法中使用num1
,num2
和num3
的问题吗?我是否将returnMiddle
方法称为错误?
答案 0 :(得分:2)
您必须在正确的位置使用该方法。 目前,您计算结果FIRST并获得输入SECOND。你必须反过来这样做。
// dont calculate it here
String inputValue = JOptionPane.showInputDialog("What is your first number?");
num1 = (Integer.parseInt(inputValue));
inputValue = JOptionPane.showInputDialog("What is your second number?");
num2 = (Integer.parseInt(inputValue));
inputValue = JOptionPane.showInputDialog("What is your third number?");
num3 = (Integer.parseInt(inputValue));
// you have to calculate the middle one here.
int middle = returnMiddle(num1, num2, num3);
JOptionPane.showMessageDialog(null, middle);
答案 1 :(得分:0)
您正在调用returnMiddle错误。在您阅读并分配输入后应该调用它。
public static void main(String[] args) {
int num1 = 0;
int num2 = 0;
int num3 = 0;
int smallest = Integer.MAX_VALUE;
String inputValue = JOptionPane.showInputDialog("What is your first number?");
num1 = (Integer.parseInt(inputValue));
inputValue = JOptionPane.showInputDialog("What is your second number?");
num2 = (Integer.parseInt(inputValue));
inputValue = JOptionPane.showInputDialog("What is your third number?");
num3 = (Integer.parseInt(inputValue));
smallest = returnMiddle(num1, num2, num3);
JOptionPane.showMessageDialog(null, smallest);
}
答案 2 :(得分:0)
查看您的代码
int smallest = returnMiddle(num1,num2,num3);
这里你实际上告诉编译器你希望var'minimum'等于returnMiddle函数的结果。由于用户输入是在调用该方法之后,您没有在该调用上将这些值传递给该函数,而实际上是初始化的0:
int smallest = returnMiddle(0,0,0);
获得用户输入后,您需要调用该方法。