java - 打印字符串,接受用户输入并使用私有(private)字符串方法验证它?

标签 java methods

对于我的编程课,我有以下作业:

In this assignment you will write a program that will model a pet store. The program will have a Pet class to model individual pets and the Assignment5 class will contain the main and act as the pet store. Users will be able to view the pets, make them age a year at a time, add a new pet, and adopt any of the pets.

我已经完成了 Pet 类(class),但在作业的这个特定步骤中遇到了困难:

Create a private static String method which prints out the main menu of the program. It then accepts a String from the user and returns their choice. The commands to list are as follows. a. List the pets in the store. b. Age up the pets. c. Add a new pet. d. Adopt a pet. e. Quit. i. Your method must verify that the user typed in a valid input before returning the input.

private static String mainMenu(){
    return "\n" + "A. List the pets in the store." +
                    "\n" + "B. Age up the pets" + 
                    "\n" + "C. Add a new pet" + 
                    "\n" + "D. Adopt a pet" + 
                    "\n" + "E. Quit";
}

问题是我找不到打印菜单并接受和验证用户输入的方法。你能帮我将下面的代码合并到我的私有(private)方法中吗?

// Ask for letter 
    System.out.println("Type the letter to make your selection." + mainMenu());
    char letter = Character.toUpperCase((scan.next().charAt(0)));

    // Check if letter is valid. If not, ask the user to input another letter.
    while (!(letter >= 'A' && letter <= 'E')){
        System.out.println("That is not one of the options. Input another letter.");
        letter = Character.toUpperCase((scan.next().charAt(0)));
    }

最佳答案

我不确定您的扫描仪现在在哪里声明,但您想要如下所示的内容

private static String mainMenu(Scanner scan){
    String menu = "\n" + "A. List the pets in the store." +
            "\n" + "B. Age up the pets" +
            "\n" + "C. Add a new pet" +
            "\n" + "D. Adopt a pet" +
            "\n" + "E. Quit";

    System.out.println("Type the letter to make your selection." + menu);
    char letter = Character.toUpperCase((scan.next().charAt(0)));

    // Check if letter is valid. If not, ask the user to input another letter.
    while (!(letter >= 'A' && letter <= 'E')){
        System.out.println("That is not one of the options. Input another letter.");
        letter = Character.toUpperCase((scan.next().charAt(0)));
    }

    return letter + "";
}

我使用 return letter + ""; 因为 letter 是一个字符,而你的函数返回一个字符串,所以转换它的一个简单方法是连接空引号

似乎您已经声明了一个扫描仪,在这种情况下您可以像我一样将其作为参数传递,或者您可以为扫描仪提供一个实例变量,最终这部分取决于您如何拥有其余部分你的类(class)结构

关于java - 打印字符串,接受用户输入并使用私有(private)字符串方法验证它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46573137/

相关文章:

java - 将List传输到Java Stream中,然后删除List中的一个元素。出现一些错误

java - math.round *1000/1000 没有意义是否有原因

java - 我应该为 Java 图形使用什么 IDE?

java - 如何在 Java 中重置、清除或撤消 DrawLine

c++ - 如何覆盖嵌套的 C++ 对象方法?

java - 在 Java 中如何从计数器中减去一个值?

PHP 在调用静态方法时使用变量

python - 区分python函数和类函数

java - 当我通过 java 应用程序中的进程运行 pg_restore 时,应用程序卡住

java - 有没有更 Eloquent 方式来编程这个方法?