자바 코드 질문

자바 코드 질문

작성일 2023.05.15댓글 1건
    게시물 수정 , 삭제는 로그인 필요

import java.text.SimpleDateFormat;
import java.util.*;

class Main {
    public static void main(String[] args) {
        Highway highway = new Highway();

        Scanner scanner = new Scanner(System.in);
        boolean isRunning = true;

        while (isRunning) {
            System.out.print("> 명령 입력: ");
            String command = scanner.nextLine();

            try {
                if (command.startsWith("t")) {
                    // 시간 설정
                    String[] tokens = command.split(" ");
                    int year = Integer.parseInt(tokens[1]);
                    int month = Integer.parseInt(tokens[2]);
                    int day = Integer.parseInt(tokens[3]);
                    int hour = Integer.parseInt(tokens[4]);
                    int minute = Integer.parseInt(tokens[5]);

                    setCurrentTime(highway, year, month, day, hour, minute);
                    System.out.println("현재시간: " + formatTime(highway.getCurrentTime()));
                } else if (command.startsWith("n")) {
                    // 차량 진입
                    String[] tokens = command.split(" ");
                    String number = tokens[1];
                    String entryLocation = tokens[2];
                    String exitLocation = tokens[3];
                    int speed = Integer.parseInt(tokens[4]);

                    enterVehicle(highway, number, entryLocation, exitLocation, speed);
                } else if (command.startsWith("o")) {
                    // 고속도로상의 모든 차량 보기
                    viewAllVehicles(highway);
                } else if (command.startsWith("x")) {
                    // 고속도로를 진출한 모든 차량 정보보기
                    viewExitingVehicles(highway);
                } else if (command.equals("c")) {
                    // 현재 시간 보기
                    System.out.println(formatTime(highway.getCurrentTime()));
                } else if (command.equals("q")) {
                    // 시스템 종료
                    isRunning = false;
                } else {
                    System.out.println("잘못된 명령입니다. 다시 입력해주세요.");
                }
            } catch (Exception e) {
                System.out.println("오류: " + e.getMessage());
            }
        }

        scanner.close();
    }

    // 현재 시간 설정
    private static void setCurrentTime(Highway highway, int year, int month, int day, int hour, int minute) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, day, hour, minute);
        Date currentTime = calendar.getTime();
        highway.setCurrentTime(currentTime);
    }

    // 차량 진입
    private static void enterVehicle(Highway highway, String number, String entryLocation, String exitLocation, int speed) throws Exception {
        Vehicle vehicle = new Vehicle(number, entryLocation, exitLocation, speed);
        highway.enterVehicle(vehicle);
        vehicle.setEntryTime(highway.getCurrentTime()); // 진입 시간 설정
        vehicle.setEntryLocation(entryLocation); // 진입 장소 설정
        vehicle.setExitLocation(exitLocation); // 진출 장소 설정
       
        System.out.println(vehicle.getType() + " " + vehicle.getNumber() + " 진입");
        System.out.println("진입시간: " + formatTime(vehicle.getEntryTime()));
        System.out.println("진입장소: " + vehicle.getEntryLocation());
        System.out.println("진출장소: " + vehicle.getExitLocation());
        System.out.println("시속: " + vehicle.getSpeed() + "km");
    }
    // 고속도로상의 모든 차량 보기
    private static void viewAllVehicles(Highway highway) {
        List<Vehicle> vehicles = highway.getVehicles();

        if (vehicles.isEmpty()) {
            System.out.println("통행 차량이 없습니다!");
            return;
        }

        Collections.sort(vehicles, new VehicleComparator());

        System.out.println("고속도로 상의 모든 차량 정보:");
        int count = 1;
        for (Vehicle vehicle : vehicles) {
            System.out.println(count + ". " + vehicle.getType() + " " + vehicle.getNumber() + " " + vehicle.getDetails()
                    + " 진입시간: " + formatTime(vehicle.getEntryTime()) + " 진입장소: " + vehicle.getEntryLocation()
                    + " 진출장소: " + vehicle.getExitLocation() + " 시속: " + vehicle.getSpeed() + "km");
            count++;
        }
    }

    // 고속도로를 진출한 모든 차량 정보보기
    private static void viewExitingVehicles(Highway highway) {
        List<Vehicle> vehicles = highway.getExitingVehicles();

        if (vehicles.isEmpty()) {
            System.out.println("진출한 차량이 없습니다!");
            return;
        }

        Collections.sort(vehicles, new VehicleComparator());

        System.out.println("고속도로를 진출한 차량 정보:");
        int count = 1;
        for (Vehicle vehicle : vehicles) {
            System.out.println(count + ". " + vehicle.getType() + " " + vehicle.getNumber() + " " + vehicle.getDetails()
                    + " 진입시간: " + formatTime(vehicle.getEntryTime()) + " 진입장소: " + vehicle.getEntryLocation()
                    + " 진출장소: " + vehicle.getExitLocation() + " 진출시간: " + formatTime(vehicle.getExitTime())
                    + " 통행료: " + vehicle.getToll() + "원");
            count++;
        }
    }

    // 시간 포맷팅
    private static String formatTime(Date time) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm");
        return format.format(time);
    }
}

class Vehicle {
    private String number;
    private String entryLocation;
    private String exitLocation;
    private int speed;
    private Date entryTime;
    private Date exitTime;
    private int toll;

