0

在我的计算机科学课上,我们被要求创建一个程序,该程序会提示用户输入他们希望在“魔术盒”中打印的行数、列数和符号,并存储这些变量中的每一个并将它们打印出来使用嵌套的 for 循环拥有自己的魔法盒。我的程序可以正确编译并根据我的输入打印正确的框,但它不会打印我的两个打印语句。它将打印前三个语句(提示用户输入某些内容的语句),但不打印语句

Here comes the magic...Here's your very own magic box

This magic box brought to you by Beth Tanner."

我已经尝试了我能想到的一切,但仍然无法打印这些语句,任何帮助将不胜感激。我在下面包括我的程序。

import java.util.Scanner;

public class MagicBox {
  public static void main(String[] args) {
    Scanner input= new Scanner(System.in);

    System.out.println("How many rows would you like in your box?");
      int rows = input.nextInt();
    System.out.println("How many columns would you like in your box?");
      int columns = input.nextInt();
    System.out.println("What symbol would you like in your box?");
      String symbol = input.next(); 

    System.out.println("Here comes the magic...\nHere's your very own magic box!");

    int count1;
    int count2;
      for(count1 = 1; count1 <= rows; count1++) 
        for (count2 = 1; count2 <= columns; count2++)
          System.out.print(symbol);
          System.out.println(); 
      System.out.println("This magic box brought to you by Beth Tanner.");   

  } // end main
} // end class
4

3 回答 3

2

使用正确的块,一切正常。

请注意,外部循环必须包含由System.out.println();. 在您的代码中,仅在所有 row * columns符号都打印在一行上之后才打印此换行符。

int rows = 5;
int columns = 3;
String symbol = "@";

System.out.println("Here comes the magic...\nHere's your very own magic box!");

for (int count1 = 1; count1 <= rows; count1++) {
    for (int count2 = 1; count2 <= columns; count2++) {
        System.out.print(symbol);
    }
    System.out.println();
}

System.out.println("This magic box brought to you by Beth Tanner.");

输出:

Here comes the magic...
Here's your very own magic box!
@@@
@@@
@@@
@@@
@@@
This magic box brought to you by Beth Tanner.
于 2013-10-29T14:57:23.987 回答
0

我不知道魔术盒是什么,但我假设你想要这样的东西:

for(count1 = 1; count1 <= rows; count1++) {
    for (count2 = 1; count2 <= columns; count2++) {
      System.out.print(symbol);
    }
    System.out.println();
  }

您的初始代码存在几个问题:

  • 没有声明“列”变量 - 你有一个错字,它实际上是列
  • 始终在循环中使用花括号。如果没有这些,每个循环中只会执行一个表达式,这意味着 System.out.println() 只会被调用一次,而不是在每一行之后添加。
于 2013-10-29T14:57:18.697 回答
0

我想你想要这个:

for(count1 = 1; count1 <= rows; count1++){ 
  for (count2 = 1; count2 <= columns; count2++)
    System.out.print(symbol);

  System.out.println(); 
}

甚至更清晰

for(count1 = 1; count1 <= rows; count1++){ 
  for (count2 = 1; count2 <= columns; count2++){
    System.out.print(symbol);
  }

  System.out.println(); 
}

这会给你你想要的魔法盒。

此链接可能会帮助您看到不同之处:stackoverflow question on omitting brackets

于 2013-10-29T15:03:50.543 回答