gpt4 book ai didi

java - 系列/菜单

转载 作者:行者123 更新时间:2023-11-30 09:18:01 26 4
gpt4 key购买 nike

    List<Student> studentInfo = new LinkedList<Student>();

int choice;
boolean flag = true;
Student student = new Student();


while(flag)
{
System.out.println();
System.out.println("Press 1 to Add Student details");
System.out.println("Press 2 to Display Student details");
System.out.println("Press 3 to Sort");
System.out.println("Press 4 to Search");
System.out.println("Press 5 to Exit");
System.out.println("Enter your choice: ");
choice = sc1.nextInt();

switch(choice)
{
case 1: studentInfo.add(student.addDetails());
break;

case 2: System.out.println("Details of Students are as follows: ");
for(Student s : studentInfo){
System.out.println(s);
}
break;
//More code

Student类中的addDetails()方法是:

        public Student addDetails() 
{
System.out.println("Enter the name: ");
name = sc2.nextLine();
this.setName(name);
return this;
}

我正在使用案例 1 block 获取学生详细信息,然后将它们添加到 studentInfo 集合中。但是,当我显示最后输入的详细信息时,会覆盖所有以前的详细信息,而当我将它们打印出来时,只会显示我添加的学生数量。有人可以告诉我我做错了什么吗?谢谢!

输出:学生详情如下:姓名=Amar,年龄=0,学期=0,sub_1_marks=0,sub_2_marks=0,sub_3_marks=0,percentage=0,totalMarks=0姓名=Amar,年龄=0,学期=0,sub_1_marks=0,sub_2_marks=0,sub_3_marks=0,percentage=0,totalMarks=0

最佳答案

您不确定此问题的答案这一事实意味着它的答案可能会随着您的代码开发而改变。如果您专注于您的代码随着时间的推移而发展这一事实,您通常会看到正确的路径。

对我来说,这段代码已经有问题了。事实上,如果您想添加一个新的菜单选项,您将不得不在两个不同的地方添加代码(打印列表和 case 语句)。

我会首先将这两个领域拉回到一个单一的行动列表中。像这样:

static boolean exit = false;

enum Action {
AddDetails("Add student details") {
@Override
public void doIt() {
// How to add details.
}

},
DisplayDetails("Display student details") {
@Override
public void doIt() {
// How to display details.
}

},
SortDetails("Sort") {
@Override
public void doIt() {
// How to sort details.
}

},
SearchDetails("Search") {
@Override
public void doIt() {
// How to search details.
}

},
Exit("Exit") {
@Override
public void doIt() {
// How to exit.
exit = true;
}

};
private final String description;

Action(String description) {
this.description = description;
}

public String getDescription() {
return description;
}

public abstract void doIt();

}

public static void main(String args[]) {
try {
Scanner sc1 = new Scanner(System.in);
do {
// Show my menu.
for (Action a : Action.values()) {
System.out.println("Press " + a.ordinal() + " to " + a.getDescription());
}
System.out.println("Enter your choice: ");
int choice = sc1.nextInt();
// Should really do some range checks here.
Action action = Action.values()[choice];
// Perform the chosen function.
action.doIt();
} while (!exit);
} catch (Throwable t) {
t.printStackTrace(System.err);
}
}

因此 - 在回答您的问题时 - 使用 static methods 机制但仅使用概念。如果您有许多不同的操作,Enum 是一个很好的替代品。

关于java - 系列/菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18739364/

26 4 0