0

I am trying to fill up the array den and it is giving me java.lang.NullPointerException
Why is that
Thanks

public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        System.out.print("Enter an amount:");
        float amount= input.nextFloat();
        int denom, i=0;
        int  [] den=null;
        do{
        System.out.print("Enter denominations: ");
        denom=input.nextInt();
        den[i]=denom;
        i++;
        }
        while(denom!=0);

Edited by kukuruku: n/a

2
Contributors
1
Reply
2
Views
6 Years
Discussion Span
Last Post by stultuske
0
int  [] den=null;
[/Code=Java]

this is why ... before you want to set values like this:
[Code=Java]
den[i]=denom;

you have to set a length for the array, for instance:

int[] den = new int[5]; // creates an int - array with 5 elements

this 'll also tell you ... you can't use an array in the logic you're trying to implement. if you want to add elements until you enter '0', you need to use a List.

List numbers = new ArrayList();
int nr = readNumber(); // let's just assume this method exists
while ( nr != 0 ){
numbers.add(nr); // autowrapping takes care of the transfer to Integer
nr = readNumber();
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.