0

I'm learning Java and trying to make a small program.

I made a list and a while loop. Everytime the user inputs something it should save the input to the list. Only if the input is "0" then i want it to break the while loop and print out everything whats inside the list. So it has to keep asking the user for an input till he insert 0. At the moment i don't have a teacher. I'm doing this all on my own. Don't blame me for my bad writting skills...

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

public class demo {
    public static void main(String[] args) {
        while (true) {

            ArrayList nummer = new ArrayList(); // make new list

            Scanner input = new Scanner(System.in); // start scanner

            System.out.print("Voer uw naam in: ");

            String naam = input.nextLine(); // scanner waiting for input + enter
            if (naam == "0") {
                System.out.println("Wrong, exit!");
                input.close();
                 for (Object item : nummer) { // foreach-loop
                     System.out.print(item);
                     }
                break;
            } else { 
                nummer.add(naam);
                continue;
            }
        }
    }
}

Could someone take a look to it and tell me what's wrong with it?

Thanks!

Aldeguer
  • 821
  • 9
  • 32
J. Adam
  • 1,457
  • 3
  • 20
  • 38
  • 1
    First thing i see, is to avoid using == when comparing Strings, try to use .equals() method. Also what is the problem so far? What isn't working? – Kleo G Feb 13 '18 at 17:04
  • 2
    Don't recreate the `List` on every loop iteration... – Elliott Frisch Feb 13 '18 at 17:05
  • Shift this line "ArrayList nummer = new ArrayList()" to before start of while loop.. You're recreating the list within each loop – DriLLFreAK100 Feb 13 '18 at 17:06
  • `ArrayList nummer = new ArrayList();` is inside the loop so each iteration a new list is created. Move this outside the loop. Similar with `input` - no need to recreate the scanner each iteration of the loop. – Andrew S Feb 13 '18 at 17:06
  • Wow guys, my thank is big! tyvm!!! It works now smootly :D – J. Adam Feb 13 '18 at 17:24

0 Answers0