Java do-while loop isn't working

后端 未结 3 1227
一个人的身影
一个人的身影 2021-01-26 02:31

I want my program to keep asking the question until it gets a response it can use, specifically a number from 0 to 20. I have a lot of other stuff on this class, so here is a sm

3条回答
  •  野的像风
    2021-01-26 03:08

    You are using an assignment in your while expression:

    while(work = false);
    

    You can replace with

    while(work == false);
    

    or better

    while(!work);
    

    If variables halp and work are not used anywhere else, they could be eliminated giving you:

    do {
       System.out.println("What level is your fort?");
       Scanner sc = new Scanner(System.in);
       try {
        fortLevel = Integer.parseInt(sc.nextLine());
       } catch (NumberFormatException e) {
         System.out.println("Numbers only, 0-20");
       }
    
    } while (fortLevel < 0 || fortLevel > 20);
    

提交回复
热议问题