Asking for a username from an array

Viewed 114

I need to create a project where only if a specific username is inputted from the given names in the array, they are allowed to continue to the next menu options. How can I change my code to do this? It is just printing Hello John! Do I need a loop?

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

    Scanner input = new Scanner (System.in); 
    
    System.out.println("please enter your username!");
    
    String[] username = { "John","Lucy", "Amy", "Noah", "Sam"}; 
    
    List<String> list = Arrays.asList(username); 
    if (list.contains("John")) {
        System.out.println("Hello!" );
    }
    else if (list.contains("Lucy")) {
        System.out.println("Hello!" );
    }
    else if (list.contains("Amy")) {
        System.out.println("Hello!" );
    }
    else if (list.contains("Noah")) {
        System.out.println("Hello" );
    }
    else if (list.contains("Sam")) {
        System.out.println("Hello" );
    }
    else { 
        System.out.println("Please enter a valid username.");
    }
}

returns:

Welcome, To start, please enter your username!

Hello John!

1 Answers

You effectivly need a loop to ask the user until the name is valid, a do/while loop is a good choice here

Scanner input = new Scanner(System.in);
List<String> allowedUsernames = Arrays.asList("John", "Lucy", "Amy", "Noah", "Sam");
System.out.println("Welcome, To start, please enter your username!");

String name = "";
do {
    if (!name.equals("")) {
        System.out.println("Please enter a valid username.");
    }
    name = input.nextLine();
} while (!allowedUsernames.contains(name));

System.out.println("Hello!");
Welcome, To start, please enter your username!
aa
Please enter a valid username.
uu
Please enter a valid username.
dd
Please enter a valid username.
John
Hello!
Related