简体   繁体   中英

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?

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(); 
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM