Java程序没有打印我的所有打印语句

时间:2013-10-29 14:43:31

标签: java

在我的计算机科学课上,我们被要求创建一个程序,该程序将提示用户输入他们想要在“魔术盒”中打印的行数,列数和符号数,并存储每个变量并打印他们是使用嵌套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

3 个答案:

答案 0 :(得分:3)

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

请注意,外部循环必须包含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.

答案 1 :(得分:0)

我不知道Magic box是什么,但我想你想要这样的东西:

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

您的初始代码存在一些问题:

  • 没有声明“collumns”变量 - 你有一个拼写错误 它实际上是列
  • 始终在循环中使用花括号。如果没有这些,你只会在每个循环中执行一个表达式,这意味着System.out.println()只会调用一次而不是在每一行之后添加。

答案 2 :(得分: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 braces