gpt4 book ai didi

Java程序不返回任何值

转载 作者:行者123 更新时间:2023-12-01 11:23:33 26 4
gpt4 key购买 nike

我目前正在做一项类作业,无法弄清楚为什么我会得到这样的输出。编程问题是:

You operate several hotdog stands. Define a class named HotDogStand that has an instance variable for the hot dog stand's ID number and an instance variable for how many hot dogs the stand has sold that day. Create a constructor that allows a user of the class to initialize both variables. Also create a method named justSold that increments by one the number of hot dogs the stand has sold. The idea is that this method will be invoked each time the stand sells a hot dog so the total can be tracked. Add another method that returns the number of hot dogs sold.

Add a static variable that tracks the total number of hot dogs sold by all the stands and a static method that returns the value in this variable.

所以我的代码是:

public class HotDogStand {
// instance variable declaration
private int IDNumber;
private int hotDogsSold = 0;
private static int totalSold = 0;

public HotDogStand(int ID, int sold) {
IDNumber = ID;
hotDogsSold = sold;
}

public int getID() {
return IDNumber;
}

public void setID(int ID) {
IDNumber = ID;
}

public void justSold() {
if (hotDogsSold > 0) {
hotDogsSold++;
}
}

public int sold() {
return hotDogsSold;
}

public static int getTotal() {
return totalSold;
}
}

我的测试类是:

public class HotDogTest {
public static void main(String[] args) {
HotDogStand stand1 = new HotDogStand(1, 11);
HotDogStand stand2 = new HotDogStand(2, 17);
HotDogStand stand3 = new HotDogStand(3, 6);

stand1.getID();
stand2.getID();
stand3.getID();
stand1.setID(1);
stand2.setID(2);
stand3.setID(3);
stand1.justSold();
stand2.justSold();
stand3.justSold();
stand1.justSold();
stand1.justSold();
stand1.justSold();
stand3.justSold();

stand1.getTotal();
stand2.getTotal();
stand3.getTotal();

int grandTotal = stand1.getTotal() + stand2.getTotal() + stand3.getTotal();

System.out.println("Stand " + stand1.getID() + " sold a total of " + stand1.getTotal() + " hotdogs.");
System.out.println("Stand " + stand2.getID() + " sold a total of " + stand2.getTotal() + " hotdogs.");
System.out.println("Stand " + stand3.getID() + " sold a total of " + stand3.getTotal() + " hotdogs.");

System.out.println("The total amount of hotdogs sold by all the stands was " + grandTotal);
}
}

我的输出是:

Stand 1 sold a total of 0 hotdogs.
Stand 2 sold a total of 0 hotdogs.
Stand 3 sold a total of 0 hotdogs.
The total amount of hotdogs sold by all the stands was 0

最佳答案

您永远不会更新totalSold字段。在 justSold() 方法的 if 条件中也增加该值。

关于Java程序不返回任何值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31014524/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com