How can I iterate through JComboBox and Validate items - java

i am trying to iterate through JComboBox items i.e its connected to Database, whenever I click it it fetches data from Database and updates it. But its adding duplicate values in such case. I am trying to validate it by iterating through each item once added to JComboBox, if the existing item is similar to item I am trying to add then it shall not add and jump to other statement.
However I am then getting Null pointer error, in order to avoid this error first time I added counter -1, but once items are added and want to update, it gives error.
My JComboBox code is given below:
comboBox.addMouseListener(
new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent ev) {
List<Guest> list = null;
list = database.readGuest();
int n = list.size();
if(n <= 0) {
JOptionPane.showMessageDialog(null, "No data found.");
}else {
for(int count = 0; count < n; count++) {
g = list.get(count);
String pass = g.getPassportNp();
//String s = (String) comboBox.getItemAt(count-1);
//for(int i = 0; i < n; ++i) {
if(comboBox.getItemCount() != 0) {
if(comboBox.getItemAt(count-1).equals(pass)) {
continue;
}else {
comboBox.addItem(pass);
}
}else {
comboBox.addItem(pass);
}
//}
}
}
}
});
any solution for this?

You are not iterating over the items in the combobox, but only comparing to the last item in it. Your basic design should be 2 nested for-loops, one for going over your database items and one for going over the combobox items to check if the current database item is already in there. (You may also use List.contains instead of an nested loop which is clearer and shorter).
Side note: registering a mouselistener on the combobox seems like a design smell for this type of work. Fetching items from a database is not something you want to do on the EDT, but rather in a background thread. Also, you don't know what happens first: opening/animating the combobox (done by Swing), or modifying its contents? It makes it hard to think about the control flow, yet another reason to take a different approach.

Here is the solution which I figured it out. I hope helps others.
I created a List, and then added all items to it then..
int size = pass.size();
if(comboBox.getItemCount() != 0) {
comboBox.removeAllItems();
for(int c = 0; c < size; ++c) {
comboBox.addItem(pass.get(c));
}
}else {
for(int c = 0; c < size; ++c) {
comboBox.addItem(pass.get(c));
}
}

Related

cannot figure out why this test is failing here in adding a item to ArrayList

method code here:
public boolean addItem(MediaItem item)
{
for (int count = 0; count < Library.size(); count++){
String callNum = Library.get(count).getCallNumber();
if(item.getCallNumber().compareToIgnoreCase(callNum) == 0)
{
while( item.getCopyNumber() < Library.get(count).getCopyNumber())
{
int copyNum = item.getCopyNumber();
copyNum++;
item.setCopyNumber(copyNum);
}
Library.add(item);
return true;
} else if (item.getCallNumber().compareToIgnoreCase(callNum) != 0)
{
item.setCopyNumber(1);
Library.add(item);
return true;
}
}
return false;
}
testCases:
public void testAddItem(){
AnytownLibrary newlib = new AnytownLibrary();
assertNotNull(newlib);
MediaItem newItem = new Book();
MediaItem nextItem = new Book();
assertNotNull(nextItem);
assertNotNull(newItem);
newItem.setCallNumber("1");
nextItem.setCallNumber("1");
newlib.addItem(newItem);
assertTrue(newlib.addItem(newItem));
newlib.addItem(nextItem);
assertTrue(newlib.addItem(nextItem));
}
I cannot figure out why this is failing it keep throwing a assertion error here, and its not telling me that its just the output is false so im unsure whats wrong
i have completely tested my get and set methods and they are correct;
and a version of this that just asserts that the (itemname) rather than call numbers return true passed previously, so I'm sure the answer is somewhere in the method itself
Your logic for adding an item to library is wrong. Adding the very first item will always fail, because the for loop with not execute as the size is zero. So nothing will happen. Since this fails all the subsequent addItem calls will also fail.
There are many what to do this, a simple way will be to check if size is zero and add to the list directly and return. Else use ur for loop.

Passing method of one class into another [duplicate]

