我正在尝试将numStudents int复制到i Integer,但它们始终保持不变。
整数不是一个对象,所以我试图使我成为整数无济于事。
如何避免使用此参考副本?

import java.util.Scanner;
public class passionProject2 {
    public static void main(String[] args) {

        Scanner scnr = new Scanner(System.in);
        Integer numStudents;


        System.out.println("Enter the amount of students in your class.");

        numStudents = scnr.nextBigInteger();
        String[] studentNames = new String[numStudents];

        System.out.println("Enter your students' full names.");

        Integer i = numStudents;
        while (i >=0) {
            i--;
                studentNames[i] = scnr.nextLine();
                System.out.println(i);
            }


        while (numStudents >=0)
        {
            numStudents--;
            System.out.println(numStudents);
            System.out.println(studentNames[numStudents]);
        }

        }

    }


numStudents太小,无法工作,它会显示一条错误消息,内容为
线程“主”中的异常java.lang.ArrayIndexOutOfBoundsException:长度为3的索引-1超出范围
    在passionProject2.main(passionProject2.java:19)

因为numStudents是-1

最佳答案

在第16行,整数i = numStudents; numStudents的值将复制到变量i。
之所以发生java.lang.ArrayIndexOutOfBoundsException,是因为您需要在while指令条件中使用“>”而不是“> =”。在每个while循环的最后一次迭代中,您输入-1。

import java.util.Scanner;
public class passionProject2 {
public static void main(String[] args) {

    Scanner scnr = new Scanner(System.in);
    Integer numStudents;


    System.out.println("Enter the amount of students in your class.");

    numStudents = scnr.nextBigInteger();
    String[] studentNames = new String[numStudents];

    System.out.println("Enter your students' full names.");

    Integer i = numStudents;
    while (i >0) {
        i--;
            studentNames[i] = scnr.nextLine();
            System.out.println(i);
        }


    while (numStudents >0)
    {
        numStudents--;
        System.out.println(numStudents);
        System.out.println(studentNames[numStudents]);
    }

    }

}

10-08 14:39