2013-03-07 140 views
0

这就是问题:嵌套for循环与数字和“ - ”

编写一个名为printDesign的方法,产生以下输出。使用嵌套for循环来捕获图形的结构。

-----1----- 
----333---- 
---55555--- 
--7777777-- 
-999999999- 

这是我有:

public static void printDesign() { 

    for(int dashAmt= 5; dashAmt >= 1; dashAmt--){ 
     for(int dash = 1; dashAmt <= dash; dash++){ 
      System.out.print("-"); 
     } 
     System.out.println(); 
     for(int numAmt = 1; numAmt <= 9; numAmt+=2) { 
      for(int num = 1; num1 <= numAmt; num++) { 
       System.out.print(num); 
      } 
      System.out.println(); 
     } 
    } 
} 

我的问题是我怎么会得到在同一行号划线,所以我可以得到这个:

-----1----- 
----333---- 
---55555--- 
--7777777-- 
-999999999- 
+0

为什么不试试自己??我想这是一个家庭作业问题。 – Anubhab 2013-03-07 06:17:07

+0

什么是** num1 ** ?? – Anubhab 2013-03-07 06:18:42

+1

你已经使用了'println()'和'print()'方法,所以我假设你知道区别。答案只是在玩这些方法:)你的亲密,不要放弃,如果这是一个功课:) – Oneb 2013-03-07 06:20:24

回答

0

删除从每个for循环中取出2 System.out.println();并放入外部for循环中。

for(int dashAmt= 5; dashAmt >= 1; dashAmt--){ 
     for(int dash = 1; dashAmt <= dash; dash++){ 
      System.out.print("-"); 
     } 
//  System.out.println(); // Removed 
     for(int numAmt = 1; numAmt <= 9; numAmt+=2) { 
     for(int num = 1; num <= numAmt; num++) { // Its num and not num1 - typo by you 
       System.out.print(num); 
      } 
//   System.out.println(); // Removed 
     } 
     System.out.println(); // Put it here. 
    } 

注:这只能解决您的sysout问题。不过,你的逻辑是错误的,我没有解决这个问题。做你的作业。

0
public class PrintDesign { 
     public static void main (String args[]) { 
      printDesign(); 
     } 

      public static void printDesign() { 
      int b = 0; 
      for (int i = 1; i <= 9; i += 2) { 
       for (int k = 0 ; k < 5 - b; k++) { 
        System.out.print("-"); 
       } 
        for (int j = 1; j <= i; j++) { 
        System.out.print(i); 
       } 
        for (int k = 0 ; k < 5 - b; k++) { 
         System.out.print("-"); 
        } 
        System.out.print(" "); 
        System.out.print(""); 
        System.out.println(""); 
        b ++; 
     } 
     } 
    } 
+0

添加解释给你的答案 – HaveNoDisplayName 2015-06-04 17:14:19