I am currently working on a class assignment and cannot figure out why I am getting the output that I am getting. The programming question is:
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.
So my code is:
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;
}
}
And my testing class is:
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);
}
}
My output is:
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
you are never updating totalSold field. Increment that as well inside justSold() method's if condition.
There is no point at which you change the totalSold variable. justsold increments the instance variable hotDogsSold but getTotal return totalSold.
You need a method getSold which returns the instance variable hotDogsSold.
The other problem is that totalSold is a static variable (it's a class variable; it's not tied to any individual instance of the class like hot dog seller 1 or 2 but rather to the entire model of hot dog sellers). As a result, your grand total would, if totalSold were incremented correctly, give 3 times the number of sold hot dogs for everyone.
Try this:
public void justSold() {
if (hotDogsSold > 0) {
totalSold = hotDogsSold++;
}
Related
I am a complete beginner in programming and I'm working on a program for my mother that tracks her employee's monetary intake through a "horse race", with each employee having a horse and the program tracking their input to a UI made to look like a racetrack. After the help from my last inquiry, I've greatly simplified my mess of code but I am now faced with a new problem in that, after sorting the values largest to smallest, I have no way of associating the sorted values with the correct horse. I understand this explanation is confusing so I hope my code will do most of the talking for me here.
I honestly have no idea where to start with this. As I said in my last inquiry, I'm a complete beginner and severely lack the terminology or knowledge to find an answer here.
public class HorseRace {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String horse1 = "#5 Gitty-Up";
String horse2 = "#7 Lady Simmons";
String horse3 = "#6 Burning Peanutbutter";
String horse4 = "#10 White Lightning";
String horse5 = "#3 Bella";
String horse6 = "#1 Meg The Stallion";
float h1val;
float h2val;
float h3val;
float h4val;
float h5val;
float h6val;
System.out.println("Input amount for " + horse1 + ":");
h1val = sc.nextFloat();
System.out.println("Input amount for " + horse2 + ":");
h2val = sc.nextFloat();
System.out.println("Input amount for " + horse3 + ":");
h3val = sc.nextFloat();
System.out.println("Input amount for " + horse4 + ":");
h4val = sc.nextFloat();
System.out.println("Input amount for " + horse5 + ":");
h5val = sc.nextFloat();
System.out.println("Input amount for " + horse6 + ":");
h6val = sc.nextFloat();
Float[] values = new Float[]{h1val, h2val, h3val, h4val, h5val, h6val};
Arrays.sort(values, Collections.reverseOrder());
//currently displays horses with the wrong number. Need a way to tie the horse name strings to their respective float elements
System.out.println("The current race progress is :");
System.out.println(horse1 + " with $" + values[0]);
System.out.println(horse2 + " with $" + values[1]);
System.out.println(horse3 + " with $" + values[2]);
System.out.println(horse4 + " with $" + values[3]);
System.out.println(horse5 + " with $" + values[4]);
System.out.println(horse6 + " with $" + values[5]);
}
}
my desired result is printing the correct horse with the correct value. For example, if I put that #5 brought in $11 and #7 brought in $14, the program would print that #7 is in the lead with $14 and #5 is in second place with $11.
Currently, the program always prints #5 as being in the lead with the highest value, #7 being in second with the second highest, etc.
I understand this is because I am hard calling the horse1-horse6 values meaning they don't change, but these are acting more as placeholders while I figure out how to associate the right horse with the right value
This is where you should create a Horse class and store the data as instances of Horse.
class Horse {
private String name;
private float value;
public String getName() { return name; }
public float getValue() { return value; }
public void setName(String name) { this.name = name; }
public void setValue(float value) { this.value = value; }
}
And then in your main method:
Horse[] horses = new Horse[6] {
new Horse(), new Horse(), new Horse(), new Horse(), new Horse(), new Horse()
};
horses[0].setName("#5 Gitty-Up");
horses[1].setName("#7 Lady Simmons");
horses[2].setName("#6 Burning Peanutbutter");
// and so on...
// you should use a for loop here instead of writing similar lines over and over again!
for (int i = 0 ; i < 6 ; i++) {
System.out.println("Input amount for " + horses[i].getName() + ":");
horses[i].setValue(sc.nextFloat());
}
Arrays.sort(horses, Comparator.comparingDouble(Horse::getValue).reversed());
System.out.println("The current race progress is :");
for (int i = 0 ; i < 6 ; i++) {
System.out.println(horses[i].getName() + " with $" + horses[i].getValue());
}
By using a class, you are essentially grouping data that belongs together, together. On the line Arrays.sort(horses, Comparator.comparingDouble(Horse::getValue).reversed());, I am sorting the whole array of horses together, by their values.
If the concepts of classes and objects are new to you, that just means it's time to learn about some new concepts. Classes and objects are very important.
Step 1, create a Horse class. It should have two fields, amount and name. It should implement Comparable because you want to sort it. And looking at your desired output, I would override toString().
class Horse implements Comparable<Horse> {
private String name;
private float amount;
public Horse(String name, float amount) {
this.name = name;
this.amount = amount;
}
#Override
public String toString() {
return String.format("%s with $%.2f", name, amount);
}
#Override
public int compareTo(Horse o) {
return Comparator.comparing((Horse h) -> h.amount)
.thenComparing((Horse h) -> h.name).compare(this, o);
}
}
Step 2, create an array of horseNames and iterate that populating an array of Horses (with amounts). Then sort it, and I would prefer Comparator.reverseOrder() to Collection.reverseOrder() when sorting an array.
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
String[] horseNames = { "#5 Gitty-Up", "#7 Lady Simmons",
"#6 Burning Peanutbutter", "#10 White Lightning",
"#3 Bella", "#1 Meg The Stallion" };
Horse[] horses = new Horse[horseNames.length];
for (int i = 0; i < horseNames.length; i++) {
System.out.printf("Input amount for %s:%n", horseNames[i]);
float amt = sc.nextFloat();
horses[i] = new Horse(horseNames[i], amt);
}
Arrays.sort(horses, Comparator.reverseOrder());
System.out.println("The current race progress is :");
for (int i = 0; i < horses.length; i++) {
System.out.println(horses[i]);
}
}
Currently learning Java as a hobby and am making small game projects to reinforce the concepts. So for this one, I've made a method that creates an array of objects, in this case, a "Computer" object. I'm doing this because I want the user to decide at startup how many computer opponents they want to play against, instead of hard coding a set number of them. Now I want to assign and retrieve a value for each Computer object. For example a Computer name, bet amount, and a dice roll guess.
public class Computer {
static int bet;
static int guess;
int cash;
static Computer[] c;
public static void create(int numComps) {
c = new Computer[numComps];
for (int i = 0; i < numComps; i++) {
c[i] = new Computer();
c[i].cash = Game.startCash;
c[i].bet = bet();
c[i].guess = guess();
c[i].display();
}
}
public static int bet() {
bet = Rng.rand(Game.startCash / 50) * 50;
return bet;
}
public static int guess() {
guess = Dice.roll();
return guess;
}
public void display() {
String name = "Computer ";
System.out.println("My name is " + name + " i bet " + bet + " and guess " + guess);
}
}
When i do Computer.create(5) i get
My name is Computer i bet 150 and guess 9
My name is Computer i bet 50 and guess 3
My name is Computer i bet 450 and guess 11
My name is Computer i bet 250 and guess 11
My name is Computer i bet 50 and guess 10
This output gives the appearance of working but i don't think i'm on the right track. For the name i want the syntax to be something like, name = "Computer " + c[i]. Resulting in "Computer 1", "Computer 2", "Computer 3" etc, not sure how to do that correctly. And an individual bet and guess to be assigned to each individual object. Right now i think its just displaying a random number rather than assigning that value to the particular object.
The bet and guess member variables shouldn't be static.
To display the id you can add a new int member variable, set it to i for each computer when you initialize them in the loop, and update the display() method to print it.
public class Computer {
int id;
int bet;
int guess;
int cash;
static Computer[] c;
public static void create(int numComps) {
c = new Computer[numComps];
for (int i = 0; i < numComps; i++) {
c[i] = new Computer();
c[i].id = i;
c[i].cash = Game.startCash;
c[i].bet = bet();
c[i].guess = guess();
c[i].display();
}
}
public static int bet() {
return Rng.rand(Game.startCash / 50) * 50;
}
public static int guess() {
return Dice.roll();
}
public void display() {
String name = "Computer ";
System.out.println("My name is " + name + id + " bet " + bet + " and guess " + guess);
}
}
Hi, I am working on a CodeHS problem and completed it with confidence, but got it very wrong. I am looking for my mistakes and helpful feedback. Thanks!
*The instructions for the problem are as follows:
We have a simple Battery class. Add two static fields to Battery,
totalVoltage and numOfBatteries. In addition, alter the constructor so that
the Battery class keeps track of both of the new static variables.
Every time a new Battery is constructed, the numOfBatteries should increase by one, and the totalVoltage should increase by the new voltage of the current Battery being constructed.
Hint: totalVoltage should be a double*
The Batterytester is:
public class BatteryTester extends ConsoleProgram
{
public void run()
{
Battery aaBattery1 = new Battery(1.5);
System.out.println("Total voltage: " + Battery.totalVoltage);
System.out.println("Total batteries: " + Battery.numOfBatteries);
Battery aaBattery2 = new Battery(1.5);
System.out.println("Total voltage: " + Battery.totalVoltage);
System.out.println("Total batteries: " + Battery.numOfBatteries);
Battery aaBattery3 = new Battery(1.5);
System.out.println("Total voltage: " + Battery.totalVoltage);
System.out.println("Total batteries: " + Battery.numOfBatteries);
Battery aaBattery4 = new Battery(1.5);
System.out.println("Total voltage: " + Battery.totalVoltage);
System.out.println("Total batteries: " + Battery.numOfBatteries);
}
}
My code is as follows:
public class Battery
{
private double voltage;
public static int numOfBatteries;
public static double totalVoltage;
//adds the new fields to constructor
public Battery(double voltage, double totalVoltage, int numOfBatteries)
{
this.voltage = voltage;
this.totalVoltage = totalVoltage;
this.numOfBatteries = numOfBatteries;
numOfBatteries++;
totalVoltage += voltage; //increments total voltage with voltage param
}
public double getVoltage()
{
return this.voltage;
}
public static int numOfBatteries()
{
return this.numOfBatteries;
}
public static double totalVoltage()
{
return this.totalVoltage;
}
//all of these return the values
}
You don't need this for numOfBatteries() and totalVoltage() methods, since static methods cannot access this.
Batteries should only be taking in one parameter, you have three. Just remove totalVoltage and numOfBatteries and your code will be fixed. Also as the other guy said, you don't need this for the two static methods your creating.
for the following code:
System.out.println("How many types of food do the gerbils eat?");
int F = keyboard.nextInt();
food = new food[F];
for
(int a = 0; a<F; a++){
System.out.println("Name of food number " + (a+1));
foodname = keyboard.next();
System.out.println("Max amount of food " + (a+1));
maximum = keyboard.nextInt();
food[a] = new food(foodname, maximum);
for (int n = 0; n<F; n++){
System.out.println(food[n]);
}
}
I get the following output:
How many types of food do the gerbils eat?
2
Name of food number 1
p
Max amount of food 1
5
p 5
null
Name of food number 2
r
Max amount of food 2
5
r 5
r 5
As you can see, every time the loop restarts, the new input values for food name and food maximum are reset. why is it doing that, and how do i fix it so that it stores my original input for food 1 name and maximum?
Class food:
public class food {
public static String foodname;
public static int maximum;
public food(String foodname, int maximum) {
this.foodname = foodname;
this.maximum = maximum;
}
public String getFood(){
return foodname;
}
public int getmaxamount(){
return maximum;
}
public String toString() {
return (this.getFood() + " " + this.getmaxamount());
}
}
In your Food class, you declared
foodname
maximum
as static.
It means, those values will be the same for every Food you create.
As you want different kind of Food, simply remove those modifiers
Although this question has already been answered, I thought I'd go ahead and add this:
Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory.
Link: http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
It is suppose to return a value of 19 full seats and 68 students remaining!
please help, with my understanding I am returning the right values and assigning them to the correct variables!
public class JetCalculator
{
public static void main(String[] args)
{
int totalStudents = 3013;
int jetCapacity = 155;
int jets;
int students;
jets = calculateJets(jetCapacity, totalStudents);
students = calculateStudents(jetCapacity, totalStudents, jets);
System.out.println("A total of "+ totalStudents + " student require "+ jets + " full seated jets.");
System.out.println("There will be " + students + " students remaining");
System.out.println("_____________________________________________");
System.out.println(jets);
System.out.println(jetCapacity);
System.out.println(students);
}
public static int calculateJets(int totalStudents, int jetCapacity)
{
int fullJets;
fullJets = totalStudents / jetCapacity;
return fullJets;
}
public static int calculateStudents( int jetCapacity, int totalStudents, int jets)
{
int remainingStudents;
remainingStudents = jetCapacity * jets;
return remainingStudents;
}
}
You call calculateJets this way
jets = calculateJets(jetCapacity, totalStudents);
But the argument names for this method imply that you've switched their order in the call
public static int calculateJets(int totalStudents, int jetCapacity)
This means you're actually doing 155 / 3013 which is 0 using integer arithmetic.
You're passing in your parameters back to front.
You call calculateJets by passing capacity then students: calculateJets(jetCapacity, totalStudents); but the method asks for students then capacity: calculateJets(int totalStudents, int jetCapacity).
This is a good argument for consistency in parameter order throughout a class interface.
To help debug this in future, try throwing in a println at the start of methods to see what is happening:
System.out.println("Called calculateJets with totalStudents of " + totalStudents + " and jetCapacity of " + jetCapacity);
Based purely on method names: did you mean to say remainingStudents = totalStudents - (jetCapacity * jets); ?