在下面的switch语句的case 5中,我希望用户从数组中输入一个学生,并从模块数组中选择一个模块,以便在不重复的情况下注册他们。任何想法/例子都会非常有用。提前谢谢。
控件类:
import java.util.Scanner;
public class Control {
public void run() {
while (true) {
Menu menu = new Menu();
menu.getMainMenu();
try {
Scanner scan = new Scanner(System.in);
int selection = scan.nextInt();
switch (selection) {
case 1:
for (Student student : students) {
System.out.print(student.getName() + " ");
}
break;
case 2:
for (Module module : modules) {
System.out.print(module.getName() + " ");
}
break;
case 3:
...
case 4:
...
case 5:
// Print out students
System.out.println("select a student: ");
for (int i = 0; i < students.length; i++) {
System.out.println(i + " " + students[i]);
}
selection = scan.nextInt();
############################
Confusion here
############################
case 6:
System.out.println("Goodbye!");
System.exit(0);
break;
default:
System.out.println("Invalid option selected. You must enter a number between 1 & 6!");
} // end switch
} catch (Exception e) {
System.out.println("Invalid entry. You must enter a number between 1 & 6");
}
} // end while
}
}发布于 2011-12-02 02:22:03
如果你想避免重复,不要使用数组或列表。使用集合。
发布于 2011-12-02 02:33:33
您可以使用set implementation (HashSet,LinkedHashSet)来避免重复。
或者使用ArrayList。但在这种情况下,请检查
list.contains(obj)插入前
使用HashSet时,您将不知道插入的顺序。但是使用LinkedHashSet和ArrayList,您可以
如果需要,你可以使用
toArray()Set或ArrayList中的函数将列表转换为数组
发布于 2011-12-02 02:38:02
在您的示例中,学生的标识符和唯一性测试是姓名(jane/alex/mike)。
如果使用名称作为索引的HashMap,则向HashMap添加(使用.put)将添加If new,但如果重复,则不会重复。
您可能想要考虑重写equals()和hashCode()来告诉Java如何确定两个学生是否相同。如果你有两个同名的不同学生,那么名字本身就会给你带来问题。
https://stackoverflow.com/questions/8346245
复制相似问题