I wrote a program that has an arraylist of users so it should either create a new user and store the user's name in an arraylist or choose an existing user from an arraylist. The problem is, when I run the code I can choose an option but when I want to create a new user I cannot type anything. Why does that happen and how can I fix this?
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
public class Main {
private ArrayList<String> users;
public static void main(String[] args) {
Main m = new Main();
m.menu();
}
public void createNewUser(String name) {
users.add(name);
}
public boolean search(String username) {
if (users.contains(username))
return true;
else
return false;
}
public void displayUsers() {
Iterator<String> itr = users.iterator();
while (itr.hasNext()) {
String name = itr.next();
System.out.println(name);
}
}
public void menu() {
users = new ArrayList<String>();
int choice = 0;
String name;
Scanner input = new Scanner(System.in);
System.out.println("Choose an option:");
System.out.println("1- Create new user");
System.out.println("2- Select current user");
choice = input.nextInt();
if (choice == 1) {
System.out.println("Enter your name: ");
name = input.nextLine();
createNewUser(name);
displayUsers();
} else {
do {
displayUsers();
System.out.println("Enter your username: ");
name = input.nextLine();
if (search(name)) {
System.out.println("User found");
break;
}
else
System.out.println("This username does not exist.");
} while (!search(name));
}
}
}