1

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?

Jatin Sehgal
  • 956
  • 2
  • 17
  • 37
user2480737
  • 13
  • 1
  • 3
  • 1
    `break` can only be used inside a loop as it breaks the loop and comes directly to the first statement outside the loop. `continue` takes the control at the start of the loop again discarding all other statements below the `continue` statement. – Jatin Sehgal Jun 13 '13 at 04:09
  • break can be used to break out of switch statement http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html or a loop in java http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html You can refer to the posted oracle java tutorial links. – AurA Jun 13 '13 at 04:20

1 Answers1

5

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(); 
    }
}
Arnab Biswas
  • 4,495
  • 3
  • 42
  • 60