How do I validate the user's input for when you enter a year , the range must be between 1900-2021. I am also confused with using the for loop within my situation. I need to print out the motorcycle accelerating four times and then right after I need the code to print out it braking/deaccelerating 3 times. I have a java class and a Java main class. I tried implementing a separate method to validate year but it ended up crashing the program.
public class Motorcycle {
private int year;
private String make;
private int speed;
/**
*
* @param year
* @param make
*/
public Motorcycle(int year, String make) {
this.year = year;
this.make = make;
this.speed = 0;
}
public Motorcycle(){
this.year = 0;
this.make = "";
this.speed = 0;
}
public void setYear(int year) {
this.year = year;
}
public void setMake(String make) {
this.make = make;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public int getYear() {
return year;
}
public String getMake() {
return make;
}
public int getSpeed() {
return speed;
}
public void accelerate() {
this.speed += 5;
}
public void brake() {
this.speed -= 5;
}
@Override
public String toString() {
return "A " + year +" " + make + " going "+ speed +" miles per hour";
import java.util.*;
public class MotorcycleDemo {
public static void main(String[] args) {
int year;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the year of your Motorcycle"); //validate year 1900 -2021
year = keyboard.nextInt();
System.out.println("Enter the make of your Motorcycle(such as, Harley, Kawasaki)");
String maker = keyboard.next();
Motorcycle motor1 = new Motorcycle(year, maker);
System.out.println(motor1); //account for 0 speed toString()
for (int i = 0; i <= 3; i++) { //use for loop //accelerate 4 times and brake 3 times
motor1.accelerate();
System.out.println(motor1);
//System.out.println("A " + year + " " + maker + " going " + motor1.getSpeed() + "miles per hour.");
//to String method
}
for (int i = 0; i <= 3; i++);
{
motor1.brake();
System.out.println(motor1);
}
}
}
If the motorcycle accelerates 4 times and brakes three times, then the output should display: "A year and make (motorcycle brand) is going speed mph. Starting at speed 0 mph and reaching max speed of 20 and then deaccelerating 4 times concluding the speed to be 5 mph.
Any help is appreciated and thanks in advance. :)