The Scanner
class is used in Java to read input from various sources, including the keyboard, files, and network sockets.
Here’s an example of how the Scanner
class can be used to read information about cars:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
import java.util.Scanner; class Car { private String make; private String model; private int year; private int speed; public Car(String make, String model, int year, int speed) { this.make = make; this.model = model; this.year = year; this.speed = speed; } public String getMake() { return make; } public String getModel() { return model; } public int getYear() { return year; } public int getSpeed() { return speed; } @Override public String toString() { return make + " " + model + " " + year + " " + speed; } } public class CarScannerExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter car make: "); String make = scanner.nextLine(); System.out.print("Enter car model: "); String model = scanner.nextLine(); System.out.print("Enter car year: "); int year = scanner.nextInt(); System.out.print("Enter car speed: "); int speed = scanner.nextInt(); Car car = new Car(make, model, year, speed); System.out.println("Car: " + car); scanner.close(); } } |
In this example, a Car
class is defined with four fields: make
, model
, year
, and speed
. The main
method creates a Scanner
object to read input from the keyboard, and then prompts the user to enter information about a car. The information is read using the nextLine
and nextInt
methods of the Scanner
class and used to create a Car
object. Finally, the Car
object is printed to the console.