java学生数组菜单
我正在编写一个菜单,将姓名存储到一个数组中,然后提供添加/删除学生以及搜索特定学生的选项,但我似乎无法找到如何设置数组以便在其他选项中使用,因为,例如,我的代码只允许我在使用选项1时输入姓名,但当我选择选项3在数组中搜索名称时,它不会将这些名称保留在数组中,它只是在数组中的每个插槽中显示为null
另一个问题是我如何删除学生,显然如果名字在数组的末尾很容易,但是如果名字在中间,我怎么能删除名字,把所有其他的名字移到一个时隙,这样数组中就没有空缺了?p>
import java.util.Scanner;
public class Lab10Ex2 {
public static void main(String[] args) {
int choice = 0;
int[] stringArray = {};
do{
String[] stringarray = new String[20];
System.out.println("----------------MENU---------------");
System.out.println();
System.out.println("1. Add Students");
System.out.println("2. Delete Students");
System.out.println("3. Search for student");
System.out.println("4. Print all Students");
System.out.println("5. exit");
Scanner scanchoice = new Scanner(System.in);
choice = scanchoice.nextInt();
if (choice ==1){
Scanner scannames = new Scanner(System.in);
System.out.println("Please enter the student names into the array");
int i = 0;
for(i = 0; i<stringarray.length; i++){
String temp =scannames.nextLine();
stringarray[i]=temp.toLowerCase();
if(i==(stringarray.length-1)){
System.out.println("successfully filled up array fully");
System.out.println();
}
}
}
if(choice==2){
}
if(choice==3){
for(int p = 0; p<stringarray.length; p++){
System.out.println(stringarray[p]);
}
int x=0;
Scanner scannames1 = new Scanner(System.in);
System.out.println("Enter name of student you want to search for: ");
System.out.println();
String search=scannames1.nextLine();
String searchName=search.toLowerCase();
for(int p=0;p<20;p++){
if(searchName.equals(stringarray[p])){
x=1;
}
else{
x=0;
}
}
if(x==1){
System.out.println("We have a match in our database for "+ searchName);
}
else if (x==0){
System.out.println("No match for "+ searchName);
}
}
if (choice ==4){
System.out.println("List of names:");
for(int p = 0; p<stringarray.length; p++){
System.out.println(stringarray[p]);
}
}
}while(choice!=5);
}
}
# 1 楼答案
删除
int[] stringArray
行(您不会在任何地方引用它)将
String[] stringarray
向上移动到循环外至于删除,您要么自己编写代码(将所有内容从数组中的已删除项上移一个),要么使用Java提供的一个集合类(而不是本机数组),它为您处理删除
# 2 楼答案
在你的每一次迭代中{…}循环,您正在重新创建stringarray变量,从而清除它。如果您将其移出循环,您的学生条目将被保留
至于删除,如果不需要使用字符串数组,我建议使用ArrayList。它将允许您轻松删除特定条目,而无需担心其他条目。否则,是的,最简单的方法是将所有其他条目向下移动一个插槽,以避免出现间隙
# 3 楼答案
以下是更正后的代码:
你做错的事情:
如果要避免删除后在数组中浪费空间,请使用ArrayList。如果您使用简单数组绑定到这一点,则可以执行以下操作:
避免硬编码数组长度