In a piece of code I'm currently working on, I'm taking in an ArrayList of data to be added to an object, from a user. I'm checking each item in the ArrayList against the current list of that type of data for the object, in order to make sure it's not in the list already.
Is there a way to throw an exception for one item in the passed- in list, to tell the user it's in the list already- and then to keep going and add the next items in the passed-in list to my current list if they aren't there already?
Update: i solved the problem by surrounding that block of code with a try/catch. Here's my code to clarify:
public void addCategories(ArrayList<BookCategory>categories) {
boolean exists;
for(int index = 0; index <categories.size(); index++) {//iterate through passed array list
try {
//for each element, check if it exists in the current category list.
exists = checkBookCategory(categories.get(index));
if (exists == false)
{subjectCategories.add(categories.get(index));}
else {
throw new IllegalArgumentException("Item " + categories.get(index) + " already in list."); }
}catch(IllegalArgumentException ie) {
System.out.println(ie);
} }
}
Thanks #JimGarrison!
The short answer is that yes, you can do this, but it usually is highly discouraged.
Some sample pseudocode:
for (Item i : inputList)
{
try
{
myObject.addItem(i);
}
catch (MyCustomDuplicateItemException ex)
{
// Tell the user there was a duplicate
}
}
However, this is using exceptions for what should be flow control. Ideally you would write the addItem() method to return a boolean value (i.e. true) if the item was successfully added, and the other value (false) if the item was a duplicate and NOT throw an exception.
Related
I'm a newbie of Java. I have a problem with object ArrayList that cannot iterate until the end when it doesn't catch up with If condition. In this code, if I input the second movie name and check for 'If condition', this condition doesn't iterate till the end. Seems like 'If condition' works for the first object value of ArrayList. Please someone points out to me what's wrong with this. Thanks in advances!
Here is the code:
boolean isFound=false;
for (Movies item: movie_list) {
if(item!=null && item.getMovie_name().contains(movie_name)) {
System.out.println("Movie exist");
isFound=true;
break;
}
}
if (!isFound) {
System.out.println("Movie doesn't exist!");
}
}
So am doing a mail server kind of program for my java course, (I would call myself a beginner in Java) and while I have completed all the required parts, there are some problems with the program that while the assignment doesn't require it, I would like to know why this is behaving the way and how to fix it. So to summarize it I have two methods that check how many mail items a specific user has and another one that returns the mail item that is first in the users mailbox, (by LIFO rule).
So while if a user both A.Has a mailbox and B.Has at least 1 mail in said mailbox there isn't a problem, this doesn't really work when a and/or b isn't true. And that is what I tried to fix. I thought it would be as simple as checking both if the mailbox.containsKey(who)==false and/or mailbox.get(who).get(0) == null would be enough but when I do this i get java.lang.IndexOutOfBoundsException: Index: 0, Size: 0.
I've tried multiple types of either checking if it's ==true/false null etc.. I've tried to just throw the exception all together but nothing seems to work and while maybe throwing the exception could work in some way I would want to solve it in another way as the throw command seems a bit lazy
Here is my method in which I check both A and B:
private boolean errorHandling(String who){
if (mailbox.containsKey(who)==false || mailbox.get(who).get(0) == null ){
return true;
}
else{
return false;
}
}
and this method is utilized by these two methods:
public MailItem getNextMailItem(String who)
{
if (!errorHandling(who) ){
MailItem item2 = mailbox.get(who).get(0);
mailbox.get(who).remove(0);
return item2;
} else{
System.out.println("that user dosent have a mailbox");
return null;
}
}
public int howManyMailItems(String who)
{
if (!errorHandling(who) ){ //To check if user has a mailbox
return mailbox.get(who).size();
}
else{
System.out.println("that user dosent have a mailbox");
return 0;
}
}
I am not sure if you need more of my code to help me or not. Tell me if that is the case but to clarify, the "mailbox" is the hashmap and the who parameter is the person you want to check his or her mailbox. Thank you.
There are couple of problems in our code which i listed below
First Problem
The if condition is wrong and which will be true even if map doesn't contain key
if (mailbox.containsKey(who)==false || mailbox.get(who).get(0) == null)
// mailbox.containsKey(who) will return false if map doesn't contain key
// then false==false ---> always true
So you are returning true even key is not present in map, And there is not necessity of errorHandling method. you can just use containsKey
if (containsKey(who) ){ // if key exists then proceed
MailItem item2 = mailbox.get(who).get(0);
mailbox.get(who).remove(0);
return item2; }
else{ // else don't proceed
System.out.println("that user dosent have a mailbox");
return null;
}
You can even avoid this `if condition by using getOrDefault
default V getOrDefault(Object key, V defaultValue)
Second Problem
Second part of if condition is wrong mailbox.get(who).get(0) == null you might have empty list for that key, so you can refactor your code as below
List<MailItem> listItem = mailbox.get(who, new ArraysList<>()); //get list if key exists or else get empty list
if(!listItems.isEmpty()) {
return listItems.remove(0); //if list has items delete at index 0
}
else{
System.out.println("that user dosent have a mailbox");
return null;
}
I have class called Modul and am adding elements of them to my LinkedList. Now I want to write a method where I input an Integer and check if there is an element at that index of the list or if it is empty. if there is a element i will return it and if not i want to return null and an error message.
I have thought of using an if-statement, but ultimately can't think of a method that checks whether or not an element is present. Now I thought of using try-catch but I don't know what kind of error I would need to catch.
import java.util.LinkedList;
public class Modulhandbuch {
private String nameStudienordnung;
private LinkedList<Modul> liste;
public Modulhandbuch(String nameStudienordnung) {
this.nameStudienordnung = nameStudienordnung;
liste = new LinkedList<Modul>();
}
public void einfuegenModul(Modul m) {
liste.add(m);
}
public int anzahlModule() {
return liste.size();
}
public Modul ausgebenModul(int i) {
try {
return liste.get(i);
}catch() //I don't know what error i would need to catch
}
}
You get a null pointer exception if you give the method an integer value that is bigger than the size of the list, because this index does not exist, so you need to check that. The method below correctly handles that case.
public Modul ausgebenModul(int i) {
if (i >= anzahlModule)
return null;
else
return liste.get(i);
}
indexing a linked list is waste of memory it takes O(n) to get to that index in a linkedList if you insist on this then you can add a property to the Node int index and through the constructer Node() increase this and set that instance to that value now there are few little problems to this what happens when you remove a Node at the Start ? yeah big problem the whole list must be reindexed thats makes the process of remove from Start which is O(1) a O(n) operation
you can do a trick to index it or give an illusion of been indexed is just don't do it when you ask for list(6) the iterator counts 6 Nodes Starting with 0 and stop at that Node
I would truly appreciate if someone could help me to understand why my code won't work the way it should:
I'd like to catch the exception when the index being tested (in the main class) is out of bound from my ArrayList in the getter method.
It should behave like: if the index (testing using 8) is out of bound from the ArrayList (length of 5), then the program will not get any value and print out statement saying Will Skip, and keep moving to the next line. If the index is not out of bound, return the value from the ArrayList.
What I have below works only when there is a "return" value in the Catch(). I know it is because the getter is asking to return a double. But I don't know how to fix this to behave the way stated above. Thank you so much!
Main Driver class for testing:
TestValue object = new TestValue();
System.out.println("The value is " + object.getListValue(8));
...other methods like print values, set new values etc.
TestValue class:
public double getListValue(int index) {
try {
listValue.get(index);
while (index <0 || index >= listValue.size()) {
}
}
catch (IndexOutOfBoundsException e) {
System.out.println(e.getMessage());
System.out.println("Can't get value. Will skip this request. ");
return listValue.get(0); // I don't want to return any values
}
return listValue.get(index);
}
This is because the definition of your method was public double,
you have to return a double unless you throw an exception.
If you really don't want to return a value, you can return 0.0.
Really need help with this as a Patient is not getting set to replace the null. We have to create an arraylist of 50 nulls so the iterator goes through the list and if it finds a null it will set it to the patient. The problem is no patients are getting set to the null. We have to return the bed number at the end too.
protected int amountOfBeds = 50;
ArrayList<Patient> bedList = new ArrayList<Patient>(amountOfBeds);
public int admitPatient(Patient illPatient) {
int index = -1;
if(illPatient.getAge() > 0 && amountOfBeds > size()) {
//if it is null then set to patient
//if it not null then we assume its a patient so we skip
Iterator<Patient> itr = bedList.iterator();
try{
while(itr.hasNext()) {
int bedIndex = bedList.indexOf(itr.next());
if(bedList.get(bedIndex).equals(null)) {
bedList.set(bedIndex, illPatient);
index = bedIndex +1;
break;
}
}
}catch(NullPointerException e) {
e.getMessage();
}
}
return index;
}
Simple way to create 50 nulls list is this
List<Patient> list = Collections.nCopies(50, null);
quick way to find index of null is this
int i = list.indexOf(null);
In Java, an ArrayList is basically an array, that can change its size during execution time. Since you seem to have a fixed amound of beds, an array would probably be better here.
The constructor new ArrayList(50) doesn't create an ArrayList with 50 elements. It creates an empty ArrayList, but gives Java the "hint, that there will probably be inserted 50 elements into the ArrayList. If you don't give such a hint, the ArrayList starts with little space and is periodically made bigger, if it gets too small too accomodate all items you want to insert. This takes time, so if you already know how many items you will insert (even if you only know it approximately) this constructor makes your code faster.
However, you have to think if you really need to do this the way you just wanted to do. Whouldn't it be easier, to just have an empty ArrayList, to which you can add or delete elements just as you want to (without a complicated logic, which replaces null with an element. You could then just add if (array.size() >= 50) // it is full, so some special case may be needed here to make sure there are never more elements in the array than you want.