Java “While循环”工作不正常

Java “While循环”工作不正常,java,while-loop,Java,While Loop,我正在学习java,使用java如何编程这本书。我在做练习。在这个实际的练习中,我应该制作一个程序,从用户那里读取一个整数。然后,程序应显示一个与从用户处读取的整数相对应的星号*平方。F.eks用户输入整数3,然后程序应显示: *** *** *** 我试着在另一行中嵌套一个while语句,第一个语句在一行上重复星号,另一个语句重复正确的次数。不幸的是,我只能让程序显示一行。谁能告诉我我做错了什么吗? 代码如下: import java.util.Scanner; public class O

我正在学习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();
}