Nabeinz kc
Nabeinz kc

Reputation: 29

Java Code Not reachable

Please have a look on my code its showing code not reachable.

private static void createUser() {
    HashMap<String, String> membership = new HashMap<String, String>();
    System.out.println("Enter the Name of the User: ");
    String nameOfUser=sc.next();
    System.out.println("Enter the Membership tier which you prefer");
    System.out.println("1. Member - 5 % discount \n 2. Bronze - 10 % discount \n 3. Silver - 15% discount \n "
            + "4. Gold - 20 % discount \n 5. Platinum - 25 % discount");
    String typeOfMembership = null;
    while(true){
        int memberChoice=sc.nextInt();
        switch(memberChoice){
            case 1:
                typeOfMembership="Member";
                membership.put(nameOfUser,typeOfMembership);
                break;
            case 2:
                typeOfMembership="Bronze";
                membership.put(nameOfUser,typeOfMembership);
                break;
            default:
                System.out.println("Please select one of the available Member Type.");
        }
    }
    for (Map.Entry<String, String> entry : membership.entrySet()) {
        System.out.println("Member Created Successfully with name "+entry.getKey()+" and "+entry.getValue()+" tier.");
    }
}

Its showing code unreachable from this line onwards

for (Map.Entry<String, String> entry : membership.entrySet()) {

Upvotes: 0

Views: 143

Answers (2)

Viktor Mellgren
Viktor Mellgren

Reputation: 4506

You have an infinite loop while(true) so you will never reach the for loop.

Note: the breaks you have will only break the switch.

Suggestion: One way to fix it is to exchange the hard coded true, to something like isMemberSelected that you set to false in the default case. You could probably also switch to a do-while-loop.

You could even break it out to a separate method memberships = createMembers();

Upvotes: 5

sticky_elbows
sticky_elbows

Reputation: 1514

I think you have an infinite loop at while(true) this will always evaluate to true hence the execution of the script will stay in the loop. Try a different loop guard which shouldn't always evaluate to true.

Upvotes: 0

Related Questions