    public Vehicle(String number, String entryLocation, String exitLocation, int speed) {
        this.number = number;
        this.entryLocation = entryLocation;
        this.exitLocation = exitLocation;
        this.speed = speed;
        this.entryTime = null;
        this.exitTime = null;
        this.toll = 0;
    }

    public String getNumber() {
        return number;
    }

    public String getEntryLocation() {
        return entryLocation;
    }

    public String getExitLocation() {
        return exitLocation;
    }

    public int getSpeed() {
        return speed;
    }

    public Date getEntryTime() {
        return entryTime;
    }

    public Date getExitTime() {
        return exitTime;
    }

    public int getToll() {
        return toll;
    }
    public void setEntryTime(Date entryTime) {
        this.entryTime = entryTime;
    }

    public String getType() {
        return "차량";
    }
    public String getDetails() {
        // 차량의 세부 정보를 반환하는 로직 추가
        return "";
    }

    // 진입 장소 설정
    public void setEntryLocation(String entryLocation) {
        this.entryLocation = entryLocation;
    }

    // 진출 장소 설정
    public void setExitLocation(String exitLocation) {
        this.exitLocation = exitLocation;
    }
}

// 차량 비교자
class VehicleComparator implements Comparator<Vehicle> {
    @Override
    public int compare(Vehicle v1, Vehicle v2) {
        int typeOrder1 = getTypeOrder(v1);
        int typeOrder2 = getTypeOrder(v2);

        if (typeOrder1 != typeOrder2) {
            return Integer.compare(typeOrder1, typeOrder2);
        }

        return v1.getEntryTime().compareTo(v2.getEntryTime());
    }

    private int getTypeOrder(Vehicle vehicle) {
        if (vehicle instanceof Car) {
            return 1;
        } else if (vehicle instanceof HybridCar) {
            return 2;
        } else if (vehicle instanceof Bus) {
            return 3;
        } else if (vehicle instanceof Truck) {
            return 4;
        }

        return 0;
    }
}

   

자바 코드인데요 실행했을때
n 1234 서울 대전 100 // 1234 차량, 서울->대전, 시속 100km로 주행 승용차 1234 진입 진입시간: 2023/05/10:14:30 // 진입시간은 현재시간과 동일함 진입장소: 서울 진출장소: 대전 시속: 100km 이렇게 나와야하는데

실행시키면 이렇게 나오네요 > 명령 입력: n 1234 서울 대전 100 차량 1234 진입 진입시간: 2023/05/15 14:33 진입장소: ???? 진출장소: ???? 시속: 100km 어떻게 하면 해결할수 있나요 ㅠㅠ 코드 수정좀 부탁드립니다


#자바 코드 #자바 코드 실행 사이트 #자바 코드 컨벤션 #자바 코드 해석 사이트 #자바 코드 정리 #자바 코드 실행 시간 측정 #자바 코드 분석 #자바 코드 정렬 #자바 코드 정렬 사이트 #자바 코드 예시

profile_image 익명 작성일 -

승용차가 차량으로 표시되는 건

옵션을 더 추가해서 다음 소스를 수정해야 할 듯 합니다.

Vehicle vehicle = new Vehicle(number, entryLocation, exitLocation, speed);

=>

Vehicle vehicle = new Car(number, entryLocation, exitLocation, speed);

* Car, Truck, Bus, HybridCar 를 구분해서 Vehicle 객체를 생성하면 됩니다.

입력한 지역이 ????로 표시되는 것은 인코딩 문제 같은데 개발도구 터미널에 따라 다를 것 같은데

java 파일을 UTF-8 인코딩으로 이클립스나 윈도우 cmd 창에서 실행하면 정상 출력 됩니다.

자바 코드 질문이요

... getUserName()) 자바 코드가 이렇게 있으면요 = 오른쪽에 있는 코드들이 User의 생성자로 들어가는건가요? 자바 초보라서 질문드립니다.. 안녕하세요....

간단한 자바코드 질문이요.

... 자바가 처음이라 어렵네요 1번째 반복 0 0 일때 if문에 돌입합니다. if문에서 ++i > 1 && ++j > 1 에 의해서 1 1 이 될 것 처럼 보이지만 사실 ++i > 1 이 False기 때문에...

자바 코드 질문

자바로 시그마로 합이 1000인 첫번째 수와 마지막수 구하는 코드좀 알려주세요 실행 결과 코드는 아래와 같습니다. main 함수의 코드만 전달...

자바 코드 질문

... 이 입력이 너무 불편하기 때문에 자바는 Scanner이라는 클래스를 제공을 하고 있습니다. 그리고 꼭 아스키 코드값으로 해야하나 싶구요. 질문에...

자바 코드 질문입니다. (급함)

... 자바 코드 오류 질문 드립니다. 1~10000의 합을 구하는 코드이고 밑은 코드를 수행하는데 걸리는 시간은 얼마인지 구하는 코드입니다. 보시면 1~10000의...

자바 코드 질문합니다.

자바코드를 이렇게 쓰면 .. public class App { public static void main(String[] args) throws Exception { int N,sum=0; for(N=1;N<=1000;N=N+5){ System.out.println(N+"-"+(N+1)...

자바 코드 질문입니다.

... 아래의 로직에 맞게 코드를 작성하시오 1.1 가진 돈과 물건의 가격을... 자바에서 배열은 객체로 다루어집니다. 질문에서 cart나 tmp 나 1차원 배열을 참조하는...