NullPointerException on an array of strings - arrays

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

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

Simple ArrayIndexOutOfBoundsException 1 in loop

I have a .data file containing lines of values. I partition them into separate values using the split method, then I initialize an ArrayList where I add the model items to the list. I had a while loop for this specific code here which looked like this:
while (inFile.hasNextLine() {
// Do something
}
That didn't seem to work so I switched it to a for loop.
public MachineLearningInstance(File f) {
try {
int noOfRowsInData = 0;
LineNumberReader lnr = new LineNumberReader(new FileReader(f));
try {
lnr.skip(Long.MAX_VALUE);
noOfRowsInData = lnr.getLineNumber();
//System.out.println(noOfRowsInData);
lnr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
irisData = new ArrayList<Iris>();
// While there is another line in inFile.
Scanner inFile = new Scanner(f);
for (int i = 0; i < noOfRowsInData; i++) {
if (inFile.hasNextLine()) {
// Store line into String
String line = inFile.nextLine();
// Partition values into separate elements in array
String[] numbers = line.split(comma);
// Grab values from that line and store it into a Iris ArrayList Item
irisData.add(i, new Iris(i, numbers[0], numbers[1], numbers[2], numbers[3], numbers[4]));
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
For some weird reason (and I bet it is a really simply reason I just can't see it) I keep getting the ArrayListIndexOutOfBoundsException 1 when I run this piece of code. I'm guessing that my while loop keeps looping? I don't understand what the problem seems to be.
Is it possible that my LineNumberReader is not reading the number of lines properly? I don't think that is the case though. Most likely I am not declaring something correctly.
So this happened to solve my problem, I'm really tired and have no interest right now in finding out why but it fixed the issue lol:
for (int i = 0; i < noOfRowsInData - 1; i++) {
if (inFile.hasNextLine()) {
// Store line into String
String line = inFile.nextLine();
// Partition values into separate elements in array
String[] numbers = line.split(comma);
// Grab values from that line and store it into a Iris ArrayList Item
irisData.add(i, new Iris(i, numbers[0], numbers[1], numbers[2], numbers[3], numbers[4]));
}
}
Supposedly noOfRowsInData - 1 fixes it.

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

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

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.

String Arrays and Session

I am dealing one serious problem and seems i cannot find a logical solution.
Here it goes.
I have a string array in my code (jsp file). I want to pass the array in the same page , and i thought of making the array a session and call it again later in my code but it seems that i cannot take the session (with get.Attribute) and make it an array again. TO be more specise the following code might help you.
while (onomaq.next()) {
String onomatemp = onomaq.getString("one1");
String[] onoma = onomatemp.split(" ");
out.println(onoma[2]);
session.setAttribute("onoma", onoma);
}
} catch (Exception e) {
System.out.println("SQL Exception: " + e.toString());
}
%>
<%
try{
Object o = session.getAttribute("onoma");
String k=o.toString();
String[] name=k.split(",");
out.println(name[1]);
}
catch (Exception e)
{
System.out.println("SQL Exception: " + e.toString());
}
the out.println gives me a message lige [L.java.String and some characters.
Can anyone help me please?
Rather than calling toString() on your array object after obtainig it from session, just cast the object reference to an array (since your object IS an array) and use it.
This means, replace this code:
Object o = session.getAttribute("onoma");
String k=o.toString();
String[] name=k.split(",");
with
String[] name= (String[]) session.getAttribute("onoma");
p.s. purpose of toString() is somwhat different from what you seem to expect. See Javadoc.
String[] expected_array= (String[]) session.getAttribute("onoma");
Then run it inside a loop to retrieve. Example:
for(int i = 0; i < expected_array. length; i++)
{
String strings = expected_array[i] ;
}

Resources