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

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

Related

Unable to run code for creating list of random numbers [duplicate]

This question already has answers here:
No Main class found in NetBeans
(16 answers)
How can I fix this error at Eclipse for JAVA?
(2 answers)
Closed 1 year ago.
This is the code I'm using.
import java.util.ArrayList;
public class Random {
public static ArrayList<Integer> generateRandomList( int size, int min, int max) {
ArrayList<Integer> list;
list = new ArrayList<>();
for(int i=0;i<size;i++) {
int n = (int)(Math.random() * (max-min))+min;
list.add(n);
}
return list;
}
}
In Eclipse IDE when I try to run it says "the selection cannot be launched, and there are no recent launches." In Netbeans it says "no main classes found."
What am I doing wrong?
In java, you need a main method to run. In the code you have included, that isn't there, and so the IDE doesn't know what you want to do with it. When I use the following code, it works as expected:
import java.util.ArrayList;
public class Random {
public static void main(String[] args)
{
System.out.println(generateRandomList(3,0,5));
}
public static ArrayList<Integer> generateRandomList( int size, int min, int max) {
ArrayList<Integer> list;
list = new ArrayList<>();
for(int i=0;i<size;i++) {
int n = (int)(Math.random() * (max-min))+min;
list.add(n);
}
return list;
}
}
Here is a link to a good explanation about main() methods in java.

Java program giving stack overflow [duplicate]

This question already has answers here:
What is a StackOverflowError?
(16 answers)
Closed 2 years ago.
During execution the problem is giving stack overflow problem, but what is this!
Runtime Error (NZEC)
Exception in thread main java.lang.StackOverflowError at
sun.nio.cs.US_ASCII$Encoder.encodeArrayLoop(US_ASCII.java:198) at
sun.nio.cs.US_ASCII$Encoder.encodeLoop(US_ASCII.java:231) at
java.nio.charset.CharsetEncoder.encode(CharsetEncoder.java:579) at
sun.nio.cs.StreamEncoder.implWrite(StreamEncoder.java:271) at
sun.nio.cs.StreamEncoder.write(StreamEncoder.java:125) at
java.io.OutputStreamWriter.write(OutputStreamWriter.java:207) at
java.io.BufferedWriter.flushBuffer(BufferedWriter.java:129) at
java.io.PrintStream.write(PrintStream.java:526) at
java.io.PrintStream.print(PrintStream.java:669) at
Solution.solve(Solution.java:22) at Solution.solve(Solution.java:23)
at Solution.solve(Solution.java:23) at
Solution.solve(Solution.java:23) at Solution.solve(Solution.java:23)
at Solution.solve(Solution.java:23) at
Solution.solve(Solution.java:27) at Solution.solve(Solution.java:23)
at Solution.solve(Solution.java:27) at
Solution.solve(Solution.java:23)
import java.util.*;
public class Solution {
public static void printIncreasingNumber(int n) {
/* Your class should be named Solution.
* Don't write main() function.
* Don't read input, it is passed as function argument.
* Print output as specified in the question
*/
int k = 10;
int N = (int)Math.pow(10,n);//limit
solve((int)Math.pow(10,n-1),N);
}
static void solve(int j,int n){
if(j==n){
return;
}
if(check(j)){
System.out.print(j+" ");
solve(j+1,n);
}
else{
j = increase(j,n);
solve(j,n);
}
}
static boolean check(int k){
ArrayList<Integer> arr = new ArrayList<>();
int temp = k;
while(temp>0){
arr.add(temp%10);
temp = temp/10;
}
boolean ans = true;
for(int i=0;i<arr.size()-1;i++){
if(arr.get(i)<=arr.get(i+1)){
ans = false;
return ans;
}
}
return ans;
}
static int increase(int j,int n){
int ans = 0;
for(int i = j;i<n;i++){
ArrayList<Integer> arr1 = new ArrayList<>();
int temp = i;
while(temp>0){
arr1.add(temp%10);
temp = temp/10;
}
int count = 0;
for(int i1=0;i1<arr1.size()-1;i1++){
if(arr1.get(i1)<=arr1.get(i1+1)){
count++;
}
}
if(count==0){
ans = i;
break;
}
}
return ans;
}
}
My main function is,
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int a;
Scanner s = new Scanner(System.in);
a = s.nextInt();
Solution.printIncreasingNumber(a);
}
}
You have several problems in your code:
Instead of if(j==n){ you should use if(j>=n){
It look like function increase has bug, due to this function returns same number or 0 (it is a quite strange for increase function, isn't?). For example, if you call printIncreasingNumber(2), when j = 90 this function returns 0 and you have infinitive loop (you call solve function again and again from 0 till 90),
P.S. I recommend you use any Java debbuger for checking, then you can see all numbers step by step.

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");
}
}
}

How do you print a stack in Java? [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 4 years ago.
I have tried many different things to try to print this stack but it keeps printing the hashcode ie. Problem1$Node#3d4eac69. I have searched a lot online and found nothing that has worked for this so if there are any suggestions help is greatly appreciated.
import java.util.*;
public class Problem1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Reading the first integer containing the number of test queries
int N = input.nextInt();
// Initializing the maximum value
int max = Integer.MIN_VALUE;
// Initializing the stack.
Stack<Node> stack = new Stack<Node>();
// Read the query and perform the actions specified.
for(int i = 0; i < N; i++){
int x = input.nextInt();
if(x == 1){
int value = input.nextInt();
Node n = new Node(value);
stack.push(n);
System.out.println(stack);
}
else if(x == 2){
stack.pop();
}
else if(x == 3){
System.out.println(stack.peek());
}
}
}
static class Node{
int data;
public Node(int data){
this.data = data;
}
}
}
You need to override the default toString method (inherited from Object see API here ) in your Node class, something like this:
static class Node {
int data;
public Node(int data){
this.data = data;
}
#Override
public String toString() {
return "Node: "+data;
}
}
The toString method is used when you try to print the object as a String. If you don't have one, it will use the Object's one which builds a String this way
getClass().getName() + '#' + Integer.toHexString(hashCode()))
and gives you something like Problem1$Node#3d4eac69

NullPointerException in array of objects [duplicate]

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

Categories

Resources