Проверьте код курса, используя метод в Java - PullRequest
0 голосов
/ 20 мая 2018

Мне нужно получить код курса для подтверждения.Код курса установлен в число 1-7, и выбор должен быть в пределах этого диапазона.Каждый курс стоит 3 кредита.Пользователь не может зарегистрироваться для получения более 9 кредитов.Пользователь не может зарегистрироваться на один и тот же курс более одного раза.У меня проблемы с повторным кодом курса.

Вот мой код:

package u6a1_consoleregisterforcourse;

import java.util.Scanner;

public class U6A1_ConsoleRegisterForCourse {

    public static void main(String[] args) {

        System.out.println("Quenten's Copy");

        Scanner input = new Scanner(System.in);

        //choice is the current menu selection
        //firstChoice is the first menu selection mande by the user
        //secondChoice is the second menu selection mande by the user
        //thirdChoice is the third menu selection mande by the user
        // a choice of 0 means the choice has not been made yet
        int choice;
        int firstChoice = 0, secondChoice = 0, thirdChoice = 0;
        int totalCredit = 0;
        String yesOrNo = "";


        do {

            choice = getChoice(input);

            switch (ValidateChoice(choice, firstChoice, secondChoice, thirdChoice, totalCredit)) {
                case -1:
                    System.out.println("**Invalid** - Your selection of " + choice + " is not a recognized course.");
                    break;
                case -2:
                    System.out.println("**Invalid** - You have already registerd for this " +  ChoiceToCourse(choice) + " course.");
                    break;
                case -3:
                    System.out.println("**Invalid** - You can not register for more than 9 credit hours.");
                    break;
                case 0:
                    System.out.println("Registration Confirmed for course " + ChoiceToCourse(choice) );
                    totalCredit += 3;
                    if (firstChoice == 0)
                        firstChoice = choice;
                    else if (secondChoice == 0)
                        secondChoice = choice;
                    else if (thirdChoice == 0)
                        thirdChoice = choice;
                    break;
            }

            WriteCurrentRegistration(firstChoice, secondChoice, thirdChoice);

            System.out.print("\nDo you want to try again? (Y|N)? : ");

            yesOrNo = input.next().toUpperCase();

        } while (yesOrNo.equals("Y"));

        System.out.println("Thank you for registering with us");

    }


    public static int getChoice(Scanner input) {
        System.out.println("Please type the number inside the [] to register for a course");
        System.out.println("[1]IT4782\n[2]IT4784\n[3]IT4786\n[4]IT4789\n[5]IT2230\n[6]IT3345\n[7]IT3349");
        System.out.print("Enter your choice : ");
        return (input.nextInt());

    }

    //This method validates the user menu selection
    //against the given registration business rules
    //it returns the following code based on the validation result
    // -1 = invalid, unrecognized menu selection
    // -2 = invalid, alredy registered for the course
    // -3 = invalid, No more than 9 credit hours allowed
    // 0 = menu selection is valid
    public static int ValidateChoice(int choice, int firstChoice, int secondChoice, int thirdChoice, int totalCredit) {

        // TO DO - Add Code to:
        // Validate user menu selection (the int choice method arguement)
        // against the given registration business rules
        int ValidateChoice;

        if ((choice < 1) || (choice >= 8)){
            ValidateChoice = -1;}
        else if (secondChoice == firstChoice){
            ValidateChoice = -2;}



        else
        {ValidateChoice = 0;}




        return ValidateChoice;

    }

    public static void WriteCurrentRegistration(int firstChoice, int secondChoice, int thirdChoice) {

        if (firstChoice == 0)
            System.out.println("Current course registration:  { none } " );     
        else if (secondChoice == 0)
            System.out.println("Current course registration: { " + ChoiceToCourse(firstChoice) + " }" );
        else if (thirdChoice == 0)
            System.out.println("Current course registration: { " + ChoiceToCourse(firstChoice) + 
                    ", " + ChoiceToCourse(secondChoice) + " }");
        else
            System.out.println("Current course registration: { " + ChoiceToCourse(firstChoice) + 
                    ", " + ChoiceToCourse(secondChoice) + ", " + ChoiceToCourse(thirdChoice) + " }");
    }

    public static String ChoiceToCourse(int choice) {
            String course = "";
            switch (choice)
            {
                case 1:
                    course = "IT4782";
                    break;
                case 2:
                    course = "IT4784";
                    break;
                case 3:
                    course = "IT4786";
                    break;
                case 4:
                    course = "IT4789";
                    break;
                case 5:
                    course = "IT2230";
                    break;
                case 6:
                    course = "IT3345";
                    break;
                case 7:
                    course = "IT3349";
                    break;
                default:
                    break;
            }
            return course;
    }

}

