【问题标题】:Validate a course code using a method in java使用 java 中的方法验证课程代码
【发布时间】:2018-05-20 04:39:39
【问题描述】:

我必须让我的课程代码进行验证。课程代码设置为数字 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 argument)
        // 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 方法是我正在研究的。这是学术作业。

【问题讨论】:

  • 您可以将输入的课程放入一个数组中,然后检查该数组中的重复课程。
  • 另外,你永远不会检查任何等于thirdChoice 的东西,我很困惑这些变量到底代表什么。如果还没有做出选择,他们有什么价值?用户可以更改现有选择吗?这如何“比较”?
  • 我还没有测试第三个选择。我正在测试它,看看它是否会比较它,因为我目前已经对其进行了编码,但它没有。我们还没有在课堂上学习数组。我如何将它们放入字符串并将它们与字符串进行比较?
  • 我会说不要尝试字符串。我认为你应该改变你的 main 方法来运行显式测试,使用不同的值来执行 validate 方法,这样你就可以快速有效地测试它。尝试手动输入所有可能的组合既困难又缓慢。
  • 我同意它们既难又慢,但我们的作业说我们必须在 validateCourse 方法中完成。

标签: java class validation methods numbers


【解决方案1】:

最好去掉那些firstChoicesecondChoicethirdChoice变量,改用同构集合:

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);
    }
}

【讨论】:

    【解决方案2】:

    您需要在代码中编写 3 种不同的验证:

    
    public static int ValidateChoice(int choice, int firstChoice, int secondChoice, int thirdChoice, int totalCredit) {
    
            //Validation: Choice is in range of 1 and 7
            if(choice > 7 || choice < 1){
                return -1;
                
            }
    
            // Validation : No 2 course choices have same value
            boolean isInvalid  = firstChoice!=0 ? 
            (firstChoice == secondChoice ||firstChoice == thirdChoice):
            (secondChoice!=0 && secondChoice==thirdChoice);
    
            if(isInvalid) {
              return -2;
            }
            // Validation : Total credits are not more than 9
            else if(totalCredit > 9){
                return -3;
            }
            else{
               return 0;  
            }
           
    }
    

    你的一位同学也在这里问过这个问题,

    Validating inputs in a function in java to avoid duplicate data other than non entry with default of 0 (No database )

    小心抄袭

    【讨论】:

    • 点评来源: 嗨,这篇文章似乎没有为问题提供quality answer。请编辑您的答案并为您的源代码提供和解释,或者将其作为对问题/其他答案的评论发布。此外,虽然链接是分享知识的好方法,但如果它们在未来被破坏,它们将不会真正回答问题。请记住始终保留指向原始解决方案网站的链接引用。见:How do I write a good answer?
    【解决方案3】:

    使用给我的参数,并且只允许更改 ValidateChoice 方法,我能够采用 John McClane 的答案并将其转换以使其工作。我感谢你的帮助。我所做的很简单,现在很有意义。

    这里是:

    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 argument)
        // 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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-11
      • 1970-01-01
      • 1970-01-01
      • 2014-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-11
      相关资源
      最近更新 更多