Как установить длину массива в переменную, Java - PullRequest
1 голос
/ 25 апреля 2020

Итак, я делаю небольшую программу и не могу установить длину массива String в соответствии с размером, указанным пользователем. Как вы хотите назначить значение, которое пользователь вводит в длину массива? У меня есть основной класс для пользовательского ввода, который передается в демонстрационный класс для хранения и выполнения нескольких различных вычислений и т. Д. c. Входом mac_attendee_limit будет размер массива

Основной класс

public class ProgMgmtSys {

private static Scanner sc = new Scanner(System.in);

public static void displayMenu() {
    System.out.println("\nMoolort Heritage Railway Demonstration Booking System\n");
    System.out.println("Menu");
    System.out.println("A: Add Demonstration");
    System.out.println("B: Add Attendee");
    System.out.println("C: Print Demonstration");
    System.out.println("D: Print Attendee");
    System.out.println("E: Select & Print Cost");
    System.out.println("Q: quit");
    System.out.print("Please enter your selection: ");
}

public static void addNewDemonstration(Demonstration demonstration) {

    String  identifier, title;
    double base_fee;
    int max_attendee_limit, start_time, duration;

    System.out.println("New Demonstration Creater");
    System.out.println("Enter an Identifier");
    identifier = sc.nextLine();
    System.out.println("Enter a Title");
    title = sc.nextLine();
    System.out.println("Enter the Base Fee");
    base_fee = sc.nextDouble();
    System.out.println("Enter the Macimum Attendee Limit");
    max_attendee_limit = sc.nextInt();
    System.out.println("Enter the Start Time");
    start_time = sc.nextInt();
    System.out.println("Enter the Duration");
    duration = sc.nextInt();

    demonstration.newDemonstration(identifier, title, base_fee, max_attendee_limit, start_time, duration);  

}

public static void newAttendeeBooking(Demonstration demonstration) {

    String attendeeName, attendeePhoneNumber, membershipType;

    System.out.println("New Attendee Booking");
    System.out.println("Enter Attendee Name: ");
    attendeeName  = sc.nextLine();
    System.out.println("Enter Attendee Phone Number: ");
    attendeePhoneNumber = sc.nextLine();
    System.out.println("Please enter discount type if applicable [concession, fsrs, arhs, mhr]: ");
    membershipType = sc.nextLine().toLowerCase();

    demonstration.newAttendee(attendeeName, attendeePhoneNumber, membershipType);

}

public static void selectDemonstrationsCost(Demonstration demonstration) {

    String discountType;

    System.out.println("Please Select the type of discount to see the cost for all demonstrations:");
    System.out.print("concession, fsrs, arhs, mhr");
    discountType = sc.nextLine().toLowerCase();

    demonstration.printDemonstrationsCost(discountType);

}


public static void main(String[] args) {
    String choice;
    Demonstration demonstration = new Demonstration();
    do {
        displayMenu();
        choice = sc.nextLine().toUpperCase();
        switch(choice) {
        case "A":
            addNewDemonstration(demonstration);
            break;
        case "B":
            newAttendeeBooking(demonstration);
            break;
        case "C":
            demonstration.printDemonstration();
            break;
        case "D":
            demonstration.printAttendee();
            break;
        case "E":
            selectDemonstrationsCost(demonstration);
            break;

        case "Q":
            System.out.println("Goodbye");
            break;
        default:
            System.out.println("Invalid selection. Please try again.");
        }
    } while (!choice.equals("Q"));      
}

}

Демонстрационный класс

public class Demonstration {

    private String  identifier;
    private String  title;
    private double base_fee;
    private int max_attendee_limit = 0;
    private int start_time;
    private int duration;
    private int newAttendee = 5;

    private String attendeeName[] = new String[max_attendee_limit];
    private String attendeePhoneNumber[] = new String[max_attendee_limit];
    private String membershipType[] = new String[max_attendee_limit];

    //Discount charges for all different societies & concession
    static final double concession_disc = .10; //10% Disc
    static final double fsrs_disc = .20; // 20% Discount
    static final double arhs_disc = .25; // 25% Discount
    static final double mhr_disc = 1.00; // 100% Discount - FREE

    private int i = 0;

    public Demonstration() {

    }

    public void newDemonstration(String identifier, String title, double base_fee, int max_attendee_limit, int start_time, int duration) {

        this.identifier = identifier;
        this.title = title;
        this.base_fee = base_fee;
        this.max_attendee_limit = max_attendee_limit;
        this.start_time = start_time;
        this.duration = duration;   

    }

    public void newAttendee(String attendeeName, String attendeePhoneNumber, String membershipType) {

        if (i < newAttendee) {

            this.attendeeName[i] = attendeeName;
            this.attendeePhoneNumber[i] = attendeePhoneNumber;
            this.membershipType[i] = membershipType;

            i++;
        }       
    }

    public void printDemonstration() {
        System.out.println("Identifier: " + identifier);
        System.out.println("Title: " + title);
        System.out.println("Base Fee: $" + base_fee);
        System.out.println("Maximum Attendee Limit: " + max_attendee_limit);
        System.out.println("Start Time: " + start_time);
        System.out.println("Duration: " + duration);

    }

    public void printAttendee() {

        for (int j=0;j< i;j++){

            System.out.println("Attendee Name: " + attendeeName[j]);
            System.out.println("Attendee Phone number: " + attendeePhoneNumber[j]);
            System.out.println("Membership Type: $" + membershipType[j]);

        }

    }
}

1 Ответ

3 голосов
/ 25 апреля 2020

Я думаю, вам нужно инициализировать массив внутри функции. Это потому, что если вы поместите его в глобальный. Когда вы создаете класс Demonstration demonstration = new Demonstration();, в это время создается глобальный массив. Тогда, хотя вы измените max_attendee_limit, он не изменит размер массива.

вы можете сделать это:

public void newDemonstration(String identifier, String title, double base_fee, int max_attendee_limit, int start_time, int duration) {

        this.identifier = identifier;
        this.title = title;
        this.base_fee = base_fee;
        this.max_attendee_limit = max_attendee_limit;
        this.start_time = start_time;
        this.duration = duration;   

        attendeeName = new String[max_attendee_limit];
        attendeePhoneNumber = new String[max_attendee_limit];
        membershipType = new String[max_attendee_limit];
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...