1

I need to write a program that continuously asked for the input from a user. However, when the user inputs "None", the program should stop asking for the input and print out everything that was input before "None" was input. (EXCLUDING "None").

I am using an array list. However, when I input "None" the program still asks for user input. Here is my code:

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

public class ShoppingList {

public static void main(String[] args) {

    List<String> Items = new ArrayList<String>();

    Scanner keyboard = new Scanner(System.in);
    System.out.println ("Enter name of item: ");

    String item;

    while(keyboard.hasNextLine()) {
        item = keyboard.nextLine();

        if (item != "None") {
            System.out.println("Item added: " + item);
            Items.add(item);
    }
      else
       break;
    }

    System.out.println("End of list");
    System.out.println();

    for (String i : Items) {
        System.out.println(i);
         }

    }

}
Noods
  • 445
  • 4
  • 13

2 Answers2

1

So you need to change :

if (item != "None")

To:

if (!item.equals("None"))

As for String you use equals() function. != wont work for this case.

ProGamer
  • 420
  • 5
  • 16
0

You could use this:

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

public class ShoppingList {
  public static void main(String[] args) {

  List<String> Items = new ArrayList<String>();

  Scanner keyboard = new Scanner(System.in);

  while (true) {
    System.out.print("Enter name of item: ");
    String item = keyboard.nextLine();

    if (!item.equalsIgnoreCase("none")) {
      Items.add(item);
      System.out.println("Item added: " + item);
    } else break;
  }

  System.out.println("End of list");
  System.out.println();

  for (String i : Items) {
  System.out.println(i);
  }
}
BeeTheKay
  • 319
  • 2
  • 15