Today I got a NullPointerException at a point where it actually can't occur.
Exception in thread "Timer-9" java.lang.NullPointerException
at packagename.censored.Bot.changeServergroups(Bot.java:1363)
at packagename.censored.Bot.xpTask(Bot.java:1239)
at packagename.censored.Bot.access$7(Bot.java:1187)
at packagename.censored.Bot$9.run(Bot.java:729)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)
This is the relevant part of the code:
public void changeServergroups(int cldbid, ArrayList<Integer> addList, ArrayList<Integer> removeList) {
// If there are groups to add AND delete, remove them from the lists
if (addList != null && removeList != null) {
ArrayList<Integer> temp = new ArrayList<Integer>(addList);
for (int s : temp) { // THIS IS LINE 1363
if (removeList.contains(s)) {
addList.remove((Integer) s);
removeList.remove((Integer) s);
}
}
}
// some more code, to do the actual group changes
}
How is it possible to get the NullPointerException there? I check to make sure that addList is not null before creating a new temporary ArrayList from it. Can someone tell me how this could possibly return in a NullPointerException?
The only possibility is that your list temp contains null. The null Integer is then unboxed to an int and that throws a NPE.
You can solve the NPE by using for (Integer s : temp) if having a null value is acceptable.
Related
I have been working on this code for hours how can I throw a NoSuchElement exception so that it stops the loop when it reaches the beginning of the list right now here is what the test case outputs with my code
expected: but was:
Expected :a
Actual :z
* Returns the data from next element in the set.
* #return the data from next element in the set
*/
public E next() {
// TODO : Implement
//returns the next element in the collection and advances
// the iterator by one location (updating both internal references).
// If one were to call next(), then prev(), then next(), the results of the two next() calls should be identical.
E temp = this.nextElem.info;
if (this.nextElem != null) {
//throw new NoSuchElementException("No element found");
return temp;
}
if (temp != nextElem.info) {
//E temp2 = this.nextElem.info;
//nextElem = nextElem.next;
//return temp2;
throw new NoSuchElementException();
} else {
return temp;
}
code
What about just doing the following?
public E next() {
E temp = this.nextElem;
if (temp != null) {
return temp.info;
} else {
throw new NoSuchElementException();
}
}
Edit:
Sorry, I forgot to explain what went wrong in your code.
What exactly will be null when you reach the end of the loop? Will this.nextElem be null? Because if so, you will already get a NullPointerException in the line E temp = this.nextElem.info;. Or, will this.nextElem.info be null?
Carefully read through your code. At first, you are assigning this.nextElem.info to the variable temp. Later, you are comparing temp to nextElem.info in the if-statement. Keep in mind that this.nextElem.info and nextElem.info are usually synonymous. Hence, what you are effectively doing is the following: if (nextElem.info != nextElem.info) {. As you can see, the condition will always evaluate to falseand you will always go into theelsebranch and never reach yourthrow`.
Consider that one of only two things can occur when the method is called:
throw an exception because there is no next element
return the next element and advance the cursor
So your algorithm could be summarized as:
public E next() {
// throw an exception because there is no next element
if there is no next element
throw exception
endif
// return the next element and advance the cursor
let info be the info at the next element
advance the cursor to next element
return info
}
How this is actually implemented depends on implementation details you have not provided. This appears to be a class assignment so pseudo-code should be sufficient to get you going. Note that the order of operations matters. For instance, if there is no next element then you shouldn't be trying to capture the value at the next element.
public class StudentSchedular {
private Student[] students=new Student[10];
private int counterStudent;
public String addStudent(int rollNumber,String name)
{
students[counterStudent++]=new Student(rollNumber,name);
return "Student added successfully";
}
public void showAllStudents()
{
for(int i=0;i<students.length;i++){
System.out.println(students[i].getRollNumber());
System.out.println(students[i].getName());
}
}
}
I know this is a noob question..but still !
Here I have omitted the other getter/setter parts and other cases where I input the values for rollnumber and name. I am trying to print the object array, but it is giving an null pointer exception. I am inputting only 2 3 values and when I try to print, it gives NPE. I know this is because of null values being in the remaining index positions, I just needed a soln to print the whole object array !
The reason why you get NullPointerException is because of private Student[] students=new Student[10];. It means that you have an Student array which has a fixed size of 10. Default Object values in Java is null. Without adding anything to the array it means you have 10 null objects in students.
If an offset in the students array is not filled yet, you will hit a null value and get an exception, because you try to invoke a method on null.
You can validate it in the loop:
for(int i=0;i<students.length;i++){
if(students[i] instanceof User) {
System.out.println(students[i].getRollNumber());
System.out.println(students[i].getName());
}
}
EDIT: This 'issue' can be avoided by using List<User> instead of User[]. But I can't decide for you if it makes more sense.
I prefer the new For loop (since Java 5).
for(Student student : this.students) {
}
The new for loop works for arrays and all iterables objects, like ArrayList. You'll get only non-null objects.
For answer your question, the best practice is:
Overriding toString() in your Student Object.
#Override
public void String toString(){
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(this.rollNumber);
stringBuilder.append(this.name);
return stringBuilder.toString();
}
And at your loop, just do
System.out.println(stundents[i]);
println handles null values as you want, and code turns clean.
Your array has 10 slots. If 3 are given values, then you have 7 slots with null. You will need to either change the type of data structure you are using, or check for nulls when printing. The below code would do a null check and then print which index in the array contains the null value.
public void showAllStudents()
{
for(int i=0;i<students.length;i++)
{
if(students[i] != null) {
System.out.println(students[i].getRollNumber());
System.out.println(students[i].getName());
}
else
{
System.out.println("Array is null at index: " + i);
}
}
}
I'm having a problem with retrieving and casting ArrayList from session. I get the following error:
javax.servlet.ServletException: java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
I stored the arrayList in the session:
List<UserApplication> userList = uaDAO.searchUser(eds);
if (!userList.isEmpty()) {
request.getSession().setAttribute("userList", userList);
action_forward = EDITSUCCESS;
and for casting the session object to ArrayList, did the following:
EditStudentForm edt = (EditStudentForm)form;
if ((session.getAttribute("userList")) instanceof List){
List <UserApplication> studtList = (ArrayList<UserApplication>)session.getAttribute("userList");
}
try {
uaDAO.editUser(edt,studtList);
action_forward = EDITSUCCESS;
}
I'm getting the error over here in the DAO class:
public void editUser(EditStudentForm edt,List studtList) throws Exception {
PreparedStatement pst = null;
StringBuilder sb = new StringBuilder();
int stCode =Integer.parseInt(studtList.get(1).toString()); GETTING ERROR HERE
if (edt.getTitle() != null && !edt.getTitle().equals(studtList.get(2).toString())) {
sb.append("title = '").append(edt.getTitle()).append("'");
}
.
.
You are explicitly asking for 2nd (studtList.get(1)) and 3rd (studtList.get(2)) item in the list but never really make sure this list is big enough. Moreover your code apparently doesn't even compile:
if ((session.getAttribute("userList")) instanceof List){
List <UserApplication> studtList = ///...
}
try {
uaDAO.editUser(edt,studtList);
studtList is unaccessible in try block, also parenthesis in if statement are unmatched.
Check your studtList value.
From the error it seems your studtList only contain one item and you're try to get the second item with this code :
int stCode =Integer.parseInt(studtList.get(1).toString());
Change your code like this :
public void editUser(EditStudentForm edt,List studtList) throws Exception {
PreparedStatement pst = null;
StringBuilder sb = new StringBuilder();
if(studtList.size() > 1)
int stCode =Integer.parseInt(studtList.get(1).toString()); GETTING ERROR HERE
if (studtList.size() > 2 && edt.getTitle() != null && !edt.getTitle().equals(studtList.get(2).toString())) {
sb.append("title = '").append(edt.getTitle()).append("'");
}
}
In studtList there are no two elements and size of list maybe 1 or 0 elements, you should check it before try to call studtList.get(1). In ArrayList indexing start from 0 and if you want get first element you should call studtList.get(0).
In this code:
EditStudentForm edt = (EditStudentForm)form;
if ((session.getAttribute("userList")) instanceof List){
List <UserApplication> studtList = (ArrayList<UserApplication>)session.getAttribute("userList");
}
try {
uaDAO.editUser(edt,studtList);
action_forward = EDITSUCCESS;
}
You create a new variable 'studtList' that is never used. It's scope is only the { } pair around that one line.
There has to be another variable by that same name, studtList, in the outer scope so the 'editUser()' call can work.
Additional Note
As the other folks have answered, it looks like you may be doing a .get(1) and expecting the first element of the array list. Maybe. Maybe not.
public void createGraph () {
int oldFrom = -1;
int oldTo = -1;
for(int i = 0; i < edges.size(); i++) {
EdgeI e = edges.get(i);
int from = e.from;
int to = e.to;
VertexI v = vertices.get(from);
if (from == oldFrom && to == oldTo){
vertexWeight wic = v.neighbors.get(v.neighbors.size() - 1);
wic.w++;
}
else {
v.neighbors.add(new vertexWeight (to, 1));
oldFrom = from;
oldTo = to;
}
}
}
neighbors is a public List from VertexI class. w is a public integer from vertexWeight class. edges is a list located in my main class. I keep getting a null pointer exception for this line of code:
v.neighbors.add(new vertexWeight (to, 1));
Tried working on it for around 15 minutes and I didn't get it to work. What am I messing up on?
java.lang.NullPointerException
at tester.createGraph(tester.java:60)
at tester.main(tester.java:11)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
Short answer
Initialize v.neighbors with new ArrayList() in vertices.get().
Long answer
Your question omitted a crucial information: How you initialized neighbors. Why is this important?
See: What is a NullPointerException, and how do I fix it?
In your case I guessed that either v or neighbors is null during the run of the program. For example vertices.get(from) could return null and v.neighbors won't work. Or neighbors is null, and v.neighbors.add() won't work.
And voilĂ . You admitted that you set neighbors to null when initializing VertexI.
The solution is: Initialize with new ArrayList() instead of null.
If that would not have been possible or you cannot avoid null pointers for some other reason, you can do null pointer checks like this:
if (v != null && v.neighbors != null) {
v.neighbors.add(new vertexWeight (to, 1));
}
This means, don't add vertices if v or neighbors are null.
But this is complicated and error-prone. It is easier to avoid null pointers as much as possible. Some would say, avoid them at all costs! Throw an exception instead or return an "empty" object like new ArrayList().
I have this function with some dead code, marked by Eclipse.
I have two lines that check a & b. Lines that check b are marked as null.
public int[] runThis(List<Integer> buildIds, List<Integer> scenarios, boolean oflag) {
int rating[] = new int[scenarios.size()];
if(buildIds == null) {
System.out.println("ERROR - Building ID list is null!");
return null;
}
if(scenarios == null) {
System.out.println("ERROR - Scenario list is null!"); //dead
return null; //dead
}
return rating;
}
Why does Ellipse make the two lines as dead? Any help? Thanks very much for your time.
Because you've already called scenarios.size() in your array constructor. This guarantees scenarios isn't null or it will have thrown an exception by that point.