lundi 1 juin 2020

How to avoid double printed statements with an if statement in a while loop

I'm new to stackoverflow and wanted to know why my statement keeps on being repeated twice when i introduce an if statement in my while loop @ "if done, type "back"". Secondly, can someone tell me why the ArrayList keeps an empty String at index 0 when i only add one item to the ArrayList? Thanks!

Here is the code:

package com.codewithrichard;

import java.util.ArrayList; import java.util.Scanner;

public class Main {

public static void main(String[] args) {
 Scanner input = new Scanner(System.in);

 //global variables
  boolean appIsStillOn = true;


 ArrayList <String> shoppingList = new ArrayList<>();

 System.out.println("Welcome to your mobile shopping list" + "\n" + "Your options are");
 System.out.println("1) add item to list");
 System.out.println("2) display list and amount of items in it");
 System.out.println("3) quit!");

 while (appIsStillOn) {
     System.out.println("Option (1-4): ");
     int option1 = input.nextInt();
     if (option1 == 1) {
         while (true) {
             System.out.println("item (if done, type \"back\"): ");
             String itemAdded = input.nextLine().toLowerCase();
             if (!itemAdded.equals("back")) {
                 shoppingList.add(itemAdded);
             } else {
                 break;
             }
         }
     }
     else if (option1 ==2){
         System.out.println(shoppingList);
         System.out.println("size of shopping list: "  + shoppingList.size());
     }
     else {
         System.out.println("Can't wait for you to come back!");
         appIsStillOn = false;
     }









 }










}

}

Aucun commentaire:

Enregistrer un commentaire