有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java while循环在停止条件结束后不会打印文本

我刚开始学习Java,我被要求使用while来决定多少球员可以成为守门员。循环应该在用户输入0并打印出可以成为守门员的球员的计数后停止

public class Q3_201303719 {

    public static void main(String[] args) {
        Scanner input = new Scanner (System.in);
        int num; int count=0;

        System.out.println("Enter the players' numbers");
        num = input.nextInt();

        while ((num != 0) && (num < 31) && (num%2==0) || (num%3==0))    
            count++; 

        System.out.println(count+ " players can be goalkeepers.\n");
        // Above line should be printed once the user enter 0, but in my case it won't
        // print and keeps asking the user to enter a number.
    }
}

共 (2) 个答案

  1. # 1 楼答案

    如果你不能像Ubica建议的那样使用do-while-loop,那么你需要努力解决这个问题:

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int num=2;   // you need to initialize num with a value, that allows you to go inside the while loop at least once
        int count = 0;
    
        while((num != 0) && (num < 31) && (num % 2 == 0) || (num % 3 == 0)) {
            System.out.println("Enter the players' numbers");  
            num = input.nextInt();   // user input is here inside the loop
            count++;  // your count will count every valid input + the user input that ends the loop
        }
        count--;  // if your user entered 0 to exit the loop, count would have still incremented, so you need do subtract one again
        System.out.println(count + " players can be goalkeepers.\n");
    }
    

    正如我在代码中所评论的,首先用一个伪值初始化num,这允许您至少进入一次循环。然后倾听用户的输入并计算循环迭代次数。但由于循环将至少执行一次(即使用户可能会立即输入0以退出循环),因此您的计数将比实际有效输入数高出一次。所以你必须再从你的计数中减去1

    编辑 我忘了提一下:当用户进入0时,你的循环不会停止,因为

    (num % 3 == 0) // is true with num=0 
    

    因此,当用户输入0时,while条件的计算结果如下:

    while( false && true && true || true ) 
    while( false || true )
    while( true )  
    
  2. # 2 楼答案

    你的代码没有意义

    1. 1:While循环没有修改“num”值,导致 如果输入无限循环
    2. 2:代码应该做什么?很难从你的表演中分辨出来

    我认为放置while loop upper可以帮助您,但代码仍然没有多大意义

    public class Q3_201303719 {
    
        public static void main(String[] args) {
    
           int num = 0; int count=0;
    
           while((num != 0) && (num < 31)&& (num%2==0)|| (num%3==0)) {
    
              Scanner input = new Scanner (System.in);
    
              System.out.println("Enter the players' numbers");
              num = input.nextInt();
              count++; 
           }
    
           System.out.println(count+ " players can be goalkeepers.\n");
           // Above line should be printed once the user enter 0, but in my case it won't
           // print and keeps asking the user to enter a number.
        }    
    }
    

    编辑: 出现此问题是因为您没有遵循一条非常简单的规则:在编码之前思考。 在本练习中,您需要考虑代码应该做什么,然后为其编写代码。编码只是一种语言,如果你知道你想写什么,那就更容易了。在这里,你显然不知道自己想做什么,而且由于你是一个新的开发人员,你很可能会被绊倒