簡體   English   中英

Java程序未打印我的所有打印語句

[英]Java program not printing all of my print statements

在我的計算機科學課上,我們被要求創建一個程序,該程序將提示用戶輸入要在“魔術盒”中打印多少行,列和什么符號,並存儲每個變量並打印它們自己的魔術盒,使用嵌套的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

使用正確的塊,一切正常。

注意,外部循環必須包含由System.out.println();產生的換行符System.out.println(); 在你的代碼這個新行只印AFER 所有 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.

我不知道什么是魔術盒,但我認為您想要這樣的東西:

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

您的初始代碼有兩個問題:

  • 沒有聲明“ collumns”變量-那里有錯字,實際上是列
  • 始終在循環中使用花括號。 如果沒有這些,則在每個循環中將只執行一個表達式,這意味着System.out.println()只會被調用一次,而不是在每行之后添加。

我想你想要這個:

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問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM