Null Pointer Exception with a 2d array [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
objects classes and arrays - why is it returning ‘null’ ? [java]
The other questions with similar titles all have the answer that their data needs to be initialized which I have done but I'm still getting a null pointer exception. Could anyone tell me why?
public class grid{
private Node [][] board = new Node [9][9];
public boolean add(int x, int y, char label) {
boolean valid=true;
System.out.println("enter add");
if(label==' '){
System.out.println("enter if 1");
board[x][y].setValue('0');
}
else if(label<='9'&&label>'0'){
System.out.println("enter if 2");
board[x][y].setValue(label);
}
else{
valid=false;
}
if(valid)
System.out.println("valid");
return valid;
}
I'm getting the error on the setValue Lines (10 and 14)
public class Node{
public char value;
public char [] possibleValues = {1,2,3,4,5,6,7,8,9};
public boolean correct=false;
}
Edit: I figured it out, if anyone else has the same problem, this seems to fix it.
if(label==' '){
System.out.println("enter if 1");
board[x][y]= new Node(' ');
}
else if(label<='9'&&label>'0'){
System.out.println("enter if 2");
board[x][y]= new Node(label);
}

An array does not initialize the elements of the array. So, each board[x][y] will be initially null.

Related

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

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

java poker game nullpointer [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm getting a null pointer exception for this and I'm not sure why
public static boolean hasPair(Card[] cards) {
int k=0;
cards = new Card[5];
for (int atPos = 0; atPos<5; atPos++){
for (int atPos2 = atPos+1; atPos2<5; atPos2++){
if(cards[atPos].getValue() == cards[atPos2].getValue()){
k++;
}
if (atPos2 == (cards.length-1) && k!=1){
k=0;
}
else if (atPos2 == (cards.length-1) && k>=2){
return true;
}
}
}
return false;
}
My method is testing whether or not my hand of cards has two cards that hold the same value and the nul pointer says it's within this line
if(cards[atPos].getValue() == cards[atPos2].getValue()){
I also have this method...could i use it as a helper?
public Card[] deal(int numCards) {
Card[] newArray;
newArray = new Card[numCards];
for (int index=0; index<numCards; index++){
newArray[index] = cards.get(0);
cards.remove(0);
}
return newArray;
}
In second line you create a new array of objects Card. Every object in that array is null, so you need to fill the array first.

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

Generating random numbers to put in an array, if number is a duplicate draw then reroll. Boolean check is "sometimes" working

Edit: Uh well now that I pasted code into here and looked at it.. I have 2 .. "duplicate methods" .. Eclipse for some god awful reason hid the first "boolean checkforDupes()" from me. It seems to be fixed now, still poking it to make sure, should I just like.. delete the post or something?
I have a class assignment, which I've done essentially everything for, but I'm having issues with generating some random numbers to put into an array, and if they number has already been "drawn" then the number is re-generated so that there are no duplicates.
I've looked through several articles and have seen various ways to accomplish what I'm trying to do, but I'm really just trying to locate the flaw in my method/reasoning/etc.
(Pulling numbers from a fully populated array randomly, or shuffling an array and picking a handful, using a Set for unique numbers etc)
Essentially the program is just supposed to generate 5 lotto numbers, player(or computer player in this case) also selects 5 numbers. Each number set is to be unique, and then you compare the Array/List/whatever and pull out matches for assumed points or notoriety.
Somewhere between my generateNumbers() and checkForDupes() methods my logic has failed me and I've been stumped for a few hours. Sometimes the generator works and recognizes that it has rolled a duplicate and will reroll, but other times it will say reroll the first number but numbers 3 & 4 are duplicates which it ignores.
Any insight into this would be much appreciated.
package lottery;
import java.util.*;
public class Lottery {
final int chance = 5; //holds the number of lottery numbers to be picked
private int lotteryNumbers[] = new int[chance]; //array to hold the lottery numbers
private int playerNumbers[] = new int[chance]; //array to hold player's numbers
//Maybe rewrite with a Set instead of Array.
//Or generate random numbers and put them in array and "draw" lotto numbers from the array. Well now that I'm looking at my post, this comment is more of my I give up, next step stuff !
public Lottery(){
generateNumbers(lotteryNumbers);
System.out.println("Lottery numbers");
generateNumbers(playerNumbers);
System.out.println("Player numbers");
}
public String returnDate(){
Date date = new Date();
// display time and date using toString()
return date.toString();
}
public int[] getLotteryNumbers() {
return lotteryNumbers;
}
public int[] getPlayerNumbers() {
return playerNumbers;
}
private int[] generateNumbers(int[] numbers){
int check;//variable to pass for checking dupes
int count = 0;
Boolean DoIt=null;
Random rng = new Random(); //Used to pick lottery numbers
while (count<chance)
{
check = rng.nextInt(5)+1;//assigns random number to check
DoIt = checkforDupes(check, numbers);//passes check and the array to be checked for dupes
if (DoIt == true) //to execute if dupe checker says its ok
{
numbers[count] = check;
System.out.print(numbers[count]+" in ["+count+"], ");
count++;
}
else //supposed to restart the loop without incrementing for a new number if dupe
{
System.out.println(" Dupe rerolling "+check+" ["+count+"], ");
}
}
return numbers;
}
private boolean checkforDupes(int check, int[] array){
//pass in the generated variable and the array, check array if duplicates then return true or false to add the number
for(int i=0; i<chance; i++)
if (check == array[i])
return false;
else
return true;
return false;
}
private Boolean checkForDupes(int check, int[] array){
Boolean doIt = false;
for (int i=0; i<array.length; i++)
{
if (check == array[i])
{
doIt = false;
System.out.println("DON'T!"); //not printing anything to console
break;
}
else
doIt = true;
}
System.out.println("Am I even being called"); //also not printing to console...
return doIt;
}
public void checkMatches(int[] array1, int[] array2){
for (int index = 0; index<array1.length; index++)
if (array1[index] == array2[index])
System.out.print(array1[index]+" ");
System.out.println();
System.out.println("**** Possible Matches listed above ****");
}
}
if (check == array[i])
return false;
else
return true;
This is in a for loop, so it runs once for each array element (with i being the index of that element).
If check equals this array element, you return false. Otherwise, you return true.
And it never gets to go around the loop again, because returning exits the method immediately.
Here i have implemented with c# you can convert it into java if needed. I have used dictionary for faster searching.
Here is the code, You can modify it accordingly:
static Dictionary<int, int> randomNoArray = new Dictionary<int, int>();
static int[] arrayHavingManyNo= new int[] { 3, 4, 5,........... };
static void Main(string[] args)
{
while (true)
{
int randomNo = 0;
Console.WriteLine("press 1 to generate random and insert.");
Console.WriteLine("Press 2 to display No in Array");
if (Console.Read() == 1)
{
randomNo = GenerateRandom(1, 100);
if (!checkInArray(randomNo))
{
InsertInArray(Full[randomNo], Full[randomNo]);
}
}
else
{
foreach (KeyValuePair<int, int> pair in randomNoArray)
{
Console.WriteLine(pair.Value);
}
}
}
}
static int GenerateRandom(int start,int end)
{
return Convert.ToInt32(new Random().Next(start, end));
}
static bool checkInArray(int no)
{
return (randomNoArray.ContainsKey(Full[no]));
}
static void InsertInArray(int key , int value)
{
randomNoArray.Add(key,value);
}
}

Categories

Resources