我在我的数组中得到一个空指针异常

时间:2013-02-06 04:36:06

标签: java arrays

每当我在int []数组中输入要添加的值时,我就会得到一个空指针异常,而且我不确定应该从哪里开始,或者是否需要另一个数组。任何帮助将不胜感激。

import java.util.Scanner;

public class Range
{
private int[] range;
private int begin,end,falseLoop,numInts,count;
Scanner scan = new Scanner(System.in);

public static void main(String[] args)
{
    Range r = new Range();
    r.getRange();
    r.getAmount();
    r.getInts();
    //r.printAll();
}

private void getRange()
{
    System.out.println("Please enter the first number in the range you would like to use: ");
    begin = scan.nextInt();
    System.out.println("Please enter the second number in the range you would like to use: ");
    end = scan.nextInt();
    falseLoop = end;
    int[] range = new int[(Math.abs(begin) + Math.abs(end))];  
    for(int x = 0; x < range.length; x++)
    {
        range[x] = 0;
    }
}

private void getAmount()
{
    System.out.println("Please enter the amount of integers you would like to enter " 
        + "in the range of " + begin + " to " + end);
    numInts = scan.nextInt();
}

private void getInts()
{
    for(int y = 0; y < numInts; y++)
    {
        System.out.println("Please enter an integer: ");
        range[scan.nextInt()]++;
    }
}
private void printAll()
{
    for(int i = 0; i < range.length; i++)
    {
        System.out.println("Value: " + falseLoop + "equals: " + range[i]);
        falseLoop++;
    }
}
}

2 个答案:

答案 0 :(得分:4)

getRange内的shadowing类变量。

int[] range = new int[(Math.abs(begin) + Math.abs(end))];

实际应该是:

range = new int[(Math.abs(begin) + Math.abs(end))];

你得到空指针,因为你已经声明了一个数组,但没有为它分配任何内容。

答案 1 :(得分:0)

不理解您的代码声明

ragne[x] = new int[0];

您在这里尝试将整数数组分配给整数变量。像

integer = integerArray;