我正在学习java,使用"Java how to program"这本书.我正在解决练习.在这个实际练习中,我应该创建一个从用户读取整数的程序.然后,程序应显示与用户读取的整数相对应的方形星号(*).F.eks用户输入整数3,程序应该显示:
***
***
***
Run Code Online (Sandbox Code Playgroud)
我尝试在另一行中嵌入一个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++;
}
}
}
Run Code Online (Sandbox Code Playgroud)
您应该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++;
}
}
Run Code Online (Sandbox Code Playgroud)