This question already exists:
How to selected items in a listbox Java Netbeans [closed]
Closed 2 years ago.
Morning all,
I am currently working on a project that involves selected an item from a list box.
The format I am following for the items in the list box is as follows:
(airline name)#(maximum weight)kgs.
My first issue comes with trying to get the item from the list box. I have tried multiple things such as list.getSelectedIndex(); and using a for loop to run through the indexes to try and compare "i" to one of the Airline names but to no avail.
Secondly, do you guys have any suggestions on how I would extract the maximum weight section from my String(SAA#25kgs). My String Handling/Manipulation isn't that great and I would appreciate any suggestions. My first thought was to use .split(), but then I would get the 25kgs as well.
The list box I am using looks like this:
https://gyazo.com/328ddeb9b7888821cfe74fecb551dd08
Kind regards IzzVoid,
To get the selected value from the JList you would do something like this:
String stringItem = jList1.getSelectedValue().trim();
To get the weight from the selected list item:
// Is something in JList selected.
if (jList1.getSelectedIndex() != -1) {
// Yes...Get the selected item from JList.
String stringItem = jList1.getSelectedValue().trim();
System.out.println("Selected List Item: " + stringItem); //Display it.
// Split the JList item based on the Hash character into a String Array.
String[] itemParts = stringItem.split("#");
// Are there two elements within the Array?
if (itemParts.length > 1) {
// Yes...Then the 2nd element must be the weight
String item = itemParts[0]; // Get ite related to weight
System.out.println("Item: " + item); // Display item
String stringWeight = itemParts[1]; // get weight related to item
System.out.println("Weight: " + stringWeight); // Display weight
// Convert weight String to double data type...
// Remove everything not a digit and convert to double.
double weight = Double.valueOf(stringWeight.replaceAll("[^\\d]", ""));
System.out.println("Weight (as double type): " + weight); // Display weight
}
else {
// No...there is only a single element - Assume No Weight is available!
System.out.println("No Weight Available!");
}
}
// No...Nothing appears to be selected in JList.
else {
System.out.println("Nothing selected!");
}
Related
For my coding class I have to build a shopping list by having the user enter the number of items they need and then each item (one at a time). I then have to output the final shopping list in a multi-line dialogue box (one item per line). I have the first two parts done where users enter the number of items and what items they would like, but can't figure out how to output all the items. Any help would be great, thanks! Also, I am using jgrasp and we don't use println to output messages.
I've tried Output.showMessage("Shopping list \n" + items); and
Output.showMessage(items.toString());
public class ShoppingList
{
public static void main (String [] args)
{
String items;
int numItems, count;
numItems = Input.readInt("Enter number of items: ");
count = 0;
while (count < numItems)
{
items = Input.readString("Enter item: ");
count = count + 1;
}//end while
Output.showMessage(items.toString());
} //end main
} //end ShoppingList
The output should show a list of user entered items like:
Shopping List:
Bananas
Milk
Items cannot be of string type because whenever the line
items = Input.readString("Enter item: ");
is executed, the previous value of items is overwritten.
If you are allowed to for your homework, it's ideal to make items an array otherwise you would have to change the previous statement to
items += Input.readString("Enter item: ");
items += '\n';
Note:items here is one long String.
I want to delete specified data in an arraylist from another class based on what the user input
so when the user input Rice, the data with 'Rice' in it will be deleted
this is the code so far
the data is stored in ArrayList rm in a subclass named RegularMenu.
ArrayList<RegularMenu> rm = new ArrayList<RegularMenu>();
Quiz1(){
int input;
do{
System.out.println("1. Add Regular Menu");
System.out.println("2. Add Special Menu");
System.out.println("3. Show All Menu");
System.out.println("4. Delete Regular Menu");
System.out.println("5. Delete Special Menu");
System.out.println("6. Exit" + "\n");
System.out.print("Choice [1-6] ");
Scanner s = new Scanner(System.in);
input = s.nextInt();
if (input == 1 ){
String code, name;
int price;
System.out.println("Add Regular Menu");
System.out.print("Input Menu Code [R...]: ");
s.nextLine();
code = s.nextLine();
System.out.print("Input Menu Name [5-20]: ");
name = s.nextLine();
System.out.print("Input Menu Price [10000-130000]: ");
price = s.nextInt();
rm.add(new RegularMenu(code, name, price));
}
else if (input == 2){
}
else if (input == 3){
}
else if (input == 4){
System.out.println("Input menu code you want to delete");
String a = s.nextLine();
for(int i=0;i<rm.size();i++){
if(a == rm.get(i).getCode()){
String code = rm.get(i).getCode();
a = code;
rm.remove(a);
}
}
}
else if (input == 5){
}
}while(input != 6);
}
i can add the data, but when try to remove it, the error occurred.
Let me know if I'm not clear enough.
The problem is that you are using List.remove(Object) wrong instead of List.remove(int).
List.remove(Object)
boolean remove(Object o)
Removes the first occurrence of the specified element from this list, if it is present (optional operation). [...] More formally, removes the element with the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))) [...]
Trying to remove a RegularMenu with a String instance won't work because a String instance can't compare itself with a RegularMenu, so it will never be equivalent. (It will use String.equals(RegularMenu) method to find where is the instance to remove.
If you want to use List.remove(Object), pass the instance itself :
rm.remove(rm.get(i));
Note:
that this will remove the first occurrence only, so if you have two "equivalent" instances, only the first one will be removed.
List.remove(Object) will search for the index where the instance passed is using Object.equals to remove by index. But in your case you already did the job with if(a == rm.get(i).getCode()) (incorrectly, see "String comparison"),
List.remove(int)
E remove(int index)
Removes the element at the specified position in this list (optional operation). Shifts any subsequent elements to the left (subtracts one from their indices) [...]
Since you know the index, you can use rm.remove(i) (List.remove(int)) to remove the value at the current index.
Careful with the index that way, the right part of the list with shift on the left. See Lajos Arpad's answer for more information
Iterator
Another solution to remove items from an ArrayList is to use the iterator. You get the Iterator and iterate every items in it. Then if one match you call Iterator.remove to remove properly the item. You can even stop the loop if you only want to remove one item
Sample data :
List<String> datas = new ArrayList<>();
datas.add("foo");
datas.add("bar");
datas.add("bar");
datas.add("foo");
datas.add("bar");
datas.add("bar");
Code :
Iterator<String> it = datas.iterator();
String s;
while(it.hasNext()){
s = it.next();
if("foo".equals(s)){
it.remove();
}
}
System.out.println(datas);
[bar, bar, bar, bar]
I precise using ArrayList because some Collection don't implements the method remove for the Iterator giving an Exception.
Predicate - removeIf
Since Java 8, Collection.removeIf exists and allows you to do a quicker solution (using the same sample data) :
final String a = "foo";
datas.removeIf(s -> a.equals(s));
System.out.println(datas);
[bar, bar, bar, bar]
It will iterate and check for each instance of RegularMenu in it if the Predicate passed will be true, if so, the item will be removed.
String comparison
Also, note the comparison "foo".equals(s) instead of "foo" == s.
More information in How do I compare strings in Java?
You can iterate your array list with a loop and remove all matches:
for (int i = 0; i < yourArrayList.size(); i ++) {
if(a.equals(rm.get(i).getCode())){
yourArrayList.remove(i--);
}
}
Your mistake was that you tried to remove a from the ArrayList using remove, but remove expects an int, representing the index to be removed. In my code notice that I am decrementing i after removing to be able to remove consequent matches.
You can remove elements from List by index
for(int i=rm.size()-1; i>=0; i--) {
// you are deleting elements from the list while iterating,
// thus it is better to iterate backwards (rm.size()..0):
if(a.trim().equals(rm.get(i).getCode().trim())) {
rm.remove(i);
}
}
Note: when you delete an element under index i, all elements to the right (i+1, ...) will be moved to the left for one position.
Thus, when iterating from left to right and deleting elements, you will be messing with indices.
On the other hand, when you are iterating from right to left and deleting something at position i, all elements to to right will still be moved one position to the left, but It does not matter for you, because you will not iterate on them.
aaaaBcccc -> aaaacccc
^ ^ ^ ^
0.. i 0.. i
for(int i=0;i<rm.size();i++) {
if(a.trim().equals(rm.get(i).getCode())) {
rm.remove(i);
break;
}
}
In the list, you can remove elements by using index.
Find below code :
for(RegularMenu regularMenu:rm){
if(a.equalsIgnoreCase(regularMenu.getCode())){
rm.remove(regularMenu);
break;
}
So I've been working on this project PhoneBook.java program for awhile. The program opens up a .txt file and imports it into a List sorted by Lastname, Firstname. I am attempting to write a search function that opens a window, asks you to input a name, then upon clicking ok it should select the searched index. I can not understand why my following code for the searchMI is not working. I appreciate any help you can give me.
public class PhoneBook extends Frame implements ActionListener, ItemListener {
MenuItem newMI, openMI, saveMI, saveAsMI, exitMI;
MenuItem searchMI, deleteMI, updateMI, newEntryMI, sortMI;
String fileName;
List nameList;
List numberList;
TextField lastName, firstName, phoneNumber;
// implementing ActionListener
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if(source == newMI)
{
nameList.removeAll();
numberList.removeAll();
fileName = null;
display(-1);
setTitle("White Pages")
}
else if(source == searchMI)
{
String searchName = JOptionPane.showInputDialog(this,
"Please enter a name (last first) to search:");
System.out.println("Name to search: " + searchName);
int index = nameList.getSelectedIndex();
String name = lastName.getText().trim() + " " + firstName.getText().trim();
for(int i=0; i!=index; i++){
if(nameList.equals(searchName)){
nameList.select(index);
}
else
{
System.out.println("Error searching for the name: " + searchName);
}
...
Suggestions
Why this: int index = nameList.getSelectedIndex();? It does not look as if the selected index will give you any useful information here.
This will never work: if(nameList.equals(searchName)){. A List cannot equal a String.
Instead use your for loop, loop through whatever collection holds the Strings, I'm guessing it's the nameList and compare the String held at each item with the entered String.
The for loop should go from i = 0 to i < nameList.getItemCount() (or nameList.size() if it is a java.util.List).
Don't have that else block, else{ System.out.println("Error searching for the name: "... inside of the for loop. Doing that will print out the else Statement many times.
You're better off using the Swing library components not AWT.
You'll want to format your posted code better. Each statement should have its own line. Careful and regular indentations matter.
Since you are using components in your GUI, you may not need that JOptionPane. Could you instead get the search String from one of your text fields?
Hi I'm trying to create a contacts list I have an array of contacts and I'm looping through each one and getting the first character of the last name. I'm then trying to create an array with the value of that character and add it to my final array. Then I want to check if the array already exists in my final array. If it doesn't add it to the array.
The aim being so I end up with an array list of arrays that are going to be headers in a list view. Does anyone know how to create an empty array and name it the value of a string (I'm going to add stuff to this array later)? and then add that to an array list?
Here is what I have tried so far but I'm struggling to get my head round it
for (int i=0; i<contactsJSONArray.length(); i++) {
singleContactDict = contactsJSONArray.getJSONObject(i);
Log.v("Main", "Contact singleContactDict " + i +"= " + singleContactDict);
String firstname = singleContactDict.getString("first_name");
String lastname = singleContactDict.getString("last_name");
char firstLetterInLastname = lastname.charAt(0);
Log.v("Main", "firstLetterInLastname = " + firstLetterInLastname);
headerWithLetterArray.add((firstLetterInLastname).toArray);
}
array is something like [a,b,c,d], they don't have names. If you mean JSONArray and you want to store everything is JSONObcject try:
parentJson.put(lastname.substring(0,1), new JSONArray());
You can try using "Map" for the final collection. Where your first character of the last name can be a key in the map and the real name will become value (value internally can be a arraylist).
When you want to add a new contact to list, you can first look for the key in the map with the first letter. If it is then get the value which is arraylist and add the new contact to that.
In this way you will have lots of arraylist marked by the single letter in map which can be used in loop to fill the list.
I have created a table and some buttons to remove/add rows.
Problem is, when I add a new row, I must insert a value in the field name which isn't already on that table. Let me explain.
Here is the default table:
Now imagine i remove Station 3:
If i add a new Station, I would want to add a new Station name Station 3 (which is missing on the list) but I am adding a new Station 5 (obviously as my code is not correct).
My code for the Add Button action event is as such:
private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
String s2 = "";
String s1 = "Station 1 Station 2 Station 3 Station 4 Station 5";
int tb1rows = jTable1.getRowCount();
if (tb1rows == 5) {
// ERROR - MAXIMUM STATION NUMBER
}
else {
for (int i=0; i<tb1rows;i++) {
s2.concat(jTable1.getValueAt(i,1).toString());
s2.concat(" ");
}
String[] s3=s2.split(" ");
for (int i=0;i<s3.length;i++) {
if (s1.contains(s3[i])) {
System.err.println("contains");
System.out.println(s3[i]);
}
}
model.insertRow(jTable1.getRowCount(),new Object[] {jTable1.getRowCount() + 1,"Station " + (jTable1.getRowCount()+1),10,false,0,Color.BLACK});
}
}
What's wrong with my logic? Is there a better way to handle the problem so that I can get the "Station x" that is missing in that column so that I can re-add it?
Thanks in advance for your answers.
As there is a space in "Station 1" split on space won't do. Instead using another separator like ";", better use a Set<String> values = new HashSet<String>().
So long as you have
"Station " + (jTable1.getRowCount()+1)
the new station is always going to be named "Station N + 1".
Assuming you fix the problem of splitting on a space described by another answer, your code should be something like
for (int i=0;i<s3.length;i++) {
if (s1.contains(s3[i])) {
System.err.println("contains");
System.out.println(s3[i]);
}
else {
model.insertRow(jTable1.getRowCount(),new Object[] {jTable1.getRowCount() + 1,"Station " + (i + 1) ,10,false,0,Color.BLACK});
}
}
instead of all that string manipulation, you could use set mainpulations:
HashSet<String> all = new HashSet<String>();
// then populate all with your 5 station strings (loop)
HashSet<String> have = new HashSet<String>();
// then populate all with the contents of your table (loop)
all.removeAll(have);
// all now contains the ones that weren't in the table.
if its ordered you can just find the first gap and insert there. so iterate over the rows and if nextrow.numberInIt > thisrow+1 you insert thisrow+1
Code should be something like this:
int nextNrToInsert;
for(int=0; i < tb1rows; i++){
thisrowNr = jTable1.getValueAt(i,1).toString();
NextrowNr = jTable1.getValueAt(i+1,1).toString();
if(nextrowNr > thisrowNr+1){
//found the gap
nextNrToInsert = thisrowNr+1;
break;
}
}
//change this to use nextNrToInsert
model.insertRow(jTable1.getRowCount(),new Object[] {jTable1.getRowCount() + 1,"Station " + (jTable1.getRowCount()+1),10,false,0,Color.BLACK});
This line is the issue
model.insertRow(jTable1.getRowCount(),new Object[] {jTable1.getRowCount() + 1,"Station " + (jTable1.getRowCount()+1),10,false,0,Color.BLACK});
You're always adding in the row with the rowCount() + 1. So even if you remove Station 3, there are 4 rows, and you're adding in row + 1.
This code has no effect:
for (int i=0; i<tb1rows;i++) {
s2.concat(jTable1.getValueAt(i,1).toString());
s2.concat(" ");
}
At loop exit, s2 will still be an empty string, so s3 will be an empty array.
But, the approach to concatenate strings and then split them is misguided, anyway. If all you need is find the lowest integer that, appended to "Station" will produce a unique string, the most natural approach is to make your own TableModel that uses a list of your own objects for each row's data. In that data you'll keep the integer itself, and not the entire string "Station n". Then it's going to be a trivial matter to find a hole in the list of integers.