简体   繁体   中英

“While-loop” not working right

I am learning java, using the book "Java how to program". I am solving exercises. In this actual exercise I am supposed to make a program which reads an integer from the user. The program should then display a square of asterisks (*) corresponding to the integer read from the user. F.eks user inputs the integer 3, the program should then display:

***
***
***

I try to nest a while-statement inside another, the first one to repeat the asterisks on one line, the other one to repeat this the right amount of times. Unfortunately, I only get the program to display one line. Could anyone tell me what I am doing wrong please? The code is as follows:

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++;
        }

    }

}

You should reset count1 back in each iteration of the outer loop

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 needs to be reset every time you move to the next line, eg

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

Unless the exercise requires while-loops, you really should use for-loops. They will actually prevent such bugs from occurring, and require less code. Also, it is idiomatic in most programming languages to start counting from zero and use < rather than <= to terminate the loop:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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