在Java中使用方法突破循环

1 java methods loops continue break

我试图在用户退出程序中的while循环之前使用方法进行双重检查.

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

运行程序后,我收到错误break outside switch or loop,然后continue outside switch or loop.有没有办法在这里实现我的目标?

Arn*_*was 5

我想你是ays()在while循环中调用的.我们的返回类型ays()BE boolean,让它return无论是truefalse.ays()while循环内部调用,并根据ays()continuebreak循环返回的值调用.

while (true) { 
    //Do Something 
    if (ays()) { 
        continue(); 
    } else { 
        break(); 
    }
}
Run Code Online (Sandbox Code Playgroud)