我正在学习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++;
}
}
}发布于 2011-12-09 17:25:16
您应该在外部循环的每次迭代中重新设置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++;
}
}发布于 2011-12-09 17:28:28
每次移动到下一行时,count1都需要重置。
while (count2 <= numberOfSquares)
{
while (count1 <= numberOfSquares)
{
System.out.print("*");
count1++;
}
System.out.println();
count1 = 1; //set count1 back to 1
count2++;
}发布于 2011-12-09 17:29:47
除非练习需要while-loops,否则您确实应该使用for-loops。它们实际上可以防止此类错误的发生,并且需要的代码更少。此外,在大多数编程语言中,从零开始计数并使用<而不是<=来结束循环也是惯用的做法:
for (int count2 = 0; count2 < numberOfSquares; ++count2)
{
for (int count1 = 0; count1 < numberOfSquares; ++count1)
System.out.print("*");
System.out.println();
}https://stackoverflow.com/questions/8443376
复制相似问题