Метод ValidateChoice, над которым я работаю.Это для академического задания.

Ответы [ 2 ]

0 голосов
/ 20 мая 2018

С параметрами, которые мне дали, и которые позволили изменить только метод ValidateChoice, я смог взять ответ Джона Макклейна и преобразовать его, чтобы он работал.Я благодарю вас за помощь.То, что я сделал, просто и теперь имеет смысл.

Вот оно:

public static int ValidateChoice(int choice, int firstChoice, int secondChoice, int thirdChoice, int totalCredit) {

    // TO DO - Add Code to:
    // Validate user menu selection (the int choice method arguement)
    // against the given registration business rules


    if ((choice < 1) || (choice >7))
        return  -1;
    if ((choice == secondChoice) || (choice == firstChoice))
        return -2;
    if (totalCredit >= 9)
        return -3;

    return 0;
}
0 голосов
/ 20 мая 2018

Лучше избавиться от этих firstChoice, secondChoice, thirdChoice переменных и использовать вместо этого однородную коллекцию:

package u6a1_consoleregisterforcourse;

import java.util.*;

public class U6A1_ConsoleRegisterForCourse {
    public static final int CREDITS_PER_COURSE = 3;
    public static final int MAX_CREDITS = 9;
    public static final int MAX_COURSES = MAX_CREDITS / CREDITS_PER_COURSE;
    private final List<Integer> registeredCourses = new ArrayList<>(MAX_COURSES);
    private int totalCredit;

    public static void main(String[] args) {
        System.out.println("Quenten's Copy");
        U6A1_ConsoleRegisterForCourse registrar = new U6A1_ConsoleRegisterForCourse();
        Scanner input = new Scanner(System.in);
        //choice is the current menu selection
        int choice;
        String yesOrNo;
        do {
            choice = getChoice(input);
            switch (registrar.validateChoice(choice)) {
                case -1:
                    System.out.println("**Invalid** - Your selection of " + choice + " is not a recognized course.");
                    break;
                case -2:
                    System.out.println("**Invalid** - You have already registered for this " + choiceToCourse(choice) + " course.");
                    break;
                case -3:
                    System.out.println("**Invalid** - You can not register for more than " + MAX_CREDITS + " credit hours.");
                    break;
                case 0:
                    System.out.println("Registration Confirmed for course " + choiceToCourse(choice));
                    registrar.totalCredit += CREDITS_PER_COURSE;
                    registrar.registeredCourses.add(choice);
                    break;
            }
            registrar.writeCurrentRegistration();
            System.out.print("\nDo you want to try again? (Y|N)? : ");
            yesOrNo = input.next().toUpperCase();
        } while (yesOrNo.equals("Y"));
        System.out.println("Thank you for registering with us");
    }

    private static final String[] courses = {"IT4782", "IT4784", "IT4786", "IT4789", "IT2230", "IT3345", "IT3349"};

    public static String choiceToCourse(int choice) {
        return courses[choice - 1];
    }

    public static int getChoice(Scanner input) {
        System.out.println("Please type the number inside the [] to register for a course");
        for (int i = 1; i <= courses.length; i++)
            System.out.format("[%d]%s%n", i, choiceToCourse(i));
        System.out.print("Enter your choice : ");
        return (input.nextInt());
    }

//    This method validates the user menu selection
//    against the given registration business rules
//    it returns the following code based on the validation result
//     -1 = invalid, unrecognized menu selection
//     -2 = invalid, alredy registered for the course
//     -3 = invalid, No more than 9 credit hours allowed
//     0 = menu selection is valid
    public int validateChoice(int choice) {
        if ((choice < 1) || (choice > courses.length))
            return -1;
        if (registeredCourses.contains(choice))
            return -2;
        if (totalCredit + CREDITS_PER_COURSE > MAX_CREDITS)
            return -3;
        return 0;
    }

    public void writeCurrentRegistration() {
        StringBuilder sb = new StringBuilder("Current course registration: ");
        if (registeredCourses.isEmpty())
            sb.append(" { none }");
        else {
            sb.append("{ ");
            boolean first = true;
            for (int i : registeredCourses) {
                if (first)
                    first = false;
                else
                    sb.append(", ");
                sb.append(choiceToCourse(i));
            }
            sb.append(" }");
        }
        System.out.println(sb);
    }
}
...