对于家庭作业问题,我必须使用JOptionPane类从用户获取2个值,然后通过我在类文件中创建的方法运行它。但是,即使在通读课程后,我也不知道该怎么做。我不确定是在我创建的类文件中还是在新的PairTester文件中实现类方法。我真的坚持执行。
要求:除了构造函数值,我不能使用任何参数值或局部变量。
import javax.swing.JOptionPane;
public class Pair{
private double x;
private double y;
public Pair(){}
public Pair(double x, double y){
this.x=x;
this.y=y;
}
public double getSum(){
return x + y;
}
public double getDifference(){
return x - y;
}
public double getProduct(){
return x * y;
}
public double getQuotient(){
return (x + y) / 2;
}
public double getDistance(){
return Math.abs(x - y);
}
public double getMax(){
return Math.max(x,y);
}
public double getMin(){
return Math.min(x,y);
}
public double getx(){
return x;
}
public double gety(){
return y;
}
public String toString(){
return "Pair[x = "+getx()+", y = "+gety()+"]";
}
}
您可以通过在对话框中添加所需输入来实现此目的。 Dialogs可以接受object
作为其第二个参数,在这种情况下,您可以使用输入传递自定义面板。
public void getInputs()
{
// Create the custom panel and inputs
JPanel inputPanel = new JPanel(new GridLayout(2, 2));
JTextField xInput = new JTextField();
JTextField yInput = new JTextField();
//Add the inputs and labels to the custom panel
inputPanel.add(new JLabel("Enter X: "));
inputPanel.add(xInput);
inputPanel.add(new JLabel("Enter Y: "));
inputPanel.add(yInput);
//Display the dialog
int dialogResult = JOptionPane.showConfirmDialog(null, inputPanel, "Enter your X & Y values below");
if(dialogResult == JOptionPane.OK_OPTION)
{
try
{
//Get the input values from our custom inputs in the panel
x = Integer.parseInt(xInput.getText());
y = Integer.parseInt(yInput.getText());
}
//Exception is thrown if user doesn't enter numbers
catch(NumberFormatException e)
{
JOptionPane.showMessageDialog(null, "Please only enter numbers");
}
}
}