2015-11-22 54 views
-3
Enter edge length of your rhomboid: 5 
Here is your rhomboid: 


    ***** 
    ***** 
    ***** 
***** 
***** 

我需要用扫描仪打印菱形图。我得到这样的:* * * * * *在日食中使用扫描仪打印菱形图

我的代码是这样的,通常我不坏,但我也没有做的第一行:

import java.util.Scanner; 
public class rhomboid { 

    public static void main(String[] args) { 

     Scanner scan = new Scanner(System.in); 

     System.out.println("Enter edge lenght of your rhomboid: "); 
     int edgelenght = scan.nextInt(); 
     System.out.println("Here is your rhomboid:"); 

     while(edgelenght > 0){ 
      System.out.print(" "); 
      System.out.print("*"); 
      edgelenght--; 
+0

你可以发布你的当前代码吗? – Tunaki

回答

0

所以,你的代码将只打印输出1D .. 输出: - *****

所以,要解决这个问题,你需要两个循环,一个用于行和列。现在菱形的2D打印有一点修改,首先现在打印前必须有4个空格的间隙,它可以通过使用一个更多的变量k来实现,如下所示。

public static void main(String[] args) { 
    Scanner scan = new Scanner(System.in); 

    System.out.println("Enter edge lenght of your rhomboid: "); 
    int edgelenght = scan.nextInt(); 
    int k = edgelenght - 1; 
    for (int i = 0; i < edgelenght; i++) { 

     for (int j = 0; j < k + edgelenght; j++) { 
      if (j < k) { 
       System.out.print(" "); 
      } else { 
       System.out.print("*"); 
      } 
     } 
     k--; 
     System.out.println(); 
    } 
} 
+0

谢谢它的正常工作 – eko56

+0

@ eko56: - 如果我的解决方案解决了您的问题,请不要忘记将其标记为“已接受”,如果您认为它有帮助,请投票。 接受标记将帮助其他人有类似的问题。 – Naruto

0

你得到的是你在代码中写的东西。

while(edgelenght > 0){ 
    System.out.print(" "); 
    System.out.print("*"); 
    edgelenght--; 
} 

将打印edgelenght次空间 “” 和一个后 “*”。

你需要的是这样的:

for(int line = 0; line < edgeLength; line++){ 
    // in line 0 print 4 spaces (5-1), in line 3 print 1 (5-1-3), in line 4 (the last one) print 0 
    for(int space = 0; space < edgeLength - line - 1; space++){ 
     System.out.print(" "); 
    } 
    for(int asterix = 0; asterix < edgeLength; asterix++){ 
     System.out.print("*"); 
    } 
    // print a newline 
    System.out.println(""); 
} 

你需要在第一线环。
对于每一行你需要一个循环来打印空格。还有一个打印*。

+0

谢谢你的工作 – eko56