我如何重新运行使用数组的部分代码?

How do i rerun part of a code that uses an array?

我正在尝试编写一个代码来接收用户输入并打印他们的日程安排,但我 运行 遇到了我的 do-while 循环的问题。

我的程序不会重新运行。我收到一条错误消息:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2 at com.company.Main.main(Main.java:25)

这是我的代码:

import java.util.*;

public class Main {

    public static void main(String[] args)  {
        Scanner input = new Scanner(System.in);
        String rerun;
        do {
            System.out.println("What is your name?");
            String name = input.nextLine();
            System.out.println("How many courses do you have?");
            int numCourse = input.nextInt();
            input.nextLine();
            String[][] timetable = new String[numCourse][2];
            for (int j = 0; j < numCourse; j++) {
                System.out.println("What is the name of your course #" + (j + 1) + "?");
                String course = input.nextLine();
                timetable[j][0] = course;
                System.out.println("What is your teachers name for " + course + "?");
                String teacher = input.nextLine();
                timetable[j][1] = teacher;
            }
            System.out.println("Hello " + name + ", here is your timetable:");
            for (int i = 0; i <= numCourse; i++) {
                System.out.format("\n%-30s%-30s", "Course #" + (i+1) + ": " + timetable[i][0],"Teacher: " + timetable[i][1]);
            }
            System.out.println("Would anyone else like to print their schedule? (yes/no)");
            rerun = input.next();
        }while(rerun.equalsIgnoreCase("yes"));
        System.out.println("Goodbye!");
    }
}

问题出在您显示 from 数组的第二个 for 循环中。将 next() 替换为 nextLine() 因为有时它会跳过该位置。

改变

for (int i = 0; i <= numCourse; i++) {
      System.out.format("\n%-30s%-30s", "Course #" + (i+1) + ": " + timetable[i][0],"Teacher: " + timetable[i][1]);
}

for (int i = 0; i < numCourse; i++) {
      System.out.format("\n%-30s%-30s", "Course #" + (i+1) + ": " + timetable[i][0],"Teacher: " + timetable[i][1]);
}

假设您的 numCorse2。在您的代码中,循环从 0 开始并在 2 之后终止,因此,您的循环在 i01 时正常工作,但是如果 i3 你得到异常 ArrayIndexOutOfBound.