所以這段代碼取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' –