Define a Car class with the following attributes: Id, Brand, Speed, Power.
Define a constructor allowing the attributes of a car object to be initialized
by values passed as parameters. Knowing that Id must be auto-increment.
Define the accessors to the different attributes of the class.
Define the toString () method to display the information of a car.
Write a Java program to test the Car class by creating an array of cars.
Display all their attributes, and give the total number of the cars
package car;
import java.util.Scanner;
public class Car {
private static int Id = 1;
private String Brand;
private double Speed, Power;
Car(){
}
Car(String b, double s, double p){
Id++;
Brand = b;
Speed = s;
Power = p;
}
public String toString(){
return "Id: "+Id+"\nBrand: "+Brand+" \nSpeed: "+Speed+"\nPower: "+Power+"\n";
}
public static void main(String[] args) {
Car c[] = new Car[2];
for(int i=0; i<2; i++){
Scanner scan = new Scanner(System.in);
System.out.println("Enter the car's brand\n");
String brand = scan.nextLine();
System.out.println("Enter the car's power\n");
double power = scan.nextDouble();
System.out.println("Enter the car's speed\n");
double speed = scan.nextDouble();
Car ca = new Car(brand, speed, power);
c[i]= ca;
}
for(int i=0; i<2; i++){
System.out.println("Car number: "+(i+1));
System.out.println(c[i].toString());
}
System.out.println("Total number of cars is: "+2);
}
}
Comments
Leave a comment