2015-09-08 19 views
1

由于某些原因,只有奇数行才能正确分隔。有人可以解释这个吗?这是我的代码。在java工作中需要帮助制作等边三角形的代码

import java.util.Scanner; 
public class Triangle { 


    public static void main(String args[]) { 
     int i, j, k1; 
     Scanner in = new Scanner(System.in); 
     System.out.println("Enter the length of the side of your equilateral triangle: "); 
     int side = in.nextInt(); 
     System.out.println("Enter the character you want your triangle filled with: "); 
     char fill = in.next().charAt(0); 
     while (side<=0 || side>50){ 
      System.out.print("Please enter a length between 1 and 50: "); 
      side = in.nextInt(); 
      break; 
     } 
     for(i=1; i<=side;i++){ 
      for (k1=0; k1 < (side-i/2);k1++){ 
       System.out.print("\t"); 
      } 
      for(j=1;j<=i;j++){ 
       System.out.print(fill + "\t"); 
      } 
      System.out.println('\n'); 
     } 
     in.close(); 
    } 
} 

这是我的结果: 输入您的等边三角形的边长:输入你希望你的三角形填充字符: *

   * 

      * * 

      * * * 

     * * * * 

     * * * * * 

我想这一点:

# 
    # # 
    # # # 
# # # # 
# # # # # 
+0

你在做什么,你期望什么? – Andreas

+0

无关:带有无条件'break'的while循环有什么意义? – Andreas

+0

这是我的第一个java类,所以我认为在用户输入正确的数字后,休息会继续我的代码的其余部分 –

回答

3

只需添加这一点,并改变/吨至4位:

if(i%2 ==0 && j ==1){ 
    System.out.print(" "); // two spaces 
} 

的完整代码

for(i=1; i<=side;i++){ 

     for (k1=0; k1 < (side-i/2);k1++){ 
      System.out.print(" "); 
     } 
     for(j=1;j<=i;j++){ 

      if(i%2 ==0 && j ==1){ 
       System.out.print(" "); 
      } 
      System.out.print(fill + " "); 
     } 
     System.out.println('\n'); 
    } 

的原因是因为每个偶数行需要入手,因为它有点偏移必须在填充字符的中间,我得到这个

       *  

           * *  

          * * *  

          * * * *  

         * * * * *  

         * * * * * *  

        * * * * * * *  

        * * * * * * * *  

       * * * * * * * * *  
+0

This!非常感谢! –

+1

这并不像预期的那样工作...而且我不是在争论,因为你不接受我回答的事实。只要尝试一边长度为1,2,3,... N,你会看到“毛刺” –

+0

Umm的作品与我鳍 –

1

您尚未说明预期结果,但删除了/2可能会诀窍。

也许用空格替换\t

println中删除'\n',除非您想在行之间留空行。

1

如何:

try (final Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8.name())) { 
    System.out.print("Enter the length of the side of your equilateral triangle: "); 

    final int side = scanner.nextInt(); 

    System.out.print("Enter the character you want your triangle to be filled with: "); 

    final char character = scanner.next().charAt(0); 

    for (int i = 1; i <= side; i++) { 
    final StringBuilder builder = new StringBuilder(side); 

    for (int k = 0; k < (side - i); k++) { 
     builder.append(' '); 
    } 
    System.out.printf(builder.toString()); 
    for (int j = 0; j < i; j++) { 
     System.out.printf("%s ", character); 
    } 
    System.out.println(); 
    } 
} 

请注意在try-与资源与Scanner - 只有从Java 7(及以后)可用。

+0

我同意所有扫描仪的试用资源,*除* System.in中的扫描仪。你不应该关闭'System.in'。 – Andreas

+0

@Andreas在应用程序流程结束时做什么问题?你介意说明一下吗? –

+0

这可能是正确的,但它对我的技能水平来说太复杂了 –