NullPointerException in 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.
import java.util.Scanner;
class TestMatrix
{
public static void main(String args[]){
Scanner in=new Scanner(System.in);
System.out.println("Enter the number of matrices: ");
int num=in.nextInt();
int[][] temp=new int[10][10];
Matrix[] matrixarray=new Matrix[num];
Matrix.numberOfMatrices(num);
for(int i=0;i<num;i++)
{
System.out.println("Enter the rows and columns of M["+(i+1)+"]: ");
int r=in.nextInt();
int c=in.nextInt();
System.out.println("Enter the values: ");
for(int x=0;x<r;x++)
for(int y=0;y<c;y++)
{
temp[x][y]=in.nextInt();
}
matrixarray[i].inputMatrixValues(temp);
}
}
}
public class Matrix
{
static int number;
int[][] matrix=new int[10][10];
int row,col;
public static void numberOfMatrices(int n)
{number=n;}
public void inputMatrixValues(int[][] matrix)
{
for(int i=0;i<row;i++)
for(int j=0;j<col;j++)
{
this.matrix[i][j]=matrix[i][j];
}
}
}
the above code returns null pointer exception while calling the method inputMatrixValues() at line 22. matrixarray[i].inputMatrixValues(temp);
matrixarray is an object array of class Matrix. The exception occurs while accessing the ith element of object array. Matrix object array is created in line 9. Pls check what part of the code causes error.

NullPointerException is raised because you have not initialized your Matrix[] matrixarray=new Matrix[num];. The matrixarray[0]{for example} is null and when you invoke matrixarray[i].inputMatrixValues(temp); this caused a NullPointerException

Related

Why is array printed differently when it goes through other method that changes the array? [duplicate]

This question already has answers here:
Are arrays passed by value or passed by reference in Java? [duplicate]
(7 answers)
Closed 3 years ago.
The result you are suppose to get is 0, but I don't understand why? The array is changed when its passed through other method.
public class Tester {
public static int function1 (int [] arr) {
arr= function2(arr);
return arr[0];
}
public static int[] function2 (int [] arr) {
arr = new int[4];
return arr;
}
public static void main(String[] args) {
int arr[] = {1,2,3,4};
System.out.print(Tester.function1(arr));
}
}
I expected 4 from the printed answer.
You are creating a completely new array in function2. That's why by default it is storing 0 at every index. When you are returning, the new array is returning only. For every index it will print 0 only.
Why are you creating new array in function 2? If you have to print 4 then simply pass the existing array only and print the arr[3].
Here is the code :-
public class Tester {
public static int function1 (int [] arr) {
arr= function2(arr);
//return arr[0];
return arr[3];
}
public static int[] function2 (int [] arr) {
//arr = new int[4];
return arr;
}
public static void main(String[] args) {
int arr[] = {1,2,3,4};
System.out.print(Tester.function1(arr));
}
}

Initialization of 2-D Arrays using Constructors in Java [duplicate]

