Null Pointer Exception for arrays - java

I'm getting a NullPointerException, it seems the program can't find nums (the array)
The Class:
/**
*Author: Chris Cherian
*Date: 4/30/14
*Desc: This program organizes numbers into 3 arrays - Even, Odd, and Negative.
*/
public class IntegerArray
{
/**
*The array that holds all the numbers.
*/
int nums [];
/**
*Holds count of the odds.
*/
private int oddCount = 0;
/**
*The numbers in the array.
*/
private int length;
/**
*Holds count of the positives.
*/
private int posCount;
public IntegerArray(int[] array)
{
nums = array;
}
/**
*The nuber of elements in the array.
*/
private final int TOTALNUMS = nums.length;
/**
*The array that holds all the even numbers.
*/
private int[] evens = new int[TOTALNUMS - this.getOddCount()];
/**
*The array that holds all the odd numbers.
*/
private int[] odds = new int[this.getOddCount()];
/**
*The array that holds all the negative numbers.
*/
private int[] negs = new int[TOTALNUMS - this.getPosCount()];
int evenCounter = 0;
/**
*Gathers the total number of odds
*#return The number of odd numbers
*/
public int getOddCount()
{
for(int i = 0; i <= TOTALNUMS; i++)
{
if(nums[i]%2 != 0)
{
oddCount++;
}
}
return oddCount;
}
/**
*Gathers number of positives
*#return posCount The number of positive numbers
*/
public int getPosCount()
{
for(int i = 0; i <= TOTALNUMS; i++)
{
if(nums[i] > 0)
{
posCount++;
}
}
return posCount;
}
public int[] organizeEvens()
{
for(int i = 0; i < nums.length; i++)
{
if(nums[i]%2 == 0)
{
evens[evenCounter] = nums[i];
evenCounter++;
}
}
return evens;
}
int oddCounter = 0;
public int[] organizeOdds()
{
for(int i = 0; i < nums.length; i++)
{
if(nums[i]%2 != 0)
{
odds[evenCounter] = nums[i];
oddCounter++;
}
}
return odds;
}
int negCounter = 0;
public int[] organizeNegs()
{
for(int i = 0; i < nums.length; i++)
{
if(nums[i]%2 == 0)
{
negs[negCounter] = nums[i];
negCounter++;
}
}
return negs;
}
}
The Client:
import java.util.Scanner;
public class IntegerArrayClient
{
public static void main(String[] jackofspades)
{
Die die1 = new Die(200);
Scanner keyboard = new Scanner(System.in);
System.out.println("How many numbers would you like to organize?");
int numbers = keyboard.nextInt();
int[] numbersarray = new int[numbers];
for(int i = 0; i < numbers; i++)
{
numbersarray[i] = (die1.Roll() - 200);
}
IntegerArray numholder = new IntegerArray(numbersarray);
int evenCount = (numbersarray.length - numholder.getOddCount());
for(int i = 0; i < evenCount; i++)
{
System.out.println(numholder.organizeEvens() + "\t");
}
}
}
The error message I get:
Exception in thread "main" java.lang.NullPointerException
at IntegerArray.<init>(IntegerArray.java:37)
at IntegerArrayClient.main(IntegerArrayClient.java:20)

The problem is that your code has an assumption that
private final int TOTALNUMS = nums.length;
would execute after the constructor, because textually it follows it. That is an incorrect assumption - this line executes before the constructor, at the time nums is still null. This is what is causing the exception.
To fix this problem, move the initialization of TOTALNUMS into the constructor:
private final int TOTALNUMS; // It's OK to leave it final - you are allowed to set it in the constructor
...
public IntegerArray(int[] array) {
nums = array;
TOTALNUMS = nums.length; // If nums is set to a non-null array, this would not cause an exception
}
Finally, note that there is little point in keeping a separate final variable for the length of nums, because its length is always available to you, and you do not need to "synchronize" the two if you decide to set nums to a different array later on.

This peice of code
private final int TOTALNUMS = nums.length;
is happening before nums has been initialized, it is still int nums []; - it has no size.

