/** * Simulation of a car, with methods to read the * car data and to convert the car data to a String */ import java.util.*;
public class Car1 {
public String owner; // owner's name public String license; // license plate public int speed; // current speed
/** * Read the data for a car from the user, * using screen prompts and scanner input. */ public void readInput() { Scanner keyboard = new Scanner(System.in); System.out.println("Who is the owner of the car?"); owner = keyboard.nextLine();
System.out.println("What is the license plate?"); license = keyboard.nextLine();
System.out.println("What is the speed?"); speed = keyboard.nextInt( );
/* * Keep reading speed until user enters * a nonnegative number */ while (speed < 0) { System.out.println("Speed cannot be negative."); System.out.println("Reenter speed:"); speed = keyboard.nextInt(); } }
/** * Return a String containing the car data */ public String toString() { String carData = "Owner: " + owner + "\n"; carData += "License: " + license + "\n"; carData += "Speed = " + speed + "\n";
return carData; } }
|
/** * A program to demonstrate the Car1 class by * instantiating 3 cars, getting user input * for all 3, and finally printing each car. */
public class Car1Demo {
public static void main(String[] args) { Car1 carA = new Car1(); Car1 carB = new Car1(); Car1 carC = new Car1();
System.out.println("Enter data for carA:"); carA.readInput();
System.out.println("\nEnter data for carB:"); carB.readInput();
System.out.println("\nEnter data for carC:"); carC.readInput();
System.out.println("\nWe created 3 car objects:"); System.out.println(carA); System.out.println(carB); System.out.println(carC); } }
|