This question already has answers here:
Syntax for creating a two-dimensional array in Java
(13 answers)
2D array Null Pointer Exception error
(2 answers)
Closed 4 years ago.
Matrix.java
import java.io.*;
class Matrix {
private int q[][];
public Matrix() {
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
q[i][j] = Integer.parseInt(System.console().readLine());
}
public Matrix( int a , int b ) {
int mat[][] = new int [a][b];
for(int i=0; i<mat.length; i++) {
for(int j=0;j<mat[i].length;j++)
q[i][j] = Integer.parseInt(System.console().readLine());
}
}
public void show() {
for(int i=0; i<q.length; i++) {
for(int j=0;j<q[i].length;j++)
System.out.println(q[i][j]+" ");
}
}
}
UseMatrix.java
class UseMatrix {
public static void main(String args[]) {
Matrix m1 = new Matrix();
System.out.println("First Matrtix ");
m1.show();
Matrix m2 = new Matrix(5,4);
System.out.println("Second Matrtix ");
m2.show();
}
}
This programs shows NullPointerException error at runtime
Confused why this isn't working could use a little help, I want to the create a 2D Array of Size 3*3 through Default Constructors.
Then I want to create a Array of size 5*4 using parameterized constructors.
There are a number of problems:
First: private int q[][]; // this holds a null value, never assigned on the parameterless constructor. A possible solution to this would be to add in your constructor: q[][] = new int[a][b]; and q[i] = new int[b];// each time you enter the loop. See the code below for clarity.
Second in public Matrix() { you try to access the array contents without checking its length (for(int i=0;i<3;i++) goes from 0 to 3, regarles of the actual array size). The array is empty at the beggining so this causes another NullPointerException here q[i][j] = Integer.parseInt... (I will solve this reusing the other constructor because they want to achieve the same result)
Third there is problems reading from console(), so I changed that too. (And added a line where you ask the user for a number)
And the last change I made was a small tweak to the show method.
Result:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class App {
public static void main(String[] args) {
Matrix m1 = new Matrix();
System.out.println("First Matrtix ");
m1.show();
Matrix m2 = new Matrix(5,4);
System.out.println("Second Matrtix ");
m2.show();
}
}
class Matrix {
private int q[][];
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public Matrix() {
this(3, 3);
}
public Matrix(int a, int b ) {
int value;
System.out.println("Input a number to fill the new 3x3 matrix");
try {
value = Integer.parseInt(br.readLine());
} catch (IOException e) {
throw new RuntimeException("There was a problem reading the number from console", e);
}
q = new int[a][b];
for(int i=0;i<a;i++) {
q[i] = new int[b];
for(int j=0;j<b;j++) {
q[i][j] = value;
}
}
}
public void show() {
for(int i=0; i<q.length; i++) {
for(int j=0;j<q[i].length;j++)
System.out.print(q[i][j]+" ");
System.out.print("\n");
}
}
}

Null pointer Exception even though setter method is present in Java [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I wrote a code for keeping record of indices even after sorting but it is showing me null pointer exception.I read other threads on same topic but still couldn't find.
import java.io.*;
import java.util.*;
public class Solution {
class Order{
public int index;
public int sum;
public void setIndex(int index){
this.index = index;
}
public void setSum(int sum){
this.sum = sum;
}
public int getSum(){
return this.sum;
}
public int getIndex(){
return this.index;
}
}
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
Order array[] = new Order[N];
int index = 0;
int sum = 0;
while(index<N){
int input1 = sc.nextInt();
int input2 = sc.nextInt();
//line 32
array[index].setIndex(index);
array[index].setSum(input1+input2);
index++;
}
ArrayList<Order> list = new ArrayList<Order>(Arrays.asList(array));
Collections.sort(list, new Comparator<Order>(){
#Override
public int compare(Order o1, Order o2){
return(Integer.compare(o1.getSum(), o2.getSum()));
}
});
System.out.println(list);
}
}
error is like this :
Exception in thread "main" java.lang.NullPointerException
at Solution.main(Solution.java:32)
I am passing i, still null pointer why?
You initialized array with Order array[] = new Order[N];, but the array is full of null objects. You need to initialize every element with new Order and then use setters

why cant i use System.out.println out side a method and when i try to use the method of my main class in other class it shows identifier not found [duplicate]

This question already has answers here:
Why can't I do assignment outside a method?
(7 answers)
Closed 7 years ago.
why cant i use System.out.println out side a method and when i try to use the method of my main class in other class it shows identifier not found
may be there are better way to do this . but i would like to learn this what is wrong here
package arraytest; //package declared
import java.util.Scanner; // for input
public class Arr { // this is my main class
void min(int arr[])
{
int min=arr[0];
for(int i=1;i<arr.length;i++)
{ if(min>arr[i])
min=arr[i];
}
System.out.println(min);
}
public static void main(String[] args)
{
Array a=new Array();
a.inputData();
a.display();
a.min();
}
}
class Array
{
int arr[]=new int[5];
Scanner sc= new Scanner(System.in);
// System.out.println(arr.length); will not work why?
void inputData()
{
for(int i=0;i<arr.length;i++)
{
arr[i]=sc.nextInt();
}
}
void display()
{
for(int i=0;i<arr.length;i++)
{
System.out.println(arr[i]);
}
}
void min()
{
Arr a=new Arr();
a.min(int arr[]); // this shows error
}
}
You can't put code there. Your code has to be inside of a method. The 2 lines above that are declarations, and the System.out.println is code.
Code has to go inside a method.'
You could use a static block if your arr was static, but it's not.
Change you min method as below,
void min() {
Arr a = new Arr();
a.min(arr); // this shows error
}
This is how you pass a reference of an array to the method.

Filling an array using a method [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 7 years ago.
I'm stuck with a revision question from a lab. The question is:
Write a static method to initialize an array of integers called numList. The size of the array should be passed as an int to the method and the array should be returned. Each odd index position should contain the value -1 and each even numbered position should contain the index value. Thus, such an array might contain {0,-1,2,-1,4,-1,6,-1}.
My code is currently :
public class initializeArray{
public static void main (String [] args) {
int [] numList = new int [6];
alterArray(numList);
}
public static void alterArray (int [] numList)
{
for( int i = 0; i<numList.length; i++)
{
if (i == 0)
{
numList[i] = i;
} else{
numList[i] = -1;
}
}
System.out.println( "The array is: " + numList);}
}
The return that I'm getting is :
"The array is: [I#1ef856c"
Thanks.
Updated to:
System.out.println(Arrays.toString(numList));
Error now occuring:
"Cannot find symbol - variable Arrays"
Try this:
System.out.println(Arrays.toString(numList));

Categories

Resources