Re: Two class program help
You're accelerate method is broken.
Instead of re-assigning the acceleration with acceleration + 5, you should be increasing the speed by 5.
something like this:
Code :
public void accelerate()
{
speed = speed + 5;
}
The brake method should be something similar to the above method.
Also, you need to be polling the speed each time through the loop, updating the value since Java passes primitives by Value rather than by Reference (note: objects are passed by reference rather than by value)
Code :
for (int i = 0; i < 5; i++)
{
// other code to accelerate or decelerate
int speed = c.getSpeed();
System.out.println("The car's current speed is " + speed);
}
Re: Two class program help
alright, I got the accelerate method fixed, and I tried to do the same thing with the brake method but i cant get the for loop to decrease the speed.
Code :
public void brake()
{
int brake = 0;
brake = brake - 5;
}
and then
Code :
for(int i = 0; i < 5; i++)
{
s = c.getSpeed();
System.out.println("The speed is now " + s);
c.brake();
}
Re: Two class program help
You're trying to do the same thing with the brake method as you originally had with your acceleration method. You need to be updating speed, not the variable brake.
Just copy/paste the acceleration method, change the name to brake and change one other thing (think: what is the difference between acceleration and braking?)
Re: Two class program help
Old thread but I want to share my work with others it might be useful.
The problem was here:
Code :
public int accelerate(int ac)
{
ac = ac + 5;
return ac;
}
Because if we already have private int speed we don't need to use another variable int ac, but we should use private int speed, so that method would be implemented like this:
Code :
public int accelerate() {
speed += 5;
return speed;
}
Full code:
Code :
public class Car {
private int yearModel;
private String make;
private int speed;
public Car(int model, String m) {
yearModel = model;
make = m;
speed = 0;
}
public int getYearModel() {
return yearModel;
}
public String getMake() {
return make;
}
public int getSpeed() {
return speed;
}
public int accelerate() {
speed += 5;
return speed;
}
public int brake(int b) {
b = b - 5;
return b;
}
}
Code :
public class CarDemo {
public static void main(String[] args) {
Car c = new Car(1992, "Mustang");
int s = 0;
s = c.getSpeed();
for(int i = 0; i < 5; i++) {
System.out.println("The " + c.getYearModel() + " " + c.getMake() + "is going: " + s);
s = c.accelerate();
System.out.println("Now the " + c.getYearModel() + " " + c.getMake() + "is going: " + s);
}
}
}