Answer to Question #276544 in Java | JSP | JSF for JAD

Question #276544

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


1
Expert's answer
2021-12-07T09:21:22-0500
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);
    }
    
    
    
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS