There is a basket, there is an implementation of its viewing, there are all possible products, etc. Basket - ArrayList. Items are added to the basket when I want to add them, and hence the question - how to remove them from there?

public static void cart () { Scanner sc = new Scanner(System.in); for (int i = 0; i < cart.size(); i++) { System.out.println(cart.get(i)); } System.out.println("Enter 9 to remove products out of your cart."); int s = sc.nextInt(); do { cart.remove(s); } while (s<=11); } 

In this code, I tried to remove the goods in cart.remove (s) as many times as the user writes (s-number of times). But something is wrong. I tried and through for, also did not work. Help please who can, I will be very grateful. Please insert the code with the answer. Thank you in advance.

  • What is the magic number 11? - Olexiy Morenets pm

1 answer 1

Your code had a problem in that you delete the s-й element of the list an infinite number of times, because s does not change (the condition s <= 11 always true ), respectively, the do while will be executed either 1 time, or it will be executed an infinite number of times.

You can use Iterator to solve your problem.

 Scanner sc = new Scanner(System.in); int s = sc.nextInt(); Iterator iter = list.listIterator(); for (int i = 0; i < s; i++) { if (iter.hasNext()) { iter.next(); iter.remove(); } } 

In this code, exactly s elements will be removed from the ArrayList, which the user has entered. I advise you to familiarize yourself with iterators.