Write a menu-driven Java program to accept a global speed limit and the speeds of two cars. The user should be able to update the speeds as many times he wishes. Whenever the speed of one car exceeds the limit, it should be notified. The program should be implemented with the help of a static methods and a static attribute.
/* Nandakumar Edamana
* 30 Sep 2018
*/
import java.io.*;
class Car {
private static int maxSpeed;
private int speed;
public static void setMaxSpeed(int maxSpeed) {
Car.maxSpeed = maxSpeed;
}
public void setSpeed(int speed) {
this.speed = speed;
if((this.speed > Car.maxSpeed))
System.out.println("OVERSPEED!");
}
}
public class SpeedCheck {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Car car1 = new Car();
Car car2 = new Car();
int op;
while(true) {
System.out.print("\nOPTIONS:\n\t1 - Set the global speed limit\n\t2 - Enter the speed of Car1\n\t3 - Enter the speed of Car2\n\t4 - Quit\n\nEnter your choice: ");
op = Integer.parseInt(br.readLine());
switch(op) {
case 1:
System.out.print("Enter the global speed limit: ");
Car.setMaxSpeed(Integer.parseInt(br.readLine()));
break;
case 2:
System.out.print("Enter the speed of Car1: ");
car1.setSpeed(Integer.parseInt(br.readLine()));
break;
case 3:
System.out.print("Enter the speed of Car2: ");
car2.setSpeed(Integer.parseInt(br.readLine()));
break;
case 4:
return;
default:
System.out.print("Invalid choice.");
}
}
}
}
Keywords (click to browse): static static-methods static-variables static-members class java oop examples java-programming programming development