因此这段代码采用 n 的值并返回一个除数列表以及除数总数。如果我删除 Scanner
声明及其对 int n 的赋值并简单地为 int n 赋值,代码将完美运行。
然而,它返回的是:
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");
}
}
最佳答案
arr
的大小在n
仍然没有值时声明(在输入大小之前)。这样做:
import java.util.Scanner;
public class Program {
static int n;
static int x = 1;
static int [] arr; //no size set
//...
//Other variables
//...
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
arr = new int[n]; //Now the size is set to the inputted number.
while(x <= n) {
//...
//Other code to find divisors
//...
}
}
}
您需要在输入n
后命名arr
的大小,否则大小设置为0
,导致 ArrayIndexOutOfBoundsException
。
这一行:
arr[q] = p;
是真正导致错误的原因。 arr[q]
无法保存值,因为没有 arr[q]
。该数组没有大小,因此它不能容纳任何成员。
关于java - 为什么扫描仪功能不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45292185/