I assume that line 37 is this one:
private final int TOTALNUMS = nums.length;
The problem is that nums has not been initialized at that point, and it therefore still has its default initial value. Therefore, executing num.length throws an NPE.
How so?
Well you are initializing nums in the constructor. Bur the code in the constructor body is only executed AFTER the initializers for the instance variables have all been executed.
You need to initialize TOTALNUMS, evens, odds and so on in the constructor, since they all depend on the value passed in the constructor's array parameter.

You need to lookup up member initializers and when they run in relation to the constructor. They run before the constructor. Only after that (during the constructor) are you initializing num, and that is after you've tried to use num.Length.
Move the code that depends on nums.length to the constructor, after you've assigned nums, or in a method that is called after the object is fully created (ie. don't to it in the constructor at all, add another method on the class that returns the length).
Trying to do too much in the initializers is causing trouble.
See the first answer in this question:
Java Static Initialization Order
Or the Java rules on initialization order:
http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.4.2
All these lines of code are wrong because these lines are executed as the object is created, prior to the constructor that initializes nums.
private final int TOTALNUMS = nums.length;
private int[] evens = new int[TOTALNUMS - this.getOddCount()];
private int[] odds = new int[this.getOddCount()];
private int[] negs = new int[TOTALNUMS - this.getPosCount()];
I suggest converting "evens" to "getEvens()" and calling getEvens() from main, not from the initializer.
Same for each of the other fields, convert to methods that are called later.

Related

Print array in a loop with dynamic variable Java

I am trying to define an array that increased by one each time then print the result of an equation that the array is assigned to;
my code so far is
public class PrimeNumberCounter {
public static void main(String[] args) {
// Define integers
int a = 1;
final int b = 2;
final int c = 3;
// Define Array
int[] nth;
nth = new int[100];
//Set loop
for (a = 1; a < 100; a = a + 1) {
int d = a * b + c;
System.out.println(d);
}
}
}
The math function and loop work but I can't figure out how to publish the nth term.
So far I have read array's are the most suitable solution but after much messing around removed the print array part, and decided to ask for help.
Thanks All
EDIT: addition of original code (it's kinda silly hence why I didn't publish it 1st time
public class PrimeNumberCounter {
public static void main(String[] args) {
// Define integers
int a = 1;
final int b = 2;
final int c = 3;
// Define Array.
int[] nth;
nth = new int[100];
//Set loop
for (a = 1; a < 100; a = a + 1) {
nth[] = a * b + c;
System.out.println(nth);
}
}
}
Use some collection like a list instead of using array.
You can use an iterator to iterate over that list and update the iterator.
If I understood you correctly, you are not trying to increase the size of the array, what you are trying to do is increase a counter that iterates through the array and assigns the result of the d = a * b + c; equation to the ith element of the array. Then after all the elements in the array have been populated, you want to iterate through the array an print all the values. If that is the case you can modify your code as follows:
public class PrimeNumberCounter {
public static void main(String[] args) {
// Define integers
int a = 1;
final int b = 2;
final int c = 3;
//int d = 0; // not used
// Define Array assuming that its size is fixed to 100
int[] nth = new int[100];
// Set the assignment loop
for (a = 1; a <= nth.length; ++a) {
// array indexing starts at 0
nth[a - 1] = a * b + c;
}
// print loop
for (int i = 0; i < nth.length; ++i) {
System.out.printf("%d: %d\n", i + 1, nth[i]);
}
}
}
If you don't know the size of the array a priori you can use an ArrayList instead which can grow dynamically as mentioned in the comments and previous answer.
import java.util.List;
import java.util.ArrayList;
public class PrimeNumberCounter {
public static void main(String[] args) {
// Define integers
int a = 1;
final int b = 2;
final int c = 3;
// Some size N let's assume it's a 100 again
List<Integer> nth = new ArrayList<Integer>();
// Set the assignment loop
for (a = 1; a <= 100; ++a) {
// array indexing starts at 0
nth.add(a - 1, a * b + c);
}
// print loop
for (int i = 0; i < nth.size(); ++i) {
System.out.printf("%d: %d\n", i + 1, nth.get[i]);
}
}
}

integer array won't print [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
I created this method randomInt, that gives a random number, between -5, and 15. I created another method randomIntArray that calls randomInt, in a loop, and stores the random integers into an array. However, when I try to print it, it just returns an ArrayIndexOutOfBoundsException.
public static int randomInt(int low, int high) {
double e;
double x = Math.random();
e = low + x * (high - low);
return (int) e;
}
public static int[] randomIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < a.length; i++) {
a[i] = randomInt(-5, 15); //"-5&15 are the lower and upper bounds of the random number array
}
return a;
}
In randomInt, When I didn't cast the return value into an int, it worked, however I need it to return an int for the array to work.
Check your printing code after calling randomIntArray(number);
/**
* #param args the command line arguments
*/
public static void main(String[]args) {
int[] myArray = randomIntArray(10);
// Manual iteration through your array
for (int i = 0; i < myArray.length; i++) {
System.out.print(myArray[i] + " ");
}
System.out.println("");
// Use of Arrays class to print your array
System.out.println(Arrays.toString(myArray));
}
public static int randomInt(int low, int high) {
double e;
double x = Math.random();
e = low + x * (high - low);
return (int) e;
}
public static int[] randomIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < a.length; i++) {
a[i] = randomInt(-5, 15);
}//"-5&15 are the lower and upper bounds of the random number array
return a;
}
Results:
http://ideone.com/3OrTei
In the function calling randomIntArray(int n):
int[] array = randomIntArray(5);
for(int i = 0; i < array.length; i++)
{
System.out.println(array[i]);
}
The code works, just make sure you're printing the results properly

