名前を配列に格納するメニューをコーディングしてから、生徒を追加/削除したり、特定の生徒を検索したりするオプションを提供していますが、他の場所で使用できるように配列を設定する方法がわからないようです。たとえば、私のコードでは、オプション1を使用した場合にのみ名前を入力できますが、オプション3を選択して配列内の名前を検索すると、これらの名前が配列に保持されず、nullとして表示されます。アレイ内のすべてのスロットに対して。
私が抱えているもう1つの問題は、生徒を削除する方法です。名前が配列の最後にある場合は明らかに簡単ですが、名前が中央にある場合は、名前を削除してシフトするにはどうすればよいでしょうか。アレイにギャップがないように、他のすべての名前を1つのスロットに配置しますか?
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);
}
}