Java Integer class and compareTo() - java

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.

Related

Iterate over an array and get all multiples of 10 java

I am very new to Java and I am trying to iterate over an array of integers and get all multiples of 10. What I get with my code is the elements in the array printed 100 times since that is the length of the array. I know it is very basic but I just can't figure the problem out. This is what I have:
import java.util.Arrays;
public class ArrayThings {
public static void main(String[] args) {
int[] myFirstArray = new int[100];
for (int i = 0; i < myFirstArray.length; i++) {
myFirstArray[i] = i;
}
for (int i : myFirstArray) {
if (i % 10 == 0) {
myFirstArray[i] = i;
} else {
i++;
}
System.out.println(Arrays.toString(myFirstArray));
}
}
}
I think that is what you want to do :
public class ArrayThings {
public static void main(String[] args) {
int[] myFirstArray = new int[100];
// array generation
for (int i = 0; i < myFirstArray.length; i++) {
myFirstArray[i] = i;
}
// printing multiples of 10
for (int i = 0; i < myFirstArray.length; i++) {
if (i % 10 == 0 && i != 0) {
System.out.println(myFirstArray[i]);
}
}
}
}
In Java-8 you can do it like below:
int result[] = IntStream.range(1, 100).filter(e -> e%10==0).toArray();
System.out.println(Arrays.toString(result));
Why do you need an array for printing multiples of 10? You could simply do:
public class ArrayThings{
public static void main(String[]args){
for(int i=0; i<101; i++) {
if(i%10==0 && i != 0){
System.out.println(i);
}
}
}}
P.S. you are printing whole array and not that particular element, that's why you are getting a wrong output.
You should move your print statement outside of the for loop, that is what is causing it to print 100 times.
Also your current code seems to do absolutely nothing. You are checking the modulo of i, then setting the value of myFirstArray to that value of i. The current value of myFirstArray at i, is already equal to i, as initialized in the first loop.
This should work
import java.util.Arrays;
public class ArrayThings {
public static void main(String[] args) {
int[] myFirstArray = new int[100];
int[] myMultiplesArray = new int[9];
for (int i = 0; i < myFirstArray.length; i++) {
myFirstArray[i] = i;
}
int j = 0;
for (int i : myFirstArray) {
if (i % 10 == 0) {
myMultiplesArray[j] = i;
j++;
}
}
System.out.println(Arrays.toString(myMultiplesArray));
}
}

Given an array of integers, find out the third largest value in the array

