Return positive values only
Hi,
I am new to JAVA and i am about half way through a JAVA course and i have been set a challenge by my tutor but i can't figure it out on my own :eek:
I have writen some code that relates to cars, it takes the velocity and it can amend the return value depending on if it accelerates, brakes or stops (as you will see in the code below)
I've been asked to look in more details at the outcome if the velocity is lower then the braking value (which will return a negative value) how do i make it return 0 instead of returning a negative value.
This is my code i used for marking so it does contains things that are not needed for my above question but please ignore them. In its current form it returns posative numbers but if i changed the velocity or brake to make it return a negative value...
Any help would be great!!!
file 1 - Car.java
public class Car
{
int velocity;
public Car()
{
velocity = 55;
System.out.println("Inside default constructor");
}
public void accelerate()
{
velocity += 10;
}
public void brake()
{
velocity -= 20;
}
public void stop()
{
velocity = 0;
}
public void setVelocity(int newVelocity)
{
velocity = newVelocity;
}
public int getVelocity()
{
return velocity;
}
public Car(int a)
{
velocity = a;
System.out.println("Inside other constructor");
}
}
File 2 - CarProgram.java
public class CarProgram
{
public static void main(String [] args)
{
Car porsche = new Car();
porsche.setVelocity(55);
System.out.println(porsche.getVelocity());
porsche.accelerate();
System.out.println(porsche.getVelocity());
porsche.brake();
System.out.println(porsche.getVelocity());
porsche.stop();
System.out.println(porsche.getVelocity());
Car ford = new Car(30);
ford.setVelocity(30);
System.out.println("The initial velocity is " + ford.getVelocity());
}
}