我正在学习java,使用“Java how to program”这本书。我正在解决练习。在这个实际练习中,我应该创建一个从用户读取整数的程序。然后,程序应显示与用户读取的整数相对应的方形星号(*)。 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++;
}
}
}
答案 0 :(得分:5)
您应该在外循环的每次迭代中重新设置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++;
}
}
答案 1 :(得分:1)
count1
,例如
while (count2 <= numberOfSquares)
{
while (count1 <= numberOfSquares)
{
System.out.print("*");
count1++;
}
System.out.println();
count1 = 1; //set count1 back to 1
count2++;
}
答案 2 :(得分:1)
除非练习需要while循环,否则你真的应该使用for循环。它们实际上可以防止出现这样的错误,并且需要更少的代码。此外,在大多数编程语言中从零开始计数并使用<
而不是<=
来终止循环是惯用的:
for (int count2 = 0; count2 < numberOfSquares; ++count2)
{
for (int count1 = 0; count1 < numberOfSquares; ++count1)
System.out.print("*");
System.out.println();
}