gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 20:11:55 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com