【问题标题】:How do a reference a variable in another object如何引用另一个对象中的变量
【发布时间】:2015-03-14 17:42:57
【问题描述】:

我是一个绝对的编程初学者,我正在尝试从一本书中学习 Java。我很困惑。

这本书有一个练习(这就像这一章的一半,所以有很多东西要建立起来,但我会尽量说清楚)要求我们向一个类添加一个方法。基本上,我们得到了一组预置的类,它们应该类似于一个简单的拍卖程序。因此,有一个数组列表,其中包含投标人列表、他们的出价以及批号。这个练习要求我们添加一个方法,该方法将打印出中标者的姓名及其投标价值的列表。

好的,这是有道理的。我可以想一想它应该如何工作。我什至写了以下代码:`

    /**
 * Exercise 4.48
 * for each item in the list of lots, get the highest bid.
 * if highest bid is not null, print the bidder and value
 * otherwise, print "lot not sold"
 */
 public void close()
{
    for(Lot lot : lots) {
        Bid highestBid = lot.getHighestBid();
        if(highestBid != null) {
            System.out.println(bidder, value);
        }
        else{
            System.out.println("Lot not sold.");
        }
    }
}

当尝试编译它时,它会在bidder 上停止,因为我还没有定义变量。所以很明显我应该告诉它“投标人”应该是什么意思。 Bidder 是同一程序中“Person”对象中变量的名称,并在整个项目中使用,但我仍然不清楚如何让它理解我的“投标人”是同一个“投标人”。我假设我对“价值”也会有同样的问题。

我错过了什么?

经过编辑以使代码实际上看起来像代码。

根据要求,这是 Person... 类? (我对术语不太了解。我会到达那里。抱歉。)

        /**
     * Maintain details of someone who participates in an auction.
     * @author David J. Barnes and Michael Kölling.
     * @version 2011.07.31
     */
    public class Person
    {
        // The name of this person.
        private final String name;

        /**
         * Create a new person with the given name.
         * @param name The person's name.
         */
        public Person(String name)
        {
            this.name = name;
        }

        /**
         * @return The person's name.
         */
        public String getName()
        {
            return name;
        }
    }

        **/**
     * A class to model an item (or set of items) in an
     * auction: a lot.
     * 
     * @author David J. Barnes and Michael Kölling.
     * @version 2011.07.31
     */
    public class Lot
    {
        // A unique identifying number.
        private final int number;
        // A description of the lot.
        private String description;
        // The current highest bid for this lot.
        private Bid highestBid;

        /**
         * Construct a Lot, setting its number and description.
         * @param number The lot number.
         * @param description A description of this lot.
         */
        public Lot(int number, String description)
        {
            this.number = number;
            this.description = description;
            this.highestBid = null;
        }

        /**
         * Attempt to bid for this lot. A successful bid
         * must have a value higher than any existing bid.
         * @param bid A new bid.
         * @return true if successful, false otherwise
         */
        public boolean bidFor(Bid bid)
        {
            if(highestBid == null) {
                // There is no previous bid.
                highestBid = bid;
                return true;
            }
            else if(bid.getValue() > highestBid.getValue()) {
                // The bid is better than the previous one.
                highestBid = bid;
                return true;
            }
            else {
                // The bid is not better.
                return false;
            }
        }

        /**
         * @return A string representation of this lot's details.
         */
        public String toString()
        {
            String details = number + ": " + description;
            if(highestBid != null) {
                details += "    Bid: " + 
                           highestBid.getValue();
            }
            else {
                details += "    (No bid)";
            }
            return details;
        }

        /**
         * @return The lot's number.
         */
        public int getNumber()
        {
            return number;
        }

        /**
         * @return The lot's description.
         */
        public String getDescription()
        {
            return description;
        }

        /**
         * @return The highest bid for this lot.
         *         This could be null if there is
         *         no current bid.
         */
        public Bid getHighestBid()
        {
            return highestBid;
        }
    }
    **

    /**
 * A class that models an auction bid.
 * It contains a reference to the Person bidding and the amount bid.
 * 
 * @author David J. Barnes and Michael Kölling.
 * @version 2011.07.31
 */
public class Bid
{
    // The person making the bid.
    private final Person bidder;
    // The value of the bid. This could be a large number so
    // the long type has been used.
    private final long value;

        /**
         * Create a bid.
         * @param bidder Who is bidding for the lot.
         * @param value The value of the bid.
         */
        public Bid(Person bidder, long value)
        {
            this.bidder = bidder;
            this.value = value;
        }

        /**
         * @return The bidder.
         */
        public Person getBidder()
        {
            return bidder;
        }

        /**
         * @return The value of the bid.
         */
        public long getValue()
        {
            return value;
        }
    }


    import java.util.ArrayList;

    /**
     * A simple model of an auction.
     * The auction maintains a list of lots of arbitrary length.
     *
     * @author David J. Barnes and Michael Kölling.
     * @version 2011.07.31
     * 
     * 3/12/15 added close method exercise 4.48
     * 
     */

        public class Auction
        {
            // The list of Lots in this auction.
            private ArrayList<Lot> lots;
            // The number that will be given to the next lot entered
            // into this auction.
            private int nextLotNumber;

            /**
             * Create a new auction.
             */
            public Auction()
            {
                lots = new ArrayList<Lot>();
                nextLotNumber = 1;
            }

            /**
             * Enter a new lot into the auction.
             * @param description A description of the lot.
             */
            public void enterLot(String description)
            {
                lots.add(new Lot(nextLotNumber, description));
                nextLotNumber++;
            }

            /**
             * Show the full list of lots in this auction.
             */
            public void showLots()
            {
                for(Lot lot : lots) {
                    System.out.println(lot.toString());
                }
            }

            /**
             * Make a bid for a lot.
             * A message is printed indicating whether the bid is
             * successful or not.
             * 
             * @param lotNumber The lot being bid for.
             * @param bidder The person bidding for the lot.
             * @param value  The value of the bid.
             */
            public void makeABid(int lotNumber, Person bidder, long value)
            {
                Lot selectedLot = getLot(lotNumber);
                if(selectedLot != null) {
                    Bid bid = new Bid(bidder, value);
                    boolean successful = selectedLot.bidFor(bid);
                    if(successful) {
                        System.out.println("The bid for lot number " +
                                           lotNumber + " was successful.");
                    }
                    else {
                        // Report which bid is higher.
                        Bid highestBid = selectedLot.getHighestBid();
                        System.out.println("Lot number: " + lotNumber +
                                           " already has a bid of: " +
                                           highestBid.getValue());
                    }
                }
            }

            /**
             * Return the lot with the given number. Return null
             * if a lot with this number does not exist.
             * @param lotNumber The number of the lot to return.
             */
            public Lot getLot(int lotNumber)
            {
                if((lotNumber >= 1) && (lotNumber < nextLotNumber)) {
                    // The number seems to be reasonable.
                    Lot selectedLot = lots.get(lotNumber - 1);
                    // Include a confidence check to be sure we have the
                    // right lot.
                    if(selectedLot.getNumber() != lotNumber) {
                        System.out.println("Internal error: Lot number " +
                                           selectedLot.getNumber() +
                                           " was returned instead of " +
                                           lotNumber);
                        // Don't return an invalid lot.
                        selectedLot = null;
                    }
                    return selectedLot;
                }
                else {
                    System.out.println("Lot number: " + lotNumber +
                                       " does not exist.");
                    return null;
                }
            }
            /**
             * Exercise 4.48
             * for each item in the list of lots, get the highest bid.
             * if highest bid is not null, print the bidder and value
             * otherwise, print "lot not sold"
             */
             public void close()
            {
                for(Lot lot : lots) {
                    Bid highestBid = lot.getHighestBid();
                    if(highestBid != null) {
                        System.out.println(bidder, value);
                    }
                    else{
                        System.out.println("Lot not sold.");
                    }
                }
            }

【问题讨论】:

  • 能否请您在 Person 类/对象中添加代码?
  • 为了帮助您,您必须提供更多代码。因为这错过了很多这里没有给出的外部事物。
  • 我们不需要所有的外部代码,但请向我们提供整个项目结构...Lot 类是什么样的? ,... - 别的东西,在你的方法close() 你同时调用biddervalue 我假设它们是具有该方法的类的类变量?如果不是,那是你的问题
  • 它们不是,但它们在别处被引用。我不知道如何描述整个事情——除了阅读第 1-3 章之外,我实际上没有这方面的经验。
  • 我们还需要 Bid 类。

标签: java arraylist field


【解决方案1】:

感谢您通过提供支持代码来澄清您的问题!

这应该可以解决您的问题。更改此行:

System.out.println(bidder, value);

到这里:

System.out.println(highestBid.getBidder().getName() + " bids " + highestBid.getValue())

highestBid 变量存储一个 Bid 类型的对象。您可以查看 Bid 类定义以了解对象具有 Bid 类型意味着什么。基本上,Bid 对象有一个称为 getValue() 的方法,它返回投标的值,还有一个方法 getBidder(),它返回一个 Person 对象(一个遵守 Person 类定义的对象)。因此,查看 Person 类,看看 Person 对象如何拥有一个名为 getName() 的方法,该方法将人名作为字符串返回。

最后,我们可以使用方便的内置 System.out.println() 函数打印名称和值。

【讨论】:

  • 好像还可以。谢谢。
  • 我错了。现在,当我尝试编译它时,它显示“找不到符号 - 可变出价”,同时在 System.out.println(bid.getBidder().getName(), bid.getValue()) 中高亮出价;
  • 抱歉,将出价更改为最高出价。我会更新答案。
【解决方案2】:

教你最基本的,

将类视为现实生活中的对象, 它有自己的特征,您将其定义为class variables

这些应该(通常)定义为私有的,因此必须从类函数(getter 和 setter)中调用它们。我们这样做的原因是您可以设置一些限制。 (例如:“不超过 3”或“必须至少 4 个字符。长”...)

类函数就像:类中的小型隐藏类它们执行一些代码。注意“In”,函数 IN 类。不是相反。所以类不知道你在函数内部创建的变量,但函数知道类变量。

我怀疑你的情况是你打电话给biddervalue

  • 如果 getter 在定义 close() 函数的同一个类之外定义为私有,则不使用 getter。

但实际上,我们很难知道哪里出了问题。请提供close()函数的类

编辑:

close()的代码应该是...

public void close()
        {
            for(Lot lot : lots) {
                Bid highestBid = lot.getHighestBid();
                if(highestBid != null) {
                    System.out.println(highestBid.getBidder(), highestBid.getValue());
                }
                else{
                    System.out.println("Lot not sold.");
                }
            }

【讨论】:

  • close() 函数在 Auction 类中。我已经在上面提供了。
  • 是的,就像我说的...您正在尝试访问私有类变量,它们被定义为私有意味着只有类本身知道它的存在。您应该使用公共 getter 函数。我将在上面的答案中添加 close() 的正确代码
  • 如果您不明白代码,请告诉我
  • @GillianWeisgram 如果这个答案看起来正确或有帮助,最好你接受或支持它,以便其他人可以享受知识......
猜你喜欢
  • 2012-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多