Java Vehicle Management Program: Cars, Trucks and Buses

Computer science2.65 KB

Java Vehicle Management Program

The following Java code reads input from the console to manage a fleet of vehicles, including cars, trucks, and buses.

Source Code

import java.util.Scanner;

public class Automoviles {
    public static void main(String[] args) {
        try {
            Scanner entrada = new Scanner(System.in);
            String linea;

            // Reading the maximum number of vehicles
            System.out.println("Insert maximum");
            int max;
            linea = entrada.nextLine();
            max = Integer.parseInt(linea);

            // Reading options
            System.out.println("1 -> Car; 2 -> Truck; 3 -> Bus; 4 -> All");
            linea = entrada.nextLine();
            int op = Integer.parseInt(linea);

            Mecanico vehiculos = new Mecanico(max);
            Coche cochecito = new Coche(1234, 12, 03, 2017, 4);
            vehiculos.insertar(cochecito);

            Autobus bus = new Autobus(90, 1234, 21, 04, 2011);

            Niños niño = new Niños(9, "C.E.I.P. ATIN", "Samuel", 35684712);
            bus.subir();

            vehiculos.insertar(bus);
            vehiculos.borrar(0);

            switch (op) {
                case 2:
                    vehiculos.mostrarTipo(op);
                    break;
                case 3:
                    vehiculos.mostrarTipo(op);
                    break;
                case 4:
                    System.out.println(vehiculos.toString());
                    break;
                default:
                    System.out.println("Error");
            }

            System.out.println("Enter: 1 -> children, 2 -> adults");
            linea = entrada.nextLine();
            int op1 = Integer.parseInt(linea);
            switch (op1) {
                case 1:
                    bus.pers1toString(op1);
                    break;
                case 2:
                    bus.pers1toString(op1);
                    break;
            }
        } catch (noHayEspacio e) {
            System.err.println(e.getMessage());
        } catch (PosicionIncorrecta ex) {
            System.out.println(ex.getMessage());
        } catch (Exception exc) {
            System.out.println(exc.getMessage());
        }
    }
}

Notes

  • The Scanner reads user input from the console.
  • The Mecanico class manages the vehicle collection.
  • Custom exceptions noHayEspacio and PosicionIncorrecta handle errors.
  • Each case with a break prevents unintended fall-through.

Download

PDF Word HTML