530,881 views
42 votes
42 votes
Write a Java program to create a class called Cars. The class should include three instance variables: makes (type: String), models (type: String), and years (type: int); and two methods: a constructor() to initialize three variables and a show() to display the information of a car. Write a class called TestCars to test the class Cars. This class should be able to read the makes, models, and years of three cars from screen input, create three-car objects using the constructor() and display each car's make, model, and years using the show(). (5pts)

User Steve F
by
2.7k points

1 Answer

5 votes
5 votes

Answer:

Step-by-step explanation:

This code was written in Java. It creates the Cars class with the requested variables and methods. It also creates the TestCars class which asks the user for the necessary inputs and then creates three Cars objects and passes the input values to the constructors. Finally, it uses the show() method on each object to call the information. A test has been created and the output can be seen in the attached image below.

import java.util.Scanner;

class TestCars{

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

System.out.print("Enter Car Make: ");

String make1 = in.next();

System.out.print("Enter Car Model: ");

String model1 = in.next();

System.out.print("Enter Car Year: ");

int year1 = in.nextInt();

System.out.print("Enter Car Make: ");

String make2 = in.next();

System.out.print("Enter Car Model: ");

String model2 = in.next();

System.out.print("Enter Car Year: ");

int year2 = in.nextInt();

System.out.print("Enter Car Make: ");

String make3 = in.next();

System.out.print("Enter Car Model: ");

String model3 = in.next();

System.out.print("Enter Car Year: ");

int year3 = in.nextInt();

Cars car1 = new Cars(make1, model1, year1);

Cars car2 = new Cars(make2, model2, year2);

Cars car3 = new Cars(make3, model3, year3);

car1.show();

car2.show();

car3.show();

}

}

class Cars {

String makes, models;

int years;

public Cars(String makes, String models, int years) {

this.makes = makes;

this.models = models;

this.years = years;

}

public void show() {

System.out.println("Car's make: " + this.makes);

System.out.println("Car's model: " + this.models);

System.out.println("Car's year: " + this.years);

}

}

Write a Java program to create a class called Cars. The class should include three-example-1
User Themightyjon
by
3.5k points