This question already has answers here:
Passing a method from another class
(4 answers)
Closed 5 years ago.
My problem is that I need to getSymbol from Element class.
I would normally establish an object in PeriodicTable like this:
Element e = new Element();
then use e.getSymbol within method in order to use it for comparison.
So, in order to complete first task and print entire list of elements, I declared an array within PeriodicTable like this:
Element[] objects = new Element[ARRAY_SIZE];
I'm guessing I declared it correctly, as it does run entire list of elements.
Again, I am having problems getting getSymbol into my method in PeriodicTable.
Any helpful suggestions, please?
For this method, a user will input a symbol for an element. The method will search for the element and return its index (in the array). Then, it will use the index to display that single element and all of its other information, using the toString method from the Element class.
public int searchBySymbol(String sym)
{
int index = 0;
boolean found = false;
for (int i = 0; i < objects.length; i++)
{
objects[i] = objects.getSymbol;
}
while (index < objects.length && !found)
{
if (objects[index].equals(sym))
{
found = true;
}
else
{
index++;
}
}
if(found)
{
System.out.println("Found at position: " + index);
System.out.println(objects[index].toString());
}
else
{
System.out.println("Not found");
}
}
You definitely don't need two loops in there first of all, there are two solutions to this:
(Recommended) If searching Elements by symbol will be the your main way of looking up Elements, consider using a HashMap to contain the data rather than an Element array as HashMaps allow look up of objects by a key e.g. HashMap<String, Element>. Lookup the HashMap API or check this example: http://beginnersbook.com/2013/12/hashmap-in-java-with-example/
(Quick fix) Rather than using two loops to get the field and compare, in Java it is good practice to define accessor methods such as getSymbol() and return the field rather than directly accessing it. Using this method you can simplify your code into...
for (Element e : objects) {
if (e.getSymbol().equals(sym) {
return true;
}
}
//return false after the loop omits the need for an explicit boolean variable`
Edit: Usual for loop construct for index access. The index number is essentially tracked by the iterator variable int i so you do not need a separate variable to track it.
for (int i = 0; i < objects.length; i++) {
if (objects[i].getSymbol().equals(sym)) {
//print i to show index number
//print objects[i].toString();
return true;
}
}
//print not found...
return false;

Adding Element of an Object in an Array in an Array to a String Array

I have a method that is suppose to traverse 2 arrays of Ojbects, the first being Menu of size 50, which contains Recipes, which hold up to 10 elements called ingredients, which holds up to 3 elements each, but I am only looking for their names! I want to take the matching names of those Ingredient elements in the Recipes and add them to my String array and then return it, here is my code...
public class Recipe implements Cloneable
{
String Name;
final int INGREDIENT_ARRAY_MAX = 10;
Ingredient Ingredients[] = new Ingredient[INGREDIENT_ARRAY_MAX];
public class RecipeBook
{
final static int MENU_ARRAY_MAX = 50;
static Recipe Menu[] = new Recipe[MENU_ARRAY_MAX];
public static String[] getRecipesByIngredient(String ingredientName)
{
String[] targetRecipes = new String[MENU_ARRAY_MAX];
int counter = 0;
for (int j = 0; j < Menu.length; j++)
{
if (Menu[j] == null)
{
break;
}
else
{
for (int k = 0; k < Menu[j].Ingredients.length; k++)
{
System.out.println(Menu[j].Ingredients[k]);
if (Menu[j].Ingredients[k].getName().equals(ingredientName))
{
targetRecipes[counter] = Menu[j].getName();
counter++;
}
}
}
}
return targetRecipes;
}
}
}
Now I know it doesn't work and why, but the solution I am not sure about. At the moment I only have 3 Recipes and 3 Ingredients in each recipe! The stuff up top is just for reference, those are the object arrays of RecipeBook (Menu) and Recipes (Ingredients).
Now when ran this code gets me into a NullPointerException because tries testing nulls against Strings, but how could I make it check through the Recipe, if it doesn't find anything, it moves on to the next Recipe in Menu, if it does, it simply adds it but continues to check til finish. I tried adding "if" statements checking for nulls and not nulls but it becomes convoluted and it still doesn't get my program to return to checking the rest of the arrays. I know the first "if" can stay because, well if the spot i check in Menu is null, the rest of it must be null so there's no point in going farther. But how do I check the Ingredients array, find something, add it, and go back to sifting through the Menu for recipes with that ingredient? Is it possible to add an if inside the inner loop to check for null and if it is, just go back to the outer loop?
update if conditions as below
1st if condition :
if (Menu[j] == null || Menu[j].Ingredients == null || Menu[j].Ingredients.length ==0)
2nd if condition :
if (Menu[j].Ingredients[k] != null && ingredientName.equal(Menu[j].Ingredients[k].getName()))
please let me know if there any issues.
I don't know how you fill the recipe array but what i can say is that your code is missing a lot of null checks. I would go this way (code not compiled / tested):
public static String[] getRecipesByIngredient(String ingredientName) {
String[] targetRecipes = null;
// check input parameter ingredientName against null and do lookup only if it is not null
if(ingredientName != null) {
// init the result array and do look up
targetRecipes = new String[MENU_ARRAY_MAX];
for (int j = 0; j < Menu.length; j++) {
// you might run into NPE if Menu[j] or if the array of ingredients in Menu[j] (Menu[j].Ingredients) is null
if(Menu[j] != null && Menu[j].Ingredients != null) {
for (int k = 0; k < Menu[j].Ingredients.length; k++) {
// Menu[j].Ingredients[k] may also be null
// Menu[j].Ingredients[k].getName() may also be null but no need to check it since
// you call equals of the string object ingredientName witch you already checked
// and equals(null) is always false in that case
if (Menu[j].Ingredients[k] != null && ingredientName.equals(Menu[j].Ingredients[k].getName()) {
// here you might want to check Menu[j].getName() against null otherwise you'll have
// a null inside your result array (this is some like a land mine) unless you want
// to check against null while iterating over you result array
if(Menu[j].getName() != null) {
targetRecipes[counter++] = Menu[j].getName();
}
}
}
} // save the else...
}
} // else targetRecipes is still null, with witch you may want to say "no result found"
return targetRecipes;
}

Getting the index value of a row with a ComboBox

One of the rows in my table is a ComboBox. They have the choice between 'Yes', 'No', 'Both'
If they choose Both have to make some modifications to the data array that is building the table and refresh the table. It was suggested in a previous post to build my logic in the else statement for Both.
protected void setValue(Object element, Object value)
{
if((element instanceof AplotDatasetData) && (value instanceof Integer)) {
Integer choice = (Integer)value;
String option = ((AplotDatasetData)element).getMarkupValue();;
if(choice == 0) {
option = "No";
}
else if(choice == 1) {
option = "Yes";
}
else {
option = "Both";
abd.getIndexOfSelectedBoth(); <<<<<<<<<
}
((AplotDatasetData)element).setMarkupValue(option);
getViewer().update(element, null);
}
}
The code above is in class OptionEditingSupport.
The table is in class AplotBaseDailog.
So in the OptionEditingSupport class, I imported the AplotBaseDailog class and assigned it.
AplotBaseDialog abd;
Then I wrote a method in the AplotBaseDailog class to get the row index of the column they just changed to Both. I need the index value to get the data from the array.
public void getIndexOfSelectedBoth() {
int row = viewer.getTable().getSelectionIndex();
AplotDataModel.getInstance().rebuildDataArray(row);
updateTableViewer();
}
Then I am passing in the index of the row to a method in my dataModel class. It is in the dataModel class that has the data array.
I am guessing I am reinventing the wheel here. There has to be a better way to do this process. Right now with all my code in place, I am getting a Null Pointer Error at the line that calls AplotBaseDialog
else {
option = "Both";
abd.getIndexOfSelectedBoth(); <<<<----
}
Can you get the index in the OptionEditingSupport class?
So you want to find the index of the AplotDatasetData for which "both" was selected.
Your ModelProvider (APlotDataModel) contains a List with your data, right?
Each List implements the method indexOf(Object). So you can get the index of your current object by using this method.
AplotDatasetData selected = ...
int index = AplotDataModel.getInstance().getIndexOf(selected);
and within your model:
public int getIndexOf(APlotDatasetData object)
{
return LIST_HOLDING_YOUR_DATA.indexOf(object);
}

Android:What to use instead of cursor

In my application I use cursor to get information from SQLite data base like this:
Cursor contacts = dataBase.select("SELECT _idContact FROM Contacts");
if (contacts.getCount() > 0) {
if (IMLayout.getVisibility() == View.VISIBLE) {
int k = contacts.getCount();
for (int j = 0; j < k; j++) {
if (j == 0) {
contacts.moveToFirst();
} else {
contacts.moveToNext();
}
What I want is to optimize the "for" using Enhanced for loop. For that I have to use an array, or other, but not cursors because the cursors are not working for Enhanced for loop. How to convert the cursor into an arrayList?
The enhanced for-loop only works on collections, iterables and arrays, and Cursor is none of those things.
You'll just have to use the methods provided, as you currently do. Alternatively, you'll have to suck the contents of the cursor into a collection, but then you're just making more work for yourself.
You can greatly simplify this logic as follows:
Cursor contacts = dataBase.select("SELECT _idContact FROM Contacts");
while (contacts.moveToNext()) {
// do stuff with this database entry
}

Categories