This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
The program looks slightly advanced; it is not. Simple manipulation of array.
The program compiles correctly, however, it encounters an exception run-time.
Exception in thread "main" java.lang.NullPointerException
at Ordliste.leggTilOrd(Tekstanalyse.java:85)
at Tekstanalyse.main(Tekstanalyse.java:23)
So there is something wrong with if(s.equalsIgnoreCase(ordArray[k])).
I cannot see why. It even provides the correct output.
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class Tekstanalyse {
public static void main(String[] args) throws FileNotFoundException {
Ordliste ol = new Ordliste();
ol.lesBok("scarlet.text");
ol.leggTilOrd("A");
}
}
class Ordliste {
private int i = 0;
private String[] ordArray = new String[100000];
private int antForekomster;
private int arrStorrelse = 0;
public void lesBok(String filnavn) throws FileNotFoundException {
File minFil = new File(filnavn);
Scanner scan = new Scanner(minFil);
while (scan.hasNextLine()) {
ordArray[i] = scan.nextLine();
//System.out.println(ordArray[i]);
i++;
arrStorrelse++;
}
System.out.println("Array size: " + arrStorrelse + " Capacity: " + ordArray.length);
}
public void leggTilOrd(String s) {
for (int k = 0; k < ordArray.length; k++) {
if (s.equalsIgnoreCase(ordArray[k])) {
antForekomster++;
System.out.println("Den har vi sett for!");
} else {
s = ordArray[arrStorrelse];
}
}
}
}
I'm pretty sure the error is right here:
for (int k = 0; k < ordArray.length; k++) {
if (s.equalsIgnoreCase(ordArray[k])) {
antForekomster++;
System.out.println("Den har vi sett for!");
} else {
s = ordArray[arrStorrelse]; // <- dangerous
}
}
As I said in the comment, ordArray could contain null elements if the read text file does not contain 100.000 lines of text. If this is the case, the above line would write null to s because s.equalsIgnoreCase(null) is false.
You should think about using a list instead of an array.
private List<String> ordList = new ArrayList<String>();
(or use a different variable name, it is up to you)
Then you can add new entries to the list using ordList.add(scan.nextLine());. This list won't contain any null elements and your mentioned problem should be gone.
I would highly recommend you to simply use a debugger to debug your code , but here goes:
in your lesBok method you fill your array with strings and make a counter arrStorrelse. to be the amount of elements in the array you made. however the array is filled for indexes 0 to n-1. and arrStorrelse is equal to N you did however allocate space in the array for this. so when in leggTilOrd() you iterate the first time and you enter the else clause you do this
for (int k = 0; k < ordArray.length; k++) {
if (s.equalsIgnoreCase(ordArray[k])) {
antForekomster++;
System.out.println("Den har vi sett for!");
}
else {
int arrStorrelse2=arrStorrelse;
s = ordArray[arrStorrelse];
}
in that else clause s is set to ordArray[arrStorrElse]; however arrStorrElse is at that moment one higher than the last intialised element of your array. so it sets s to the null pointer.
then the next iteration of your loop in the if clause
if (s.equalsIgnoreCase(ordArray[k])) {
antForekomster++;
System.out.println("Den har vi sett for!");
the s.equalsIgnoreCase() call is done on an s that is null that's where the null pointer exception comes from.
you need to change the arrStorrElse assignment you haven't explained what it should do so i can't do that for you also try to learn how to debug your code here is a usefull link:
http://www.tutorialspoint.com/eclipse/eclipse_debugging_program.htm
I have compiled and tested your code.
s.equalsIgnoreCase(null)
throws nullPointerException.
Maybe you should try to use ArrayList instead of Array to avoid iterating through nulls.
It took me some time to figure out why the NullPointerException occurs and I have to agree with Piotr and Tom: The NPE is caused by the line
s.equalsIgnoreCase(ordArray[k])
and a side-effect in your code. This side-effect is introduced by reassigning the parameter s in the else-branch to null (this value comes from ordArray[arrStorrelse]). After this reassignment happened, you will have something like this:
null.equalsIgnoreCase(ordArray[k])
And voila, there is the NullPointerException.
Related
I have built a method which compares objects attributes with user input int. The method then adds all the objects to an array(the assignment demands it to be an Array and not ArrayList). After its added I have a foor-loop which prints out a list of Results for an athlete(in user input), it prints out all results from one category and then another and so forth..
I keep getting a NullPointerException error on the last line which is a System.out.println. I have searched for an answer for hours, and read the NullPointerException posts here but cannot find the issue or solve it.
for (int x = 0; x < category.size(); x++) {
Category c = categories.get(x);
System.out.println("Result in " + c.categoryName() + " for " + matchedAthlete.surName() + " "
+ matchedAthlete.lastName() + ": ");
for (int i = 0; i < individarrayresult.length; i++) {
Result res = individarrayresult[i];
if (res.nameOfCategory().equals(c.categoryName())) {
System.out.println(res.categoryResult());
}
}
}
So the last line of code ( System.out.println ) gets the NullPointerException, I am desperete for help. Below is the Array filled with results from only 1 Athlete.
Result[] individarrayresult = new Result[resultlist.size()];
for (int i = 0; i < resultlist.size(); i++) {
Result res = resultlist.get(i);
if (res.athleteStartNumber() == DSN) {
individarrayresult[i] = res;
}
}
If you have a NullPointerException on that row:
System.out.println(res.categoryResult());
The problem is in the method categoryResult because res is not null, otherwyse the previous test
if (res.nameOfCategory().equals(c.categoryName())) {
must throw the NullPointerException prior of the System.out.
So check the code of categoryResult() or post it.
Perhaps, as T.J. said, that the problem is not on that row but on the previous row and the NullPointerException is related to the value of res. Post the complete StackTrace and row lines of your code to be sure of that answer.
I think you're mistaken, I think you're getting the NPE one line earlier, on this line:
if (res.nameOfCategory().equals(c.categoryName())) {
And the reason you're getting it is there are nulls in your array, because of how you fill it:
Result[] individarrayresult = new Result[resultlist.size()];
for (int i = 0; i < resultlist.size(); i++) {
Result res = resultlist.get(i);
if (res.athleteStartNumber() == DSN) {
individarrayresult[i] = res;
}
}
If res.athleteStartNumber() == DSN is false, you never assign anything to individarrayresult[i], so that array entry keeps its null default.
How to fix it:
Build up a list of matching results:
List<> individResults = new Arraylist<Result>(resultlist.size());
for (int i = 0; i < resultlist.size(); i++) {
Result res = resultlist.get(i);
if (res.athleteStartNumber() == DSN) {
individResults.add(res);
}
}
...and then either use that list directly, or convert it to an array:
Result[] individarrayresult = individResults.toArray(new Result[individResults.size()]);
...and use the resulting array.
(You can also do the same with the nifty new streams stuff in the latest version of Java, but I'm not au fait with them...)
It's possible, of course, that you're getting the NPE on the line you said you are and that there are two problems, and it just happens you've been processing all DSN entries so far. If so, and you fix the other problem, the first time you have a non-DSN entry, you'll run into this problem unless it fix it as well.
I've read gone through the tutorials, so by all means, if you see something that I've done wrong here, please tell me so I can learn to better-participate on this site.
The getPerishedPassengers method below is giving me an out of bounds exception. I have researched and researched, and I seem to be populating the array properly, and I don't know what is wrong with the method that I've created either. Could someone guide me in the right direction as to how to overcome this exception? Thank you folks!
Here's the main/method:
int passengerMax = 2000;
int passengerActual = 0;
//Create a 2D array that will store the data from the .txt file
String[][] passengerData = new String[passengerMax][6];
//Constructor to read the file and store the data in the array
Titanic(String file) throws FileNotFoundException {
try (Scanner fileIn = new Scanner(new File(file))) {
//Conditional for reading the data
while (fileIn.hasNextLine()) {
//tab through the data to read
passengerData[passengerActual++] = fileIn.nextLine().split("\t");
}
}
}
public int getTotalPassengers() {
return passengerActual;
}
//Method for getting/returning the number of passengers that perished
public int getPerishedPassengers() {
int count = 0;
//For loop w/conditional to determine which passengers perished
for (int i = 0; i < getTotalPassengers(); i++) {
int survive = Integer.parseInt(passengerData[i][1]);
/*The program reads the file and if 1, the passenger survived. If 0,
the passenger perished. Conditional will add to the count if they
survived*/
if (survive == 0) {
count++;
}
}
return count;
}
Here's the stacktrace I'm receiving. I can include the test code as well if you folks would like. Thanks in advance:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at titanic.Titanic.getPerishedPassengers(Titanic.java:66)
at titanic.testTitanic.main(testTitanic.java:68)
Java Result: 1
From what I can see above, the issue is in the line:
int survive = Integer.parseInt(passengerData[i][1]);
My best guess, lacking your input file, is that when you are reading the file, at least one line creates an array of length 0 or 1. In all likelihood, if the last line of the file is an empty line, it would be this line which is causing your array out of bounds exception, as the split would create an array of length 0. Another cause would be a line which lacks any tab in it at all (say a space instead of tabs, etc.) will create a length 1 array, of which passengerData[i][1] will not exist, only passengerData[i][0] will.
Assuming that your input file does not have any lines which are improperly formatted / lack the appropriate number of tabs, I would suggest changing this line in the file read loop:
passengerData[passengerActual++] = fileIn.nextLine().split("\t");
to:
String incomingLine = fileIn.nextLine().trim();
if (null != incomingLine && !incomingLine.isEmpty()) {
passengerData[passengerActual++] = incomingLine.split("\t");
}
I apologize in advance, I am a java noob.
I have this in a statement
if(a==0 && b<4)
{
value = ((elev[a][b]-elev[a+1][b])*0.00001* double "variable" ) ;
}
So my main question is would the following....
(elev[a][b]-elev[a+1][b])
return an int value (assuming that the array was initialized and populated with int values, and that for a==0 and b<4 none of the references are null.
Sorry in advance if this is silly. Please don't feel inclined to comment, but help would be appreciated. I haven't done a lot of this java stuff.
When i populated the array, I printed it's contents to make sure I was populating correctly, and everything is where it should be...
Alas, I get a null pointer error wherever that (elev[a][b] - elev[a+1][b]) is first referenced....yet i know that the values are being put there.
Next question. When i populate an array, if i want to reference the values,
while(input.hasNextInt())
{
elev[i][j] = input.nextInt(); <-- this is how i was doing it
}
of elev[][]... do i need to say
elev[i][j] = new input.nextInt();
or is how i was doing it sufficient. When i populated an ArrayList from a file I had to use the "new" prefix So i was trying to figure out why i would get a null there.
Like i said I did print the array after reading it from the file and it printed out everything was in its place.
Thanks everyone.
EDIT
ok sorry for simplicity sake i didn't put in the actual code of "value"
it is actually
double randKg = getRandKg(avgKgNitrogen[z]);
double gradient = 0.00001
double under = ((randKg *(elev[a][b] - elev[a+1][b]) * gradient));
2nd Edit
This is the code for how i populated.
try{
File file = new File(filename);
Scanner input = new Scanner(file);
int rows = 30;
int columns = 10;
int elev[][] = new int[30][10];
for(int i = 0; i < rows; ++i){
for(int j = 0; j < columns; ++j)
{
while(input.hasNextInt())
{
elev[i][j] = input.nextInt();
}
}
}
input.close();
}
catch (java.io.FileNotFoundException e) {
System.out.println("Error opening "+filename+", ending program");
System.exit(1);
}
3rd edit
So i am getting the null pointer here.....
(elev[a][b] - elev[a+1][b]) > 0 )
Which is why i originally asked. I have printed the array before when i populated and everything is where it should be.
You are getting a null pointer exception because double "variable" does not indicate to any integer or double value. Compiler is just trying to convert String 'variable' into double which is not possible. So, try eliminating the Double Quotes from "variable". Moreover you have not declared the data type of value variable.
Ignoring other problems in your code (covered by other answers), here's about your actual question:
If the code
if(a==0 && b<4) {
value = (elev[a][b] - elev[a+1][b]);
}
crashes with NullPointerException, it means elev is null. Assuming a and b are of type int, then there is no other way this can generate that exception (array out of bounds exception would be different). There are two options for the cause:
You execute above code before you do int elev[][] = new int[30][10];, so that elev still has the initial null value.
elev in the crashing line is a different variable than elev in initialization shown in the question.
And in you code, it seems to be 2. You create local elev in the initialization. It goes out of scope and is forgotten. You probably should have this initialization line in your method:
elev = new int[30][10];
And then you should have a class member variable instead of local variable in a method:
private int[][] elev;
I am trying to send two variables from one sketch to another, using the oscP5 library for processing.
The message I am sending is created like this:
OscMessage myMessage = new OscMessage("/test");
myMessage.add(title);
myMessage.add("Zeit");
oscP5.send(myMessage, remoteLocation);
In the second sketch, I receive the data like that:
void oscEvent(OscMessage theOscMessage) {
if(theOscMessage.checkAddrPattern("/test")) {
String title = theOscMessage.get(0).stringValue();
String layoutType = theOscMessage.get(1).stringValue();
addToQueue(title, layoutType);
}
}
And here my simplified addToQueue function:
void addToQueue(String title, String layoutType) {
if(!existsInQueues(title)) {
upcomingHeadlines.add(new Headline(title, printAxis, scrollSpeed, layoutType));
}
}
Every time I start the sketches, I get the error:
ERROR # OscP5 ERROR. an error occured while forwarding an OscMessage to a method in your program. please check your code for any possible errors that might occur in the method where incoming OscMessages are parsed e.g. check for casting errors, possible nullpointers, array overflows ... .
method in charge : oscEvent java.lang.reflect.InvocationTargetException
I have been able to track the problem down to the layoutType-Variable. If I change
String layoutType = theOscMessage.get(1).stringValue();
to
String layoutType = "Zeit";
no error occurs.
That is quite confusing, because both versions should have the same result.
The error message does not help me in any way.
Edit
I have compared the two possible variables like that:
String layoutType = theOscMessage.get(1).stringValue();
String layoutTypeB = "Zeit";
if(layoutType.equals(layoutTypeB)) println("Same String!");
Since gets printed to the console, both have to be the same … I really do not know where to search for an error anymore.
Edit 2
I have wrapped my second sketch in try {...} catch(Exception ex) {ex.printStackTrace();} like that:
void oscEvent(OscMessage theOscMessage) {
try {
if(theOscMessage.checkAddrPattern("/test")) {
if(debug && debugFeed) println("Received message from other sketch.");
String title = theOscMessage.get(0).stringValue();
String layoutTypeO = (String)theOscMessage.get(1).stringValue();
String layoutType = "Zeit";
if(debug && debugTemp) {
if(layoutType.equals(layoutTypeO)) println("IS DOCH GLEICH!");
}
if(debug && debugFeed) println("Parsed Information.");
if(debug && debugFeed) println("-----");
addToQueue(title, layoutTypeO);
}
} catch(Exception ex) {ex.printStackTrace();}
}
That gives me this error as result:
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:635)
at java.util.ArrayList.get(ArrayList.java:411)
at printer$Headline.useLayout(printer.java:260)
at printer$Headline.<init>(printer.java:188)
at printer.addToQueue(printer.java:407)
at printer.oscEvent(printer.java:395)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at oscP5.OscP5.invoke(Unknown Source)
at oscP5.OscP5.callMethod(Unknown Source)
at oscP5.OscP5.process(Unknown Source)
at oscP5.OscNetManager.process(Unknown Source)
at netP5.AbstractUdpServer.run(Unknown Source)
at java.lang.Thread.run(Thread.java:744)
Edit 4
Constructor for my Headline-Class:
class Headline {
//Define Variables
Layout layout;
String title, lastHeadline;
float yPos, speed;
float transparency = 255;
boolean fullyPrinted = false;
int boundingBoxHeight;
// Initialize Class Function
Headline(String t, float y, float s, String lay) {
title = t;
yPos = y;
speed = s;
layout = useLayout(lay);
boundingBoxHeight = calculateTextHeight(title);
}
You might want to know about useLayout() too, so here it is:
Layout useLayout(String name) {
ArrayList layoutVariants = new ArrayList<Layout>();
int existingLayouts = layouts.size();
Layout chosenLayout;
for(int i = 0; i < existingLayouts; i++) {
Layout currentLayout = (Layout)layouts.get(i);
if(currentLayout.layoutType == name) {
layoutVariants.add(currentLayout);
}
}
if(layoutVariants != null) {
int rand = (int)(Math.random() * layoutVariants.size());
chosenLayout = (Layout)layoutVariants.get(rand);
} else {
chosenLayout = (Layout)layouts.get((int)(Math.random() * existingLayouts));
}
return chosenLayout;
}
There are two problems with your code, and both of them are in your useLayout method.
The first problem is that you are not comparing Stringss correctly on this line:
if(currentLayout.layoutType == name) {
name is a String, and I assume currentLayout.layoutType is too. Two Strings that are equal but not the same will not compare equal under ==. As a result of this, your layoutVariants list will quite probably be empty at the end of the for loop.
This line should read:
if(currentLayout.layoutType.equals(name)) {
See also this question.
The second problem is that you don't correctly handle the case that the layoutVariants list is empty. The problem is on this line:
if(layoutVariants != null) {
layoutVariants will never be null, so the else branch of this if statement will never execute. Because layoutVariants.size() will be zero, rand will always be zero. Trying to get the element at index 0 in an empty ArrayList will give you precisely the IndexOutOfBoundsException you are seeing.
I imagine you want the else block to execute if the layout name given isn't recognised, in other words, if the layoutVariants list is empty, rather than null. In that case, change this line to
if(!layoutVariants.isEmpty()) {
Note the ! (not-operator) before layoutVariants. You want the code under the if statement to run if the layoutVariants element is not empty.
EDIT in response to your comments: a null ArrayList is very much not the same as an empty one. null is a special value meaning that the variable doesn't have an object of a given type.
Let's try a real-world analogy: a shopping bag. If you have an empty bag, or no bag at all, then you have no shopping either way. However, you can put things into an empty bag, and count how many items it contains, for example. If you don't have a bag, then it doesn't make sense to put an item in it, as there's no bag to put the item into. null represents the case where you don't have a bag.
Similarly, a String is a collection of characters, and the collection of characters can exist even if it doesn't contain any characters.
isEmpty() can be used for any collection, and, if you're using Java 6 or later, Strings as well. Off the top of my head I can't name any other classes that have an isEmpty method. You'll just have to consult the documentation for these classes to find out.
I've not worked with Processing much, but I am aware that Processing is built on Java, so I would expect any standard Java method to work. Also, I wouldn't worry about 'clearing' a variable: the JVM is generally very good at clearing up after you. There's certainly nothing I can see wrong with your code in this respect.
EDIT 2 in response to your further comment: ArrayList arr; declares a variable of type ArrayList. However, the variable arr is uninitialized: it does not have a value (not even null) and it is an error to try to read the value of this variable before you have assigned a value to it:
ArrayList arr;
System.out.println(arr); // compiler error: arr might not have been initialised.
Assign null and the code then compiles:
ArrayList arr = null;
System.out.println(arr); // prints 'null'.
It's not often you need to declare a variable and not give it a name, but one common case is where you want to assign different values to the same variable on both sides of an if statement. The following code doesn't compile:
int y = getMeSomeInteger(); // assume this function exists
if (y == 4) {
int x = 2;
} else {
int x = 5;
}
System.out.println(x); // compiler error: cannot find symbol x
The reason it doesn't compile is that each variable x is only available within the braces { and } that contain it. At the bottom, neither variable x is available and so you get a compiler error.
We need to declare x further up. We could instead write the following;
int y = getMeSomeInteger(); // assume this function exists
int x = 0;
if (y == 4) {
x = 2;
} else {
x = 5;
}
System.out.println(x);
This code compiles and runs, but the value 0 initially assigned to x is never used. There isn't a lot of point in doing this, and we can get rid of this unused value by declaring the variable but not immediately giving it a value.
int y = getMeSomeInteger(); // assume this function exists
int x;
if (y == 4) {
x = 2;
} else {
x = 5;
}
System.out.println(x);
I am a newbie Computer Science high school student and I have trouble with a small snippet of code. Basically, my code should perform a basic CLI search in an array of integers. However, what happens is I get what appears to be an infinite loop (BlueJ, the compiler I'm using, gets stuck and I have to reset the machine). I have set break points but I still don't quite get the problem...(I don't even understand most of the things that it tells me)
Here's the offending code (assume that "ArrayUtil" works, because it does):
import java.util.Scanner;
public class intSearch
{
public static void main(String[] args)
{
search();
}
public static void search()
{
int[] randomArray = ArrayUtil.randomIntArray(20, 100);
Scanner searchInput = new Scanner(System.in);
int searchInt = searchInput.nextInt();
if (findNumber(randomArray, searchInt) == -1)
{
System.out.println("Error");
}else System.out.println("Searched Number: " + findNumber(randomArray, searchInt));
}
private static int findNumber(int[] searchedArray, int searchTerm)
{
for (int i = 0; searchedArray[i] == searchTerm && i < searchedArray.length; i++)
{
return i;
}
return -1;
}
}
This has been bugging me for some time now...please help me identify the problem!
I don't know about the infinite loop but the following code is not going to work as you intended. The i++ can never be reached so i will always have the value 0.
for (int i = 0; searchedArray[i] == searchTerm && i < searchedArray.length; i++)
{
return i;
}
return -1;
You probably mean this:
for (int i = 0; i < searchedArray.length; i++)
{
if (searchedArray[i] == searchTerm)
{
return i;
}
}
return -1;
I don't know what is the class ArrayUtil (I can not import is using my Netbeans). When I try to change that line with the line int[] randomArray = {1 , 2, 3, 5, 7, 10, 1 , 5}; It works perfectly.
And you should change the loop condition. I will not tell you why but try with my array and you will see the bug soon. After you see it, you can fix it:)
There are 4 basic issues here.
1. Putting searchedArray[i] == searchTerm before i < searchedArray.length can result in an out-of-bounds exception. You must always prevent that kind of code.
2. Your intention seems to be the opposite of your code. Your method name implies finding a search term. But, your code implies that you want to continue your loop scan until the search term is not found, although your loop won't do that either. Think of "for (; this ;) { that } " as "while this do that".
3. Place a break point at the beginning of "search". Then, with a small array, step through the code line by line with the debugger and watch the variables. They don't lie. They will tell you exactly what's happening.
4. Please use a standard IDE and compiler, such as Eclipse and Sun's JDK 6 or 7. Eclipse with JDK 7 is a serious combination that doesn't exhibit a strange "infinite loop" as you describe above.