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.
Related
How to implement a filter which in case of null returns all the data?
For example if name is null it should be excluded from the filter.
The only way in my head is to make 100k lines of code and test all of the combinations. It is very stupid. I dont want it like this. I am sure there is better way.
Collection<Ojects> filter(String name, Integer age, Integer number) ;
NOTE: your line of code is not correct:
To call the filter method:
Collection<Ojects> ojects = filter(String name, Integer age, Integer number);
Also there are a lot of details missing in your question, but to use as a guide: check if all the conditions to filter are null and return all elements else do the filter:
public Collection<Ojects> filter(String name, Integer age, Integer number) {
// return all object if no filter
if (name == null && age == null && number == null) {
Collection<Ojects> allOjects = // get all objects from where you wish
return allOjects;
}
// do the filters
Collection<Ojects> filteredOjects = new ....
// filter by name
if (name != null && name.lenght > 0) {
// do the filter and put the matching ones in filtered objects
}
// filter by age
if (age != null && age < 0) {
// do the filter and put the matching ones in filtered objects
}
// filter by number
if (name != null // conditions you need) {
// do the filter and put the matching ones in filtered objects
}
return filteredObjects
}
If you don't filter when parameters are not given you will return all objects...
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.
I have a static method where I get a list of tweets and the name of a town as a parameter and I remove from the list whichever tweet did not originate from the town or the user that made it did not originate from the town.
Here is my code:
public static void removeIncorrectTowns(List<Status> tweets, final String town) {
if (town.isEmpty()) {
return;
}
Iterator<Status> it = tweets.iterator();
while (it.hasNext()) {
Status status = it.next();
if ((status.getPlace() == null && (status.getUser().getLocation() == null || !status.getUser().getLocation().equalsIgnoreCase(town)))
|| !status.getPlace().getName().equalsIgnoreCase(town)) {
it.remove();
}
}
}
The problem I have is that I got a NullPointerException at line 62 which is the line with it.remove().
How is it even possible for the iterator to be null? That alone makes no sense to me since the while loop checks if it.hasNext().
In the case that status.getPlace() is null and status.getUser().getLocation() is not null and does not equal town, you are going to get a NPE in the last part of the condition when status.getPlace().getName() is called.
i want to find a name in a recursivly build itemlist.
Items can have subitems which can have subsubitems etc.
For the first level it worked. for deeper levels the correctly found name/id mapping gets an overwrite from the stack. Because of the string result, i have to write the return statement at the end. So i have a mental blockage how i can solve this problem. I appreciate for your help.
public String getNameForID(List<Item> top, long id, String name ) {
for (Item i : top) {
if (i.getId() == id) {
name = i.getName();
return name;
}else{
this.getNameForID(i.getSubItemsList(), id,name);
}
}
return name;
}
This must be what you're looking for:
public String getNameById(List<Item> items, long id) {
// boundary condition
if (items == null || items.isEmpty()) {
return null;
}
// looping
for (Item item : items) {
// if current is
if (item.getId() == id) {
return item.getName();
}
// recursion
String name = getNameById(item.getSubItemsList(), id);
// if nested found
if (name != null) {
return name;
}
}
// boundary condition
return null;
}
Your recursive call to getNameForID must also be able to return a value. It also needs to be able to indicate that no value was found so that the recursion is terminated.
Based on #sp00m's previously deleted (and slightly incorrect) answer, try this:
public String getNameById(List<Item> items, long id) {
// sanity checking conditions to terminate recursion early
if (items == null || items.isEmpty()) {
return null;
}
// iterate over collection
for (Item item: items) {
if (item.getId() == id) {
return item.getName();
} else {
String name = getNameById(item.getSubItemsList(), id);
if (name != null) {
return name;
}
}
}
// final termination condition - entry wasn't in this list
return null;
}
you do not assign the value returned here to name:
this.getNameForID(i.getSubItemsList(), id,name);
actually you don't need the parameter name - just return name or null in each call
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.