2015-11-22 95 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