Getting the size on an array from one method into another method where I will be filling the array with numbers

I must ask to the user for the size of the array. This method must be an integer. Then I must pass that value into another method where the user will fill the array, this method must be float.
It's throwing an error in this line float[] arraySize = new float [getLengthOfArray()]; In the second method.
The error says "Int[] cannot be converted to int".
I don't know what to do.
Here's the entire code
package Exercise;
import javax.swing.JOptionPane;
public class Exercise3 {
public static int[] arrayLenght(){
int arraySize = Integer.parseInt(JOptionPane.showInputDialog("Enter the array size"));
int[] totalArraySize = new int[arraySize];
return totalArraySize;
}
public static float[] fillArray(){
float[] arraySize = new float [arrayLenght()];
for (int i = 0; i < arraySize.length; i++) {
arraySize[i] = Float.parseFloat(JOptionPane.showInputDialog("Enter a number"));
}
return arraySize;
}
public static void calculateArithmeticAverage(float[] numbers){
int total = 0;
int average = 0;
for (int i = 0; i < numbers.length; i++) {
total += numbers[i];
}
average = total / numbers.length;
}
public static void main(String[] args) {
calculateArithmeticAverage(fillArray());
}
Your arrayLength method should return an int, not an array.
public static int arrayLength()
{
int arraySize = Integer.parseInt(JOptionPane.showInputDialog("Enter the array size"));
return arraySize ;
}

Counting number of data swaps in Java bubble sort

I'm trying to count and output the number of swaps of data elements in a bubble sort method using Java. I'm a beginner, so am unsure how to overcome my issue: method is void and can't return anything, so what can I do to output the swaps?
in one doc, the sort method:
public class SearchSortAlgorithms<T> implements SearchSortADT<T>
{
//Bubble sort algorithm.
//Postcondition: list objects are in ascending order.
public void bubbleSort(T list[], int length)
{
//Initialize swap counter
int bubbleSwaps = 0;
for (int iteration = 1; iteration < length; iteration++)
{
for (int index = 0; index < length - iteration;
index++)
{
Comparable<T> compElem =
(Comparable<T>) list[index];
if (compElem.compareTo(list[index + 1]) > 0)
{
T temp = list[index];
list[index] = list[index + 1];
list[index + 1] = temp;
bubbleSwaps++;
}
}
}
}
}
In another, I use the method, and am looking to find a way to output bubbleSwaps:
public class numberSwapsReview{
public static void main(String [] args)
{
// define an Integer array of 1000 elements
Integer[] bubbleArray = new Integer[1000];
// load the array with random numbers using
// a for loop and Math.random() method - (int)(Math.random()*1000)
for (int i = 0; i < bubbleArray.length; i++) {
bubbleArray[i] = (int)(Math.random() * 1000);
}
SearchSortAlgorithms<Integer> sortObject = new SearchSortAlgorithms<Integer>();
sortObject.bubbleSort(bubbleArray, 1000);
}
}
Since you are making an instance of the class, you could make bubbleSwaps class level then get the value after the sort
public class SearchSortAlgorithms<T> implements SearchSortADT<T>
{
//Initialize swap counter
int bubbleSwaps = 0;
//Bubble sort algorithm.
//Postcondition: list objects are in ascending order.
public void bubbleSort(T list[], int length)
{
for (int iteration = 1; iteration < length; iteration++)
{
for (int index = 0; index < length - iteration;
index++)
{
Comparable<T> compElem =
(Comparable<T>) list[index];
if (compElem.compareTo(list[index + 1]) > 0)
{
T temp = list[index];
list[index] = list[index + 1];
list[index + 1] = temp;
this.bubbleSwaps++;
}
}
}
}
public int getBubbleSwaps(){
return this.bubbleSwaps;
}
}
Here is the other class:
public class numberSwapsReview{
public static void main(String [] args)
{
// define an Integer array of 1000 elements
Integer[] bubbleArray = new Integer[1000];
// load the array with random numbers using
// a for loop and Math.random() method - (int)(Math.random()*1000)
for (int i = 0; i < bubbleArray.length; i++) {
bubbleArray[i] = (int)(Math.random() * 1000);
}
SearchSortAlgorithms<Integer> sortObject = new SearchSortAlgorithms<Integer>();
sortObject.bubbleSort(bubbleArray, 1000);
sortObject.getBubbleSwaps();
}
}
You might use a Comparator instead of Comparable elements. With that (preferable as a wrapper around the normal comparator), you can compute in a field variable how many time was the result >0
One way would be to change the return type of your method as int and return the number of swaps you did. Then just call:
int nbswaps = sortObject.bubbleSort(bubbleArray, 1000);
If you can't modify the return type, you can
print the number of swaps in the method at the end
create an attribute named nbSwaps in your class (don't forget to reset it at each call of bubbleSort method) and then implement a getter to be able to get the value from your main
Also you may change the declaration of your class as class SearchSortAlgorithms<T extends Comparable<T>>.
Now you will be sure that the elements have to be comparable and you could get rid of Comparable<T> compElem = (Comparable<T>) list[index];.

Java Integer class and compareTo()

This code throws a null pointer exception at line 20, where the compareTo() is called. Any advice on how to get it to work?
package exam1review;
import java.util.Random;
public class ArrayTester {
/**
* #param args
*/
public static void main(String[] args) {
int result, max=0;
Integer[] myArray = new Integer[10];
Random rand = new Random();
for (int i = 0; i < 10; i++) {
myArray[i] = rand.nextInt();
System.out.println(myArray[i]);
while (i != myArray.length - 1) {
result = myArray[i].compareTo(myArray[i+1]);
if (result > 0)
max = myArray[i];
else
max = myArray[i+1];
}
}
System.out.println(max);
}
}
Three issues:
You are trying to access myArray[i+1] while you only initialize it
on next iteration of your for loop, this is causeing you the NPE.
Your condition is (i != myArray.length - 1) and later you access
myArray[i+1], which is out of bound for i == myArray.length -
1.
The while loop: while (i != myArray.length - 1) from first galnce, it seems it will never be terminated, since you do not increase i in it.
At the point where you execute
result = myArray[i].compareTo(myArray[i+1]);
the array element myArray[i+1] has not yet been set to anything. Its value is null.
the problem is that you're looping over i, but your comparison tries to compare to myArray[i+1] before it's set.
Populate the array first, then look for the max value.
Like this:
package cruft;
import java.util.Random;
public class ArrayTester {
/**
* #param args
*/
public static void main(String[] args) {
Integer[] myArray = new Integer[10];
Random rand = new Random();
for (int i = 0; i < myArray.length; i++) {
myArray[i] = rand.nextInt();
}
for (Integer value : myArray) {
System.out.println(value);
}
System.out.println(String.format("max value: %d", findMax(myArray)));
}
public static int findMax(Integer [] values) {
int max = Integer.MIN_VALUE;
if (values != null) {
for (Integer value : values) {
if (value.compareTo(max) >= 1) {
max = value;
}
}
}
return max;
}
}
You need to initialize myArray with non null values.
The Integer[] array is initialized with 10 null values. You need to set them to actual numbers, or better - use int[] instead.
If you want to keep your logic, you'd need two loops - one to fill the array, and another to look for the maximum value.

Categories

Resources