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.
Related
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!");
}
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;
}
I have written this:
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();//declare your list
Scanner input = new Scanner(System.in);//create a scanner
System.out.println("How many participants? ");
int nbr = input.nextInt();//read the number of element
input.nextLine();
do {
System.out.println("What is the name of the people?");
list.add(input.nextLine());//read and insert into your list in one shot
nbr--;//decrement the index
} while (nbr > 0);//repeat until the index will be 0
System.out.println(list);//print your list
The output is:
Jack, Frank
What I want to do is changing the content of the linked list. For example I wrote 2 names Jack and Frank. Then I want to add Jack's surname so that linked list will be:
Jack Adam, Frank
What should I do?
What you need to do is use the set method updating the specific position that you want to update. In this case will be something like this:
list.set(0, list.get(0) + " Adam");
Notice that we are getting the content of the position 0 of the list and concatenating with the surname.
I wrote code to store the values of user-inputted dollar amounts. Whenever the program prompts the user, "would you like to input items - y/n?" the user can then put in values stored in an ArrayList.
The initial prompt is below. It seems to work as I am able to put in values with no visible errors.
System.out.print("Would you like to input item/s - y/n: ");
String response = textReader.nextLine();
System.out.println();
// create while loop to restrict responses to single characters
while ((!response.equalsIgnoreCase("y")) && (!response.equalsIgnoreCase("n")))
{
System.out.print("Sorry - we need a y/n: ");
response = textReader.nextLine();
System.out.println();
}
But when I go to put in values a second time, I notice the program doesn't clear out the values from my first entry. The code I wrote to prompt the user for another cluster of values is identical to the code I wrote for the initial prompt. I nested these second prompt in a while loop triggered by the user selecting "y" to the initial prompt.
while ((response.equalsIgnoreCase("y")))
{
System.out.print("Please enter an item price, or -1 to exit: $");
double values = numberReader.nextDouble();
while ((values > (-1)))
{
cartItems.add(values);
System.out.print("Please enter another item price, or -1 to exit: $");
values = numberReader.nextDouble();
}
System.out.println();
System.out.println("********** Here are your items **********");
// I omitted the code here to make this more concise.
// prompt the user to input a second round of values
System.out.print("Would you like to input item/s - y/n: ");
response = textReader.nextLine();
System.out.println();
// create while loop to restrict responses to single characters
while ((!response.equalsIgnoreCase("y")) && (!response.equalsIgnoreCase("n")))
{
System.out.print("Sorry - we need a y/n: ");
response = textReader.nextLine();
System.out.println();
}
}
My output is below. When I am prompted a second time, I select 'y' to add more items. However, my newly added item $3.00, gets added to the list from the first prompt. Is there anyway to refresh or erase the ArrayList so that it is brand new each time the user wants to input new values?
cartItems.clear();
put it at the end of the loop, after the results are printed to the console.
It will refresh the list and remove all the elements within it.
In no place you are resetting the ArrayList.
You can call cartItems.clear() when you are done with your processing and you are looping for a next round (at the bottom of the outter while).
...
while ((!response.equalsIgnoreCase("y")) && (!response.equalsIgnoreCase("n")))
{
System.out.print("Sorry - we need a y/n: ");
response = textReader.nextLine();
System.out.println();
}
cartItems.clear();
}
Create instance of list in the while loop
List<Double> cartList = new ArrayList<Double>();
So now everytime user selects yes, the program enters in the while loop and then a new instance of list is created without any values. If you want to store the values in the previous list, write it to a persistence storage like file or database before creating a new instance of list.
Alternatively, you can also use
cartList.clear();
But, i don't recommend doing so.It can give you junk values and takes more amount of time. The clear method basically iterates over all the elements of list and does them null like this.
for(int i = 0; i < cartList.size(); i++){
cartList.get(i) = null;
}
I'm trying to get it where the user inputs a 1 or 2 for a predetermined values. Then using that to calculate a final cost.
Example:
Would you like the red or orange box? 1 for red, 2 for orange
The red would cost $10 and the orange $12.
How do I connect the inputs 1 and 2 to $10 and $12? Do I use switch or if?
Both options work. I personally prefer using the switch statement as it makes the code a bit more readable.
import java.util.Scanner;
public class Untitled {
public static void main (String[]args) {
Scanner s = new Scanner(System.in);
// this is where you store your items - you would obviously have to create the class and its methods first
// ArrayList <Item> items = new ArrayList<>;
// items.Add(new Item(SomePrice, SomeName);
System.out.println("Item 1 or 2");
String input = s.nextLine();
// Option 1
switch(input) {
case ("1"): {
System.out.println("Cost is 1");
// some method to retreive an item from the list of Items carrying the name one
// get user Input
// update the item in the list
break;
}
case ("2"):{
System.out.println("Cost is 2");
break;
}
}
// Option 2
if (input.equalsIgnoreCase("1"))
System.out.println("Cost is 1");
else if (input.equalsIgnoreCase("2"))
System.out.println("Cost is 2");
}
}