Exception in thread "main" java.lang.NullPointerException? What does this mean? - arrays

I have an error when trying to run this program. This is not the entire program just the few details I think where the problem is. The error points out
if(board[randSpace].isEmpty()) and
cl.makeChutes(5);"
Error is :
"Exception in thread "main" java.lang.NullPointerException
at ChutesAndLadders.makeChutes(ChutesAndLadders.java:29)
at ChutesAndLadders.main(ChutesAndLadders.java:67)"
This is my program:
import java.util.Random;
public class ChutesAndLadders{
Cell [] board = new Cell [100];
Random rand = new Random ();
public int chutes, ladders;
public void makeChutes (int a ){
int makeChutes = a;
for (int i = 0; i < a; i++){
int randSpace = rand.nextInt(99);
if(board[randSpace].isEmpty())
board[randSpace] = new Cell (-10,"C");
else
i--;
}
}
public static void main(String[] args) {
// Create an instance of ChutesAndLadders
ChutesAndLadders cl = new ChutesAndLadders(10,10);
// Randomly place 5 more chutes and 5 more ladders
cl.makeChutes(5);
cl.makeLadders(5);
Here is my isEmpty:
public boolean isEmpty(){
for(int i = 0; i < board.length; i++)
{
if (board[i].isEmpty())
return true;
}
return false;
}
I could be entirely wrong on my coding. I'm still learning so please be patient. Thank you!

Following on what Dewfy said, board is an array of Cell objects. That means it is a placeholder for Cell objects --a bunch of nulls waiting to be replaced by a Cell.
If say, the object at position 1 (board[1]) has not been assigned a Cell object (i.e. you haven't issued a command like board[1]=new Cell() or something like that) then board[1] is null. Therefore if you were to ask board[1].isEmpty() you would get a NullPointerException because you are trying to call a method on a null object.
Now, your error is likely to come from board[randSpace] being null. So, the question is: does it contain a Cell object? Have you initialized your array with Cell objects?
One way to check this would be to say:
if (board[randSpace]==null || board[randSpace].isEmpty()) .....

Problem appears with this line:
if(board[randSpace].isEmpty())
so it is supposed that obect at randSpace already exists, if not you create object (Cell). But object is not yet created, how you can ask it if null isEmpty(). Just check against null first

Related

What does the error unexpected token 'public' mean?

I am a beginner in Apex and I need your help. What I am trying to do is creating a class that returns an array of formatted strings. The class has as a parameter the number of strings and it returns the array of strings formatted as:
Test 0, Test 1, ...Test n
The error I get is:
unexpected token 'public (line 1).
There might be more than one error in my code, if yes please feel free to let me know.
Thank you in advance!
public class StringArrayTest {
public static void generateStringArray(Integer n){
//List<String> stringArray = new List<String>();
for(Integer i=0; i<n; i++){
List<String>stringArray = new List<String>{'Test '+i};
}
return stringArray[];
}
}
There are a few things wrong with the code you have posted. When I tried this out I didn't get the error you mentioned, but here are the things to fix and get your code working:
The method should declare a return value of List<String>
Uncomment the line to initialize your list before the loop.
Return just the variable itself, no need to have the brackets. It's already a list.
Here is working code:
public class StringArrayTest {
public static List<String> generateStringArray(Integer n){
List<String> stringArray = new List<String>();
for(Integer i = 0; i < n; i++){
stringArray.add('Test ' + i);
}
return stringArray;
}
}

NullPointerException on an array of strings

My purpose is to get what a user types in and to store them in the array "info", then convert the info[0] into upper case. However, when I compile my code, I always got the message Exception in thread "main" java.lang.NullPointerException at the line "info[0]=info[0].toUpperCase();". But I totally have not idea what causes this exception. If anyone can tell me the cause, it would be great. Thank you!
public static void main(String[] args)
{
Scanner userScan = new Scanner(System.in);
String keyboard = userScan.nextLine();
StringTokenizer tokens = new StringTokenizer(keyboard, " ");
String[] info= new String[4];
for(int i=0; tokens.hasMoreTokens(); i++)
{
info[i] = tokens.nextToken();
}
info[0]=info[0].toUpperCase();
//other codes...
}
When you try to execute the code without any tokens, It would skip past the for loop, and try to perform
info[0].toUpperCase();
But since the for loop has been skipped info object is initialized to null.
Thus trying to access it would give you an Null Pointer Exception.
Just move the conversion inside the for loop to avoid this.
for(int i=0; tokens.hasMoreTokens(); i++){
info[i] = tokens.nextToken();
//converts only when value exists
info[i]=info[i].toUpperCase();
}

Apply method to array through for loop

I am trying to apply a method to an array of arrays through a for loop.
Unfortunately where I have inserted my array of arrays inside the checkGuess method, I am getting the error 'Local variable x defined in an enclosing scope must be final or effectively final'. I'm a little new to Java so I'm not sure what I'm doing wrong... any help would be greatly appreciated.
for(int x = 0; x < columns.length; x++){
columns[x][y].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event) {
checkGuess(columns[x][y]);
}
});
if(x>4 && y<5){
y++;
x=-1;
}
}
Additional info:
The array of arrays contains JButtons.
The method checkGuess() takes a JButton as an argument as so:
checkGuess(JButton guess){
}
In Java, variables that are used in an anonymous class must be final (or in Java 8, effectively final - essentially the same thing, just without the explicit final modifier). As for why this is, Jon Skeet has a very nice answer to this here.
One method of correcting your code is simply to assign x to a final reference, as shown below:
for (int x = 0; x < columns.length; x++) {
final int copy = x;
columns[x][y].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
checkGuess(columns[copy][y]);
}
});
}
ActionListener is an inner anonymous class and it doesn't know what 'x' is when it tries to read it when passing the array of arrays to the function checkGuess().
Untested, but this might work:
for(int x = 0; x < columns.length; x++){
columns[x][y].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event) {
checkGuess(this);
}
});
if(x>4 && y<5){
y++;
x=-1;
}
}
If not, you would need to find out how to pass x into the class.
I believe "this" will reference the parent of the class, which should be 'columns[x][y]. I could be wrong though.

