如何解决我的问题?

问题描述 投票:0回答:1

对于家庭作业问题,我必须使用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()+"]";
}
}
java
1个回答
0
投票

您可以通过在对话框中添加所需输入来实现此目的。 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");
            }
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.