2017-06-04 122 views
2

这是一个考试练习题,我被授予了为我的java考试接近学习......我被赋予了主要方法,并且不能改变输入,只有改变另外两种方法和他们的代码。我需要打印出试图用for循环形成一个半三角形,没有任何东西正在打印

 & 
    && 
    &&& 
    &&&& 
&&&&& 
&&&&&& 

我想我已经写了我的for循环错误创建空白,我似乎无法得到这个写出来与主要方法我已经放弃,任何想法?

public static void main(String[] args) { 
    int size = 6; 
    char c = '&'; 
    for (int i = 1; i < size + 1; i++) { 
     drawBlanks(size, size - i); 
     drawChars(size, size - i, c); 
     System.out.println(); 
    } 
    System.out.println(); 

} 

public static void drawChars(int size, int i, char c) { 

    for (int j = size; j < 1; j--) { 
     System.out.print(c); 
    } 

} 

public static void drawBlanks(int size, int i) { 

    for (int k = 0; k <= i; k++) { 
     System.out.print(" "); 
    } 
} 

回答

1

你在这个循环中的一个问题:

for(int j = size; j < 1; j--) 

相反,它更改为:

for (int j = size; j > i; j--) { 
//-------------------^_^ 

j应>到i没有j <到1

+1

喔是的我看到现在,我必须做出一个错字,感谢堆 –

+0

欢迎你@ B.Fall –

0
一个循环内

替代解决方案:

public class Main { 

    public static void main(String[] args) { 
     int rowCount = 10; 
     int whiteSpaceCount = rowCount - 1; 

     for (int i = 0; i < rowCount; i++) { 
      for (int j = 0; j < rowCount; j++) { 
       char ch = ' '; 
       if (j >= whiteSpaceCount) 
        ch = '&'; 
       System.out.print(ch); 
      } 
      System.out.println(); 
      whiteSpaceCount = rowCount - (i + 2); 
     } 
    } 
} 
0

您需要更改j < 1;j > 1;,在这之后你的输出将是,

输出:

 &&&&& 
    &&&&& 
    &&&&& 
    &&&&& 
    &&&&& 
&&&&& 

为了让您的预期产出变化j > 1j > i

public static void main(String[] args) { 
      int size = 6; 
      char c = '&'; 
      for (int i = 1; i < size + 1; i++) { 
       drawBlanks(size, size - i); 
       drawChars(size, size - i, c); 
       System.out.println(); 
     } 
    System.out.println(); 

} 

public static void drawChars(int size, int i, char c) { 

    for (int j = size; j > i; j--) { 
     System.out.print(c); 
    } 

} 

public static void drawBlanks(int size, int i) { 

    for (int k = 0; k <= i; k++) { 
     System.out.print(" "); 
    } 
} 

输出:

 & 
    && 
    &&& 
    &&&& 
    &&&&& 
&&&&&&