gpt4 book ai didi

java - 为什么数组值没有在 switch case 中保留?

转载 作者:行者123 更新时间:2023-12-01 18:09:46 25 4
gpt4 key购买 nike

为什么数组值没有保存在我的 switch 函数中?首先我按下 1,创建我的名册值。创建值后,按 2 会导致 ArrayOutOfBound 错误。谁能告诉我我做错了什么?

请忽略 FileNotFoundExceptions。在修复我做错的事情后需要处理该部分。

public static Scanner keyboard = new Scanner(System.in);
public static int numStudents;
public static String[] nameOfStudent;
public static int[] broncoID;
public static int[] grade;

^ 这些是我声明的变量

public static void main(String[] args) throws FileNotFoundException {

startMenus(keyboard);
}

public static void startMenus(Scanner sc) throws FileNotFoundException {
while (true) {
System.out.println("(Enter option # and press ENTER)\n");
System.out.println("1. Create new Roster");
System.out.println("2. Display Current Roster");

int option = sc.nextInt();

sc.nextLine();

switch (option) {
case 1:
createRoster();
break;
case 2:
displayRoster();
break;
default:
System.out.println("Unrecognized Option!\n");
}
}
}

public static void createRoster() throws FileNotFoundException {

System.out.println("Please list how many students there are.");

numStudents = keyboard.nextInt();

nameOfStudent = new String[numStudents];
broncoID = new int[numStudents];
grade = new int[numStudents];

keyboard.nextLine();

for(int i = 0; i < numStudents; i++){
System.out.println("Please enter full name of Student.");
nameOfStudent[i] = keyboard.nextLine();
System.out.println("Now please enter the BroncoID of Student.");
broncoID[i] = keyboard.nextInt();
System.out.println("Now please enter grade of Student (0-100)");
grade[i] = keyboard.nextInt();
keyboard.nextLine();
}
System.out.println("Roster successfully created!");
for (int i = 0; i < numStudents ; i++){
System.out.printf("Name: %9s\t Bronco ID: %5d \t Grade: %2d \n", nameOfStudent[i], broncoID[i], grade[i]);
}
}

public static void displayRoster(){
System.out.printf("Name: %9s\t Bronco ID: %5d \t Grade: %2d \n", nameOfStudent[1], broncoID[1], grade[1]);

}

第一种情况下的 printf 可以工作,但在第二种情况下则不起作用。我得到的错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Roster.displayRoster(Roster.java:115)
at Roster.startMenus(Roster.java:36)
at Roster.main(Roster.java:16)

最佳答案

数组始终以索引 0 开头。您向数组中添加了一个“名册”。该名册将获得索引 0。在您的 displayRoster() 方法中,您想要显示索引 1,但您的数组只有索引 0。因此它将获得 ArrayIndexOutOfBoundsException。

而不是:

System.out.printf("Name: %9s\t Bronco ID: %5d \t Grade: %2d \n", nameOfStudent[1], broncoID[1], grade[1]);

尝试:

System.out.printf("Name: %9s\t Bronco ID: %5d \t Grade: %2d \n", nameOfStudent[0], broncoID[0], grade[0]);

关于java - 为什么数组值没有在 switch case 中保留?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33909529/

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