how to make getArray method

When I run a specific part of a code I have:
public String getWords (){
randomWord = words[randy.nextInt(words.length)];
return randomWord;
}
private String[] words = {"apple", "beret", "arose", "along", "beamy", "becks", "decks", "barks",
"stark", "start", "stabs", "baggy", "asked", "asset", "asses", "audit",
"bowls", "boxes", "seats", "balls", "boats", "boxer", "brick", "bound",
"brass", "caked", "braid", "caged", "essay", "fault", "dents", "dutch",
"ethos", "dunks", "pains", "faxes", "mummy", "mixer", "mills", "might",
"moral", "teeth", "wings", "works", "walls", "tolls", "crawl", "toxin",
"bangs", "tough"};
Hangman man = new Hangman();
man.mainScreen();
public void mainScreen (){
start();
while (guesses != maxGuesses){
continueGame();
checkBodyParts();
}
gameOver();
}
ERROR:
java.lang.NullPointerException
at Hangman.getWords(Hangman.java:43)
at Hangman.<init>(Hangman.java:28)
at GameApp.main(GameApp.java:9)
I get a runtime error of NullPointerException. I asked around and they said I should make a method to get the array words because I can't get to it at the moment. What should this method have in it?
I believe your problem is here:
private String myGeneratedRandomWord = getWords();
This method is trying to use the array "words" before it is created.
Move this line after the array "words" is created.
This should solve your NullPointerError.

Is there any possibility to store all database fields value into one array variable if all fields have same datatype in java?

in this program i have used different array variable for each of
the fields in a
database.In database all fields having the same datatype and now i want to store all
the fields values into one array variable.is it possible???
import java.sql.*;
class ja1
{
public static void main(String ar[])
{
try
{
int x,i,j,k,l;
int a[]=new int[30];
int b[]=new int[30];
int c[]=new int[30];
int d[]=new int[30];
int count[]=new int[10];
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c1=DriverManager.getConnection("Jdbc:Odbc:ds");
Statement s=c1.createStatement();
ResultSet r=s.executeQuery("select * from pro");
i=0;
j=0;
k=0;
l=0;
x=0;
while(r.next())
{
a[i]=r.getInt(2);
i++;
b[j]=r.getInt(3);
j++;
c[k]=r.getInt(4);
k++;
d[l]=r.getInt(5);
l++;
}
for(i=0;i<6;i++)
System.out.println(""+a[i]);
for(j=0;j<6;j++)
System.out.println(""+b[j]);
System.out.print("\n\n");
for(k=0;k<6;k++)
System.out.println(""+c[k]);
System.out.print("\n\n");
for(l=0;l<6;l++)
System.out.println(""+d[l]);
}
catch(Exception e)
{
System.out.print(e);
}
}
}
Yes, it is possible in several ways :
1) If you want to use only one array then please create an array with size of 120 (4X30) and use 4 counter to arrange your data in range. That means, your first variable would be from index 0 to 29, the 2nd would be from 30 to 69 and so on. This is not good if you don't know the exact size of your array as you are binding them with perfect size of 30.
2) You can create a POJO and have 4 arrays into it, you can use a List instead of array, but it depends on your implementation. So, create a class, put 4 arrays into it, give good variable names and access thru getter/setter methods. This will be a clear code
3) You can use a Map<Integer,Integer[]> or Map<Integer,List<Integer>> and have a single variable/reference which is holding your key value pair.
It all depends on you, if you dont know, why are you using arrays,then please move the Collection
I would define a POJO for the record and then use a generic list to add and iterate the record/s
Try this:
class RecordData
{
public int First;
public int Second;
public int Third;
public int Fourth;
}
class ja1
{
public static void main(String ar[])
{
try
{
List<RecordData> list = new ArrayList<RecordData>;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c1=DriverManager.getConnection("Jdbc:Odbc:ds");
Statement s=c1.createStatement();
ResultSet r=s.executeQuery("select * from pro");
while(r.next())
{
RecordData data = new RecordData();
data.First = r.getInt(2);
data.Second = r.getInt(3);
data.Third = r.getInt(4);
data.Fourth = r.getInt(5);
list.add(data);
}
for(RecordData data : list) {
System.out.println(data.First);
System.out.println(data.Second);
System.out.println(data.Third);
System.out.println(data.Fourth);
}
}
catch(Exception e)
{
System.out.print(e);
}
}
}

Resources