質問

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(); 
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top