user2480737
user2480737

Reputation: 13

Breaking Out Of A Loop Using A Method In Java

I am trying to use a method to double check before a user exits a while loop in my program.

private static Scanner input = new Scanner(System.in);

public static void ays() {
    System.out.println("Are you sure?");
    String ays = input.nextLine();
    if (ays.equals("Yes")) {
       break; 
    } else {
       continue;
    }
}

Upon running the program, I get the error break outside switch or loop, and continue outside switch or loop. Is there any way to achieve my goal here?

Upvotes: 1

Views: 5427

Answers (1)

Arnab Biswas
Arnab Biswas

Reputation: 4605

I guess you are invoking ays() inside a while loop. Let the return type of ays() be boolean and let it return either true or false. Invoke ays() from inside the while loop and based on the value returned by ays(), you continue or break out of the loop.

while (true) { 
    //Do Something 
    if (ays()) { 
        continue(); 
    } else { 
        break(); 
    }
}

Upvotes: 5

Related Questions