JAVA Getting a nullpointer exception in an "if" statement? - java

public void display(Date date) {
boolean loop = true;
System.out.println("Events on " + date.toString());
for (int i = 0; i < schedule.length; i++) {
while (loop) {
Date tmp = schedule[i].nextOccurrence();
if (tmp.compareTo(date) == 0) {
System.out.println(schedule[i].nextOccurrence().toString());
}
}
schedule[i].init();
}
}
The above is supposed to print out an occurrence of an event if it falls on the date given to the method. The method nextOccurrence grabs the next occurrence of an event (if its weekly or daily). nextOccurence looks like this for a DailyEvent:
public Date nextOccurrence() {
if (timesCalled == recurrences) {
return null;
}
else {
Calendar cal = Calendar.getInstance();
cal.setTime(startTime);
cal.add(Calendar.DATE, timesCalled);
timesCalled++;
return cal.getTime();
}
}
I call schedule[i].init() to reset the number of times called to 0 (daily events have a limit of number of times they can be called, denoted as an int with the variable recurrences).
Basically, my problem is that I'm getting a NullPointerException for this line:
if (tmp.compareTo(date) == 0) {
I've tried everything and I'm completely lost.
Any help would be great!

your method nextOccurence may return null, you need to check for that :
if (tmp != null && tmp.compareTo(date) == 0) {
Also, your loop variable is never set to false and will cause an infinite loop... And you call nextOccurrence() twice within your loop; is that desired?
You might consider redesigning your getNextOccurence() and have your schedule class implement an iterator for your dates. This will change your loop with
Iterator<Date> iterator = schedule[i].occurenceIterator();
Date tmp;
while (iterator.hasNext()) {
tmp = iterator.next();
if (tmp.compareTo(date) == 0) {
System.out.println(tmp.toString());
}
}
which is cleaner than what you're using.

I have a feeling that your nextOccurrence() function is returning null. If it returns null, then you'll get a NullPointerException when you try to use the compareTo function on that object.

Why didn't you step through this in a debugger?
My guess is that
public Date nextOccurrence() {
if (timesCalled == recurrences) {
return null; // <<<<
}
the line with '<<<<' is the root of the problem.

Related

Error handling for a while loop

I need help with this scenario where I need to find a string from a pagination table wherein each page contains 50 items. My code below works fine, only problem is that when it cannot find the data my while loop sometimes keep running indefinitely and does not fail but sometimes it does! What can I do so that it will always return an error after reaching a number of loops?
public int inboxLocateLoan(String expName, String name) throws Throwable {
//Locate Loan element in SharePoint table
report.setFailedResult("Loan element is not found");
int loanRow;
try {
boolean loansearch = true;
while (loansearch) {
List < WebElement > rowElem = getWebElements(getAEDriver(), "xpath", sRow);
for (int i = 1; i <= rowElem.size(); i++) {
String actualLoanName = driver.findElement(By.xpath("//*[#id='onetidDoclibViewTbl0']/tbody[2]/tr[" + i + "]/td[3]")).getText();
// String actualLoanNumber = driver.findElement(By.xpath("//*[#id='onetidDoclibViewTbl0']/tbody[2]/tr["+i+"]/td[5]")).getText();
loanRow = i;
if (actualLoanName.equals(expName)) {
loansearch = false;
return loanRow;
}
if (actualLoanName.equals(name)) {
click(getAEDriver(), "xpath", "//*[#class='ms-pivotControl-surfacedOpt-selected']", "Refresh");
loansearch = true;
} else {
if (i == 50) {
click(getAEDriver(), "xpath", "//*[#id='pagingWPQ2next']/a", "Next Page");
} else {
loansearch = true;
}
}
}
}
}
Initialize the romElem outside the for, and then use it to toggle your flag. If you reached your max rowElemen and you didn't find what you were looking for, it is safe then to assume that the value will be false.
Also, what is the purpose of the while? you could remove it completely, it is usually a bad idea to mix a while and a for. I don´t see the point in doing so in this case.

Insert Method in a BinarySearchTree

Hey i have written some kind of Binary Search Tree, which has a insert method.
So it gets a Object to insert, a Char Array and a Integer which gives it the Index to look at.
So this is the insert method :
public void insert(Buchstabe pBuchstabe,char[] pChar,int pStelle)
{
if(pBuchstabe==null)
return;
if(baum.isEmpty())
{
baum=new BinaryTree(pBuchstabe);
}
else
if(pStelle <= pChar.length)
{
if(pChar[pStelle] == '.')
{
Mybaum lTree=this.getLeftTree();
lTree.insert(pBuchstabe,pChar,pStelle+1);
this.baum.setLeftTree(lTree.baum);
}
else
if(pChar[pStelle]=='-')
{
Mybaum lTree=this.getRightTree();
lTree.insert(pBuchstabe,pChar,pStelle+1);
this.baum.setLeftTree(lTree.baum);
}
}
}
I have a Method which passes the required Parameters (in this case) : A Object Buchstabe,then the Char Array['.','.'] and the integer 0 to the insert method.
And i get a out of bounds error :
java.lang.ArrayIndexOutOfBoundsException: 2
at Mybaum.insert(Mybaum.java:22)
at Mybaum.insert(Mybaum.java:25)
at Mybaum.insert(Mybaum.java:25)
at Mörserbaum.einlesen(Mörserbaum.java:42)
Does anyone know what ive made wrong ?
Looks like you have an issue
if(baum.isEmpty())
{
baum=new BinaryTree(pBuchstabe);
}
else
**if(pStelle <= pChar.length)**
{
**if(pChar[pStelle] == '.')**
{
Mybaum lTree=this.getLeftTree();
lTree.insert(pBuchstabe,pChar,pStelle+1);
this.baum.setLeftTree(lTree.baum);
}
if(pChar[pStelle] == '.') -- you get indexOutOfBound bc/ you need to say
if(pChar[pStelle-1] == '.') .. since Java array index starts from 0, if the length is 5, last index would be pChar[4]...
there could be more issues with this code, since we don't have full code/context i can't speculate more.. but this is one of the reason you could get indexoutofbound
public void einlesen()
{
Buchstabeenschlange sch = new Buchstabeenschlange();
for(int i = 0;i<codeTabelle.length;i++)
{
Buchstabe a = new Buchstabe(alphabet[i],codeTabelle[i]);
if(a == null)
{
System.out.println("Buchstabe mit Error == "+a);
}
System.out.println("Buchstabe == "+a);
sch.hinzufuegen(a);
System.out.println("------------");
}
List l = sch.gibListe();
sch.druckeListe();
l.toFirst();
while(l.hasAccess())
{
Buchstabe buch = (Buchstabe) l.getObject();
char[] code = buch.getCode().toCharArray();
baum.insert(buch,code,0);
l.next();
}
TreeViewGUI view = new TreeViewGUI(baum);
}
This creates the object Buchstabe and sorts it in a List so that you have the shortest Strings at the beginning.
Then it inserts them into a Binaray Tree and displays it.

Return statement doesn't break out of block, even though condition is true

This is a simple program to check if a number if Fibonnacci. I have a mysterious bug: the "return true" statement isn't triggered. Instead, "hi" will be printed many times. Return should break out of the method, does anyone have insight as to why it's not? Thanks!
import java.util.*;
public class Solution {
public static boolean listFibs (long oldestFib, long oldFib, long input) {
long newFib = oldestFib + oldFib;
while (newFib < Math.pow(10,10)) {
if (newFib == input) {
System.out.println("hi");
return true;
}
listFibs(oldFib, newFib, input);
}
return false;
}
public static void main(String[] args) {
/*Scanner in = new Scanner(System.in);
int testCases = in.nextInt();
for (int i = 0; i < testCases; i++) {
int a = in.nextInt();
System.out.println("A= " + a);
System.out.println(listFibs(0, 1, a));
}*/
System.out.println(listFibs(0, 1, 5));
}
}
Due to the recursion there are many incarnations of listFibs. The return just leaves one of them.
In the example given, you get the following calls:
listFib(0,1,5)
listFib(1,1,5)
listFib(1,2,5)
listFib(2,3,5)
-> true
listFib(2,3,5) // called again due to the loop
-> true
listFib(2,3,5) // called again due to the loop
-> true
listFib(2,3,5) // called again due to the loop
-> true
listFib(2,3,5) // called again due to the loop
...
actually, if "hi" is printed many times, the return statement must be executed the same time. if you install a break point in that return statement, you will see.
your function is a recursion, and "listFibs" will be called many times.
Print values of all 3 variables in the method and you will know what's wrong. You are using recursion, see how many times it's being called.
Also, after call to listFib, execution will go to while loop again. You need to say return listFibs at least. Between your listFibs and while loop condition, nothing is changing. 2,3,5 are being found again and again.
see http://ideone.com/1d440f
You are one step short... The recursive call doesn't do anything with the results you get from listFibs, so the program sees something like this:
while (newFib < Math.pow(10,10)) {
if (newFib == input) {
System.out.println("hi");
return true;
}
true //or false
}
Try adding this extra little IF statement. Once a true result is found it will be passed back up the chain and out of the function.
while (newFib < Math.pow(10,10)) {
if (newFib == input) {
System.out.println("hi");
return true;
}
if listFibs(oldFib, newFib, input){
return true;
}
}

java.util.NoSuchElementException using iterator in java

I'm trying to iterate through a list using the iterator over my list of Logs. The goal is to search for a logs which contains the same phonenumber, type and date as the new log
However, I get a java.util.NoSuchElementException in my conditional statement. Does anyone know what might cause the problem?
My code
public void addLog(String phonenumber, String type, long date, int incoming, int outgoing)
{
//Check if log exists or else create it.
Log newLog = new Log(phonenumber, type, date, incoming, outgoing);
//Log exists
Boolean notExist = false;
//Iterator loop
Iterator<Log> iterator = logs.iterator();
while (iterator.hasNext())
{
//This is where get the exception
if (iterator.next().getPhonenumber() == phonenumber && iterator.next().getType() == type && iterator.next().getDate() == date)
{
updateLog(newLog, iterator.next().getId());
}
else
{
notExist = true;
}
}
if (notExist)
{
logs.add(newLog);
}
}
You are calling next() a bunch of times in one iteration forcing the Iterator to move to an element that doesn't exist.
Instead of
if (iterator.next().getPhonenumber() == phonenumber && iterator.next().getType() == type && iterator.next().getDate() == date)
{
updateLog(newLog, iterator.next().getId());
...
Use
Log log = iterator.next();
if (log.getPhonenumber() == phonenumber && log.getType() == type && log.getDate() == date)
{
updateLog(newLog, log .getId());
...
Every time you call Iterator#next(), it moves the underlying cursor forward.

Sorting method not sorting correctly

I'm calling Arrays.sort(schedule, c); where c is an instance of a comparator like so:
import java.util.Comparator;
public class FirstOccComparator implements Comparator<AbstractEvent> {
public int compare(AbstractEvent event1, AbstractEvent event2) {
int result = 0;
if (event1 == null || event2 == null) {
//System.out.println("null");
}
else if (event1.hasMoreOccurrences() && event2.hasMoreOccurrences()) {
result = event1.nextOccurrence().compareTo(event2.nextOccurrence());
}
return result;
}
}
The output I'm getting isn't what it's supposed to be. I'm wondering if someone can point me in the right direction here. This is the first sorting algorithm I've ever made and its using concepts that are still new to me (comparators and implementation), so sorry about the multiple questions regarding my code :)
EDIT
This is the difference between the outputs: http://pastebin.com/LWy1jqkt
There are two kinds of events, these are the hasMoreOccurrences() and nextOccurrence() methods:
DailyEvent
public boolean hasMoreOccurrences() {
boolean result = false;
Date check = nextOccurrence();
timesCalled--;
if (check instanceof Date && check != null) {
result = true;
}
return result;
}
public Date nextOccurrence() {
if (timesCalled > recurrences) {
return null;
}
else {
Calendar cal = Calendar.getInstance();
cal.setTime(startTime);
cal.add(Calendar.DATE, timesCalled);
timesCalled++;
return cal.getTime();
}
}
WeeklyEvent
public boolean hasMoreOccurrences() {
Date tmp = nextOccurrence();
timesCalled--;
boolean result = false;
if (tmp instanceof Date && tmp != null) {
result = true;
}
return result;
}
public Date nextOccurrence() {
Calendar cal = Calendar.getInstance();
cal.setTime(startTime);
cal.add(Calendar.DATE, timesCalled*7);
if (cal.getTime().compareTo(this.endTime) > 0) {
return null;
}
else {
timesCalled++;
return cal.getTime();
}
}
There are a few things that seem incorrect with your comparator.
For instance, what happens if only one of them is null? How do you want those to sort? Right now you are considering two events equal if one of them is null.
Also, what happens if one event has more occurences while the other does not? Right now you only do comparisons on occurrences if both events have more occurrences. You need to handle the case where one has occurences while the other does not.
Also, if the occurence is a custom class, you need to evaluate that comparator as well.
When behavior doesn't match your assumptions, perhaps it's time to check your assumptions.
"...isn't what it's supposed to be..." suggests that you've got a notion of how your Comparator is supposed to work that isn't matching the output. Since the sorting algorithm built into Collections is proven, I think you need to look at your class and its Comparator for the error.
Write some unit tests and see where you've gone wrong.
Without seeing the results and the class you're sorting, it's impossible to advise you on what to do next.
Ask yourself: what happens when event1 and event2 are not null but one (or both) has run out of occurrences?
Your algorithm for determining equality is deeply flawed. Read this for more details: http://blogs.msdn.com/b/oldnewthing/archive/2003/10/23/55408.aspx?wa=wsignin1.0

Categories

Resources