public int thirdLargest(int[] arr){
int f_l = arr[0];
int s_l = arr[0];
int t_l = arr[0];
for(int i=1;i<arr.length;i++)
{
if (f_l < arr[i]){
t_l = s_l;
s_l = f_l;
f_l = arr[i];
}
else if (s_l < arr[i]){
t_l = s_l;
s_l = arr[i];
}
else if (t_l < arr[i]){
t_l = arr[i];
}
}
return t_l;
}
my code didn't passes some cases,any suggestion?
parameter {24,27,30,31,34,37,40,42}' , passes
parameter {2,-1,-2,-3,-4,-5}' , fails
This is simply cause by the fact that you initialize all values to arr[0]. If all elements are smaller than arr[0] this code won't update the values, even though the second-largest element for example wouldn't be arr[0]. Instead initialize the variables for the third/second/largest value with Integer.MIN_VALUE and start the search with the first element (index = 0) instead of the second.
There is actually a well-known algorithm for this, which is more generic than yours. It is called quick-select and looks like a quick sort with an optimization making it faster (linear time in average) : since we don't need to sort the array, we just recurse on the part of the array containing the index we are looking for (in your case, third item so index 2).
Here is an implementation in Java :
private static final Random rd = new Random();
public static int kthElement(int[] arr, int k) {
return kthElement(arr,k,0,arr.length);
}
private static T kthElement(int[] arr, int k, int min, int max) {
if (min < max - 1) {
int p = pivot(arr,min,max);
return p == k - 1 ? arr[p] :
p < k - 1 ? kthElement(arr,k,p + 1,max) : kthElement(arr,k,min,p);
}
return arr[min];
}
private static int pivot(int[] arr, int min, int max) {
int pivot = min + rd.nextInt(max - min);
swap(arr,pivot,max - 1);
pivot = min;
for (int i=min ; i<max ; i++)
if (arr[i] < arr[max - 1]) swap(arr,i,pivot++);
swap(arr,max - 1,pivot);
return pivot;
}
private static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
Well, as an alternative to your working code, here is a solution that will allow you to find the Nth largest integer in your array using Collections to do the heavy lifting:
import java.util.Arrays;
import java.util.Collections;
public class ArrayNthLargest {
public static int getNthLargest(int[] arrayInput, int n) {
Integer[] sortedArray = new Integer[arrayInput.length];
for (int i = 0; i < arrayInput.length; i++) {
sortedArray[i] = new Integer(arrayInput[i]);
}
Arrays.sort(sortedArray, Collections.reverseOrder());
return (sortedArray[n - 1]);
}
public static void main(String[] args){
int nth = new Integer(0);
int n = new Integer(3);
int[] testArray = {1,2,3,4,5,6,23,44,55,8,1};
nth = getNthLargest(testArray, n);
System.out.printf("The %d sorted array value is %d", n, nth);
}
}
This was actually an interesting question to me to do in O(n) complexity. I hope this solution is order n. I used an ArrayList as a stack (since Stack object won't allow addition of items in specific incidences (I've generalized it).
public int thirdLargest(int[] arr){
public int N_TH = 3; // Assuming this is nth largest you want
public ArrayList<Integer> largest = new ArrayList<Integer>(N_TH);
for(int i = 0;i<N_TH;i++)
largest.add(0); // initialize the ArrayList
for(int i = 0;i<arr.length;i++) {
for(int j=0;j<largest.size();j++){
if(arr[i] >= largest.get(j)) {
// Add the item at the correct index
// Pop the last element
largest.remove(largest.size()-1);
largest.add(j,arr[i]);
break;
}
}
}
return largest.get(N_TH);
}
Let me know if you find any problems with it, I might have mistyped part of trying to put it in OP's method.
EDIT won't work with negative numbers at the moment. You can find the smallest value in arr and initialize largest with that value. Then it'll also with negative numbers

Why does my bubble sort method not work?

Sorry I am still learning programming. Java just stops and seems to be processing something. It says "Building java application Javaapplication2" then just sits there doing nothing. What have a I done to cause this ?
package javaapplication2;
public class JavaApplication2 {
public static void main(String[] args) {
int a [] = {1,2,3};
int c [] = Sortarray.sortlowhigh(a);
int i = 0;
while (i<c.length){
System.out.println("array is" + c[i]);
i++;
}
}
}
package javaapplication2;
public class Sortarray {
public static int[] sortlowhigh(int a[])
{
int i = 0;
int j = 0;
while(j<a.length){
while(i<a.length){
if (a[i]>a[i+1]){
/* store low value in temp*/
int temp = a[i+1];
/* assign low value to be the higher value*/
a[i+1] = a[i];
/* assign the old higher value to be the lower value stored in temp*/
a[i]=temp;
}
j++;
}
}
return a;
}
}
My code is above. A while ago I wrote a sort and remove duplicates method now I want to put them into a class but I am doing something wrong. Please help. Thanks.
I try your code and I can see that you have a infinite loop in the class Sortarray. The variable i is never increased.
Try this code:
public static int[] sortlowhigh(int a[])
{
int i = 0;
int j = 0;
int temp;
while(j< (a.length -1) ){
i = 0;
while(i< (a.length - j - 1)){
if (a[i] > a[i+1]){
/* store low value in temp*/
temp = a[i];
/* assign low value to be the higher value*/
a[i] = a[i+1];
/* assign the old higher value to be the lower value stored in temp*/
a[i+1]=temp;
}
i++;
}
j++;
}
return a;
}
In the sortlowhigh while loop you have i, i < a.lenght is the condition of the second loop and it will continue until i is >= a.length but i never changes it always stay 0.
/*change your code as given*/
public static int[] sortlowhigh(int a[]){
int i = 0;
int j = 0; int temp=0;
while(j<(a.length-1))
{
i=0;
while(i<a.length-j-1)
{
if(a[i]>a[i+1])/* For descending order use < */
{
temp = a[i];
a[i]=a[i+1];
a[i+1] = temp;
}
i++;
}
j++;
}
return a;
}
you should reset the value of i, when the value of j is incremented.
The array is of size 3. but the value of i is already 3. so it gets garbage value in a[i+1].
Hope this helps. I haven't tried the code.

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];.

Null Pointer Exception for arrays

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.

Categories

Resources