繁体   English   中英

“同时循环”无法正常工作

[英]“While-loop” not working right

我正在学习Java,使用的是《 Java如何编程》一书。 我正在练习。 在这个实际的练习中,我应该编写一个程序来从用户读取一个整数。 然后,程序应显示与从用户读取的整数相对应的星号(*)的平方。 F.eks用户输入整数3,然后程序应显示:

***
***
***

我尝试将while语句嵌套在另一个语句中,第一个语句在一行上重复星号,另一个语句在适当的时间内重复一次。 不幸的是,我只能让程序显示一行。 谁能告诉我我做错了吗? 代码如下:

import java.util.Scanner;
public class Oppgave618 
{

    public static void main(String[] args) 
    {
    int numberOfSquares;
    Scanner input = new Scanner(System.in);
    System.out.print("Type number of asterixes to make the square: ");
    numberOfSquares = input.nextInt();

        int count1 = 1;
    int count2 = 1;

    while (count2 <= numberOfSquares)

        {
        while (count1 <= numberOfSquares)
            {
            System.out.print("*");
            count1++;
            }
        System.out.println();
        count2++;
        }

    }

}

您应该在外循环的每次迭代中将count1重新设置为

public static void main(String[] args)  {
    int numberOfSquares;
    Scanner input = new Scanner(System.in);
    System.out.print("Type number of asterixes to make the square: ");
    numberOfSquares = input.nextInt();
             //omitted declaration of count1 here
    int count2 = 1;
    while (count2 <= numberOfSquares) {
        int count1 = 1; //declaring and resetting count1 here
        while (count1 <= numberOfSquares) {
            System.out.print("*");
            count1++;
        }
        System.out.println();
        count2++;
    }
}

每次移至下一行时, count1需要重置,例如

while (count2 <= numberOfSquares)
{
    while (count1 <= numberOfSquares)
    {
        System.out.print("*");
        count1++;
    }
    System.out.println();
    count1 = 1; //set count1 back to 1
    count2++;
}

除非练习需要while循环,否则您确实应该使用for循环。 它们实际上将防止此类错误的发生,并且所需的代码更少。 而且,在大多数编程语言中,习惯用法是从零开始计数,并使用<而不是<=终止循环:

for (int count2 = 0; count2 < numberOfSquares; ++count2)
{
    for (int count1 = 0; count1 < numberOfSquares; ++count1)
        System.out.print("*");
    System.out.println();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM