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/

相关文章:

python - 全部与全部点积

Java 线程与 Scanner 第一次工作但第二次就不行了?

java - 在 HashMap 中搜索

java - 我该如何用扫描仪(java)处理它?

java - 将 sse 广播与 Jersey 一起使用,无论如何将事件发送到特定的 EventOutput?

java - 无法追踪错误 java.lang.NullPointerException 的原因

arrays - 修改 MongoDB 中数组的最后一个元素

javascript - Angular js - 具有简单条件的 ng-class =""将不起作用

java - 将 XML 编译成 Java

java - 安装带有依赖的jar到maven仓库(Android gcm-server push library)