所以这段代码取n的值并返回一个除数列表以及除数的总数。如果我删除了Scanner
声明并将其赋值给int n并只给出一个int值,则代码将完美运行。为什么扫描仪功能无法正常工作?
然而,因为它是,它返回:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Program.main(Program.java:25)
我不知道是什么问题。
import java.util.Scanner;
public class Program{
static int n;
static int x = 1;
static int [] arr = new int[n];
static int q = 0;
static int g = 0;
static int p = 1;
static int count;
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
while(x <= n){
arr [q] = p; //assigns value to each array index
g = n%arr[q]; // stores value of remainder
q++;
p++;
x++;
if (g == 0){ //counts and displays each time remainder = 0
count++;
System.out.println(q);
}
}
System.out.println(count + " Divisors");
}
}
观察你的病情的同时,'X <= N'。记住数组索引从0开始不是1. –
你声明你的int []'arr'长度为'n'。但是,您不会给'n'一个值,所以默认情况下它是0.因此,'arr'的长度为0,所以您无法得到ArrayIndexOutOfBounds异常。 – geokavel
假设您没有为'static int n'分配一个值,因此如果默认情况下为0,那么'arr'的大小。还有一个局部变量'int n',而不是'static' –