Exception in creating array of Objects [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am storing sum of all pairs of an array element to pairSum[] array.
For this I have created PairSum class which store two elements and their sum.
But I am getting null Pointer Exception on line pairSum[k].sum = v
I have created array as
PairSum[] pairSum = new PairSum[val];
What am I doing wrong?
public class test {
class PairSum{
int first;
int second;
int sum;
}
public static void findElements(int arr[], int n){
int val = (n*(n-1))/2;
PairSum[] pairSum = new PairSum[val];
int k=0;
for(int i=0;i<n-1;i++){
for (int j=i+1;j<n;j++){
int v = arr[i] + arr[j];
System.out.println("sum..." + v);
pairSum[k].sum = v;//NullPointerException here
System.out.println("valll.." + pairSum[k]);
pairSum[k].first = arr[i];
pairSum[k++].second = arr[j];
}
}
}
public static void main(String[] args) {
int arr[] = {10, 20, 30, 40, 1, 2};
int n = arr.length;
findElements (arr, n);
}
}

As of now, you have only created an array that can hold objects of type PairSum. You need to instantiate every PairSum object individually:
pairSum[k] = new PairSum();
Before accessing any PairSum in your pairSum array.

Related

NullPointerException when declaring method from another class [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I've been trying to work around this NullPointerException issue:
Exception in thread "main" java.lang.NullPointerException
at LinearSearcher.<init>(LinearSearcher.java:12)
at DemoSearches.main(DemoSearches.java:4)
through researching, I found that this exception occurs when you declare a reference type but don't create an object. In my case it is when I am trying to declare LinearSearcher
I've tried to understand this with my code but i'm having difficulties
Code for LinearSearcher:
public class LinearSearcher implements Searcher {
private int[] numbers;
public LinearSearcher() {
numbers[0] = 1; // Line 12 Here
numbers[1] = 10;
numbers[2] = 20;
numbers[3] = 30;
numbers[4] = 40;
numbers[5] = 50;
numbers[6] = 60;
numbers[7] = 70;
numbers[8] = 80;
numbers[9] = 90;
}
public int searchFor(int key) {
for (int i = 0; i < numbers.length; i++){
if (numbers[i] == key) {
return i;
}
}
return NOT_FOUND;
}
public void display() {
for (int i = 0; i < numbers.length; i++){
}
}
}
Class where LinearSearcher is declared:
public class DemoSearches {
public static void main(String args[]) {
LinearSearcher search = new LinearSearcher(); // Line 4 Here
search.display();
search.searchFor(50);
search.searchFor(100);
}
}
numbers is null because you haven't initialized it. You can change
private int[] numbers;
to
private int[] numbers = { 1, 10, 20, 30, 40, 50, 60, 70, 80, 90 };
and eliminate the problem. Other solution, add
numbers = new int[10];
Before your current assignments.
You never initialize the numbers array so when you try to access it in the LinearSearcher constructor you are trying to access a nonexistent array. So an exception is thrown.
You need to do numbers = new int[10]; before doing numbers[0] etc. This will create the object so it can be used.

Getting sub-array from a 2D double[][] array [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'm trying to get a sub-array from double[][] 3x3 matrices (to calculate a determinant). I keep getting the ArrayIndexOutOfBoundsException.
Any idea why ?
public double[][] get2DSubArray(double[][] largeArray, int rowStartIndex, int rowEndIndex, int columnStartIndex, int columnEndIndex) {
double[][] subArray = new double[rowEndIndex-rowStartIndex+1][columnEndIndex-columnStartIndex+1];
for (int row = rowStartIndex; row < rowEndIndex; row++) {
subArray[row] = Arrays.copyOfRange(largeArray[row], columnStartIndex, columnEndIndex);
}
return subArray;
}
Looks like it has something to do with array initialization, the array passed to the method does not seem to be 3x3. E.g, following does not produce an Exception:
public static void main(String[] args) throws IOException {
double[][] array = new double[][]{{1d,1d,1d},{2d,2d,2d},{3d,3d,3d}};
double[][] subArray = get2DSubArray(array, 1, 2, 1, 2);
for(double[] arrayElement : subArray){
for(double number : arrayElement){
System.out.println(number);
}
}
}
public static double[][] get2DSubArray(double[][] largeArray, int rowStartIndex, int rowEndIndex, int columnStartIndex,
int columnEndIndex) {
double[][] subArray = new double[rowEndIndex - rowStartIndex + 1][columnEndIndex - columnStartIndex + 1];
for (int row = rowStartIndex; row < rowEndIndex; row++) {
subArray[row] = Arrays.copyOfRange(largeArray[row], columnStartIndex, columnEndIndex);
}
return subArray;
}
Update
Although the above solution does not produce an Exception, it does not produce correct output as well. Mainly because of the following reasons:
Third argument for Arrays.copyOfRange method is exclusive, so we have to pass columnEndIndex+1 for it to work
for loop only executes once for provided set of arguments whereas it should execute at least twice
Instead of assigning Arrays.copyOfRange to subArray[row], we need to assign it to subArray[<zero based index>]
Below solution does work:
public double[][] get2DSubArray(double[][] largeArray, int rowStartIndex, int rowEndIndex, int columnStartIndex,
int columnEndIndex) {
double[][] subArray = new double[rowEndIndex - rowStartIndex + 1][columnEndIndex - columnStartIndex + 1];
int index = 0;
for (int row = rowStartIndex; row <= rowEndIndex; row++) {
subArray[index++] = Arrays.copyOfRange(largeArray[row], columnStartIndex, columnEndIndex+1);
}
return subArray;
}
If the row start was 500 and the end was 505, the variable in the for loop would start at 500 instead of 0. You want to replace "subArray[row] =" with "subArray[row-rowStartIndex] =". You are referencing where it would of been in the larger array compared to where the copy will be in the smaller array.
Edit:
//Fixed Version:
public static double[][] get2DSubArray(double[][] largeArray, int rowStartIndex, int rowEndIndex, int columnStartIndex,
int columnEndIndex) {
double[][] subArray = new double[rowEndIndex - rowStartIndex + 1][columnEndIndex - columnStartIndex + 1];
for (int row = rowStartIndex; row <= rowEndIndex; row++) {
subArray[row-rowStartIndex] = Arrays.copyOfRange(largeArray[row], columnStartIndex, columnEndIndex+1);
}
return subArray;
}

ArrayStoreException while assigning default value using Arrays.fill method in java [duplicate]

This question already has answers here:
Arrays.fill with multidimensional array in Java
(15 answers)
Closed 6 years ago.
trying to assign default value using Arrays.fill method, but I'm getting ArrayStoreException. Code is given Below "for finding all path from source to destination in 2d array with only k moves"
I went through few links(https://stackoverflow.com/questions/15120089/convert-arraylist-to-array-throws-java-lang-arraystoreexception,https://stackoverflow.com/questions/12369957/dealing-with-an-arraystoreexception), but not able to locate the problem
public class FindPathWithConstaint {
int[][][][] dp = new int[100][100][100][2];
public static void main(String arg[]) {
int m = 3, n = 3, k =2;
FindPathWithConstaint obj = new FindPathWithConstaint();
System.out.println(obj.findAllPath(m,n,k));
}
public int findAllPath(int m, int n, int k) {
if(m==0 && n==0)
return 1;
Arrays.fill(dp,-1);
return countAllPaths(m-1,n,k,1) + countAllPaths(m,n-1,k,0);
}
public int countAllPaths(int i, int j, int k, int d) {
if(i<0 || j<0)
return 0;
if(i==0 && j==0)
return 1;
if(k==0) {
if(d==0 && i==0)
return 1;
if(d==1 && j==0)
return 1;
}
if(dp[i][j][k][d]!=-1)
return dp[i][j][k][d];
if(d==0)
return countAllPaths(i,j-1,k,0) + countAllPaths(i-1,j,k-1,1);
else
return countAllPaths(i-1,j,k,1) + countAllPaths(i,j-1,k-1,0);
}
}
You are Having this error because you have declared dp as Multidimentional array in this line
int[][][][] dp = new int[100][100][100][2];
Which mean that you gonna have an array of arrays, then you have tried to assigne values to this array using Arrays.fill() which throws error in this line
Arrays.fill(dp,-1);
it throws an exception because the fill method try to affect an integer "-1" to each element of dp array, although dp is an array of arrays not an array of integers and that is exactly the cause of the exception,

Java: Insertion Sort Algorithm [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 7 years ago.
Hello fellow Stackoverflowers,
How do I print out the numbersArray so that I can see the numbers?
When I sysout the numbersArray, it shows me:
[I#677327b6
[I#677327b6
Thank you for your time and help!
package AlgoExercises;
public class InsertionSort {
static int[] numbersArray = { 5, 2, 4, 6, 1, 3 };
static void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
// a and b are copies of the original values.
// The changes we made here won't be visible to the caller.
}
static void insertionSort(int[] numbersArray) {
for (int i = 1; i < numbersArray.length; i++) {
int j = i;
while ((j > 0) && (numbersArray[j] < numbersArray[j - 1])) {
swap(numbersArray[j], numbersArray[j - 1]);
j = j - 1;
System.out.println(numbersArray);
}
}
}
public static void main(String args[]) {
insertionSort(numbersArray);
}
}
System.out.println(numbersArray); You are printing an array instead of values. you should print the value by numbersArray[i]
For printing out arrays use java.lang.Arrays.toString() method:
System.out.println(Arrays.toString(numbersArray));

Reverse order of single dimensional array in Java [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I reverse an int array in Java?
I need to reverse the order of the given numbers in the array without using a temp.
public class Reverse
{
public static void main (String[] args)
{
int[] num = { 12, 34, 50, 67, 88 }, cl, cl2;
for (i=0; i < a.length; i++)
{
cl = a[i];
cl2 = a[(a.length - 1 )-1];
System.out.println (cl1 + " " + cl2);
}
}
}
Since it only seems that you're printing the values out, you can iterate over your array backwards.
for(int i = a.length - 1; i >= 0; i--) {
// relevant code here
}
you can use Collections#reverse to inline a reverse sort of the integer array,
Collections.reverse(Arrays.asList(num));
The answers given are perfect. But i just added another answer in case if you want to store the reverse array into the original array without using any temp. use this.
public class Reverse
{
public static void main (String[] args)
{
int[] a = { 12, 34, 50, 67, 88 };
int i, j;
for (i = 0, j = a.length - 1; i < j; i++, j--)
{
a[i]=a[i]+a[j];
a[j]=a[i]-a[j];
a[i]=a[i]-a[j];
}
}
}

Categories