java - 为什么扫描仪功能不起作用?

标签 java arrays java.util.scanner

因此这段代码采用 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/

相关文章:

java - 是否可以通过路径访问 jar 内的资源?

java - 如何通过System.setProperty设置内存不受影响?

arrays - 在二维空间中找到一个圆内的所有点

javascript - 对象数组到数组数组作为字符串

java - 获取不同的文件

java - Google Drive SDK 中的文档查看器 - Java

java:如何在大文件中搜索字符串?

arrays - 为什么结构数组比较有不同的结果

java - 扫描仪在使用 next() 或 nextFoo() 后跳过 nextLine()?

java.util.Scanner 跳过输入请求