【问题标题】:Java -Comparing values from objects in an ArrayListJava - 比较 ArrayList 中对象的值
【发布时间】:2018-05-04 17:12:57
【问题描述】:

所以基本上我有一个程序,我将电脑添加到数组列表中,并且必须挑选出其中最好的一个(取决于分数/价格数学运算),这意味着分数为 10 且价格为 5 的电脑将是比得分为 10 且价格为 10 的更好。问题是必须实现的布尔 (isBetterThan) 方法,并以某种方式用于比较它们,我不知道具体如何)。 到目前为止的代码如下:

    package filipapp;

public interface Better {
    public double getPrice();
    public void setPrice(double price);
    public int getScore();
    public void setScore(int score);
    public boolean isBetterThan(Object obj);
}

    package filipapp;

public class Computer implements Better {
    private String model;
    private double price;
    private int score;
    public Computer (String model,double price,int score){
        this.model = model;
        this.price = price;
        this.score = score;
    }
    @Override 
    public double getPrice(){
        return price;
    }
    @Override
    public void setPrice(double price){
        this.price = price;
    }
    @Override 
    public int getScore(){
        return score;
    }
    @Override
    public void setScore(int score){
        this.score = score;
    }
    @Override 
    public boolean isBetterThan(Object obj){
        obj = getScore()/getPrice();
        return true;
    }
    @Override
    public String toString(){
        return ("Model "+model+" at price: "+price+" with score: "+score);
    }
}

图形界面

 package filipapp;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class FilipApp extends JFrame implements ActionListener {
    private JLabel l1,l2,l3;
    private JTextField t1,t2,t3;
    private JPanel p1,p2,p3;
    private JButton b1,b2;
    private JTextArea area;
    private JScrollPane scroll;
    public Computer p;
    ArrayList <Computer> pc = null;

    public static void main(String[] args) {
         EventQueue.invokeLater(new Runnable(){
           @Override
           public void run(){
               new FilipApp().setVisible(true);
           }
       });
    }
    public FilipApp(){
        super("The best PC");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(600,400);
        Container container = this.getContentPane();

        p1 = new JPanel();
        p1.setLayout(new GridLayout(3,2));
        l1 = new JLabel("Model",JLabel.CENTER);
        p1.add(l1);
        t1 = new JTextField(15);
        p1.add(t1);
        l2 = new JLabel("Price",JLabel.CENTER);
        p1.add(l2);
        t2 = new JTextField(15);
        p1.add(t2);
        l3 = new JLabel("Score",JLabel.CENTER);
        p1.add(l3);
        t3 = new JTextField(15);
        p1.add(t3);
        container.add(p1,BorderLayout.PAGE_START);

        p2 = new JPanel();
        b1 = new JButton("Add");
        b1.addActionListener(this);
        p2.add(b1);
        b2 = new JButton("Best");
        b2.addActionListener(this);
        p2.add(b2);
        container.add(p2,BorderLayout.CENTER);

        p3 = new JPanel();
        area = new JTextArea(15,35);
        scroll = new JScrollPane(area ,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        p3.add(scroll);
        container.add(p3,BorderLayout.PAGE_END);

        pc = new ArrayList <>();
    }
    @Override
    public void actionPerformed(ActionEvent e){
        try{
            Object source = e.getSource();
            if (source == b1){
                p = new Computer(t1.getText(),Double.parseDouble(t2.getText()),Integer.parseInt(t3.getText()));
                pc.add(p);
                area.append("Added PC  \n"+p.toString()+"\n");
                t1.setText("");t2.setText("");t3.setText("");
            }
            else if (source == b2 && pc.isEmpty()){
                area.append("Empty List \n");
            }
            else if (source == b2){
              for (Computer element : pc){

                  element.isBetterThan(element);
                  area.append("Best PC: "+element.toString()); 
              }
            }
        }catch(NumberFormatException ex){
             System.out.println("Error in input data");
        }
    }
}

【问题讨论】:

  • 很难回答。你试过什么?你要逻辑?算法?句法?结构?
  • 我们需要有关您的算法/系统的更多详细信息。 scoreprice 是否总是满分 10?
  • 嗯,我已经玩了一段时间的代码,所以我确实尝试了一些东西,但它们似乎都没有给我想要的结果。如果可能的话,Syntab 将是完美的。这里的主要问题是这个布尔方法,因为我根本无法理解如何使用它的逻辑。不,我只是以这些数字为例。分数和价格可以是任何整数/您希望它们成为双倍数字。关键是通过以某种方式比较它们,从而取出具有最佳分数/价格比例的PC。
  • 我会创建一种方法来生成分数,基本上,就像每单位货币的分数一样,然后将它们存储在对象中并基于该字段进行流最大化。如果您真的想要提供类似布尔对象的东西,那么我只需实现比较器接口。
  • 我解决了。感谢每个人的答案:)

标签: java oop user-interface arraylist


【解决方案1】:

在你的循环中,你应该使用一个节奏变量来作为最好的项目。

       else if (source == b2){
          Computer best = pc.get(0); // Depend on your logic, you should verify if the pc list is empty or not before get(0)
          for (int i = 1; i < pc.size(); i++){
              Computer element = pc.get(i);
              if (element.isBetterThan(best)) {
                   best = element;
              }
          }
          // When loop exits, you have access to the best pc
          area.append("Best PC: "+best.toString()); 
        }

【讨论】:

    【解决方案2】:

    首先,如果它比另一个“更好”是主观的,我看到你正在使用getScore()/getPrice() 做出判断,所以我会继续假设这很好。

    首先要了解的是isBetterThan 正在将this 这是一个Computer 对象与另一个计算机对象进行比较。所以启动界面应该是这样的

    public boolean isBetterThan(Computer comp);
    

    然后使用您的除法逻辑来实现它看起来像

    public boolean isBetterThan(Computer comp){
        if((this.getScore()/this.getPrice()) <
                 comp.getScore()/comp.getPrice()) {
            return false;
        }
        return true;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-02-27
      • 1970-01-01
      • 2010-11-09
      • 2021-02-13
      • 1970-01-01
      • 2014-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多