When running the code, there appears to be a logic error where the current speed starts at 0, and is supposed to increase over 5 increments. However, the problem is that it remains at 0 throughout the 5 increments. But, the braking part works as intended. Can anyone please help me in finding out what I am doing wrong here? I cannot seem to locate my error on my own, or by googling other resources. Please forgive my garbage code in advance, this is my first project.
public class Car {
private static int Speed = 0;
private String Make = "Ford";
private int yearModel = 2013;
public Car (int i, String n, int Model)
{
Make = n;
yearModel = Model;
}
public static int getSpeed ()
{
return Speed;
}
public String getMake ()
{
return Make;
}
public int getyearModel ()
{
return yearModel;
}
public void accelerate ()
{
if (Speed !=0)
Speed = Speed 5;
}
public void brake ()
{
if (Speed !=90)
Speed = Speed -5;
}
public void setSpeed(int speed) {
speed = speed;
}
public void accelerateSpeed() {
}
}
And then my runner
public class CarRun {
public static void main (String [] str)
{
Car car1 = new Car(0, "Ford", 2013);
for (int i = 1; i <= 5; i )
{
car1.accelerateSpeed();
System.out.println("Current speed is: " Car.getSpeed());
}
for (int j = 1; j <= 5; j )
{
car1.brake();
System.out.println("Current speed is: " Car.getSpeed());
}
}
}
CodePudding user response:
Your accelerate function's if statement if(speed != 0)
won't let a car who's speed is 0 accelerate.
CodePudding user response:
Your car starts at speed 0, and the accelerate function has a " if (Speed !=0)" clause before incrementing it. Thus the speed is stuck at 0 and never gets incremenred. I would suggest changing that if statement to your intended behavior
CodePudding user response:
If you look closely you'll see that you are initializing the speed variable as 0 as follows:
private static int Speed = 0;
And your accelerate() method won't do anything with a 0 speed car, because of the if clause:
public void accelerate ()
{
if (Speed !=0)
Speed = Speed 5;
}
Another problem is that you're not calling the accelerate method in your program Main as you can see in the line:
car1.accelerateSpeed();
So, for your code to work properly remove the if clause from your accelerate method and change the method call from car1.accelerateSpeed(); to:
car1.accelerate();