无限循环

Infinite do while loop

出于某种原因,尽管用户专门指定了扫描仪读取的值,但我的循环永远不会结束。当用户键入 0 时,它会继续

public static void InseretToDB() throws IOException {
    IO init = new IO();
    Scanner scan = init.getScanner();
    BufferedWriter bWriter = init.getWriter();
    int j;

    do {
        System.out.println("Name");
        String name = scan.nextLine();
        bWriter.write(name);
        bWriter.write("      ");
        System.out.println("Ocuppation");
        String occupation = scan.nextLine();
        bWriter.write(occupation);
        bWriter.newLine();
        System.out.println(" Input 1 to continue, 0 to end");
        j = (int) Integer.parseInt(scan.nextLine());
    } while (j != 0);

}

当我输入 0 时循环确实结束了,但我将程序更改为以下内容

Scanner scan = new Scanner(System.in);
BufferedWriter bWriter = new BufferedWriter(new OutputStreamWriter(System.out));

希望这对您有所帮助,

将扫描仪初始化为

 Scanner scan = new Scanner(System.in);

替换当前代码
j = (int) Integer.parseInt(scan.nextLine()); 

try{
    j = scan.nextInt();
}catch(Exception e){
   j = -1;
}