2016-08-22 5 views
0

競合サイトで問題を解決していましたが、出力前に新しい行が印刷されるため、出力がテストケースの出力と一致しません。私はコードのどの部分がそれを印刷しているかを検出することができません。誰か助けてください?ouputの前に新しい行を印刷していますか?

Problem

マイ溶液:

 # 
    ## 
    ### 
    #### 
##### 
###### 

マイO/P:最初for iteratioで

<NEWLINE> 
     # 
     ## 
     ### 
     #### 
    ##### 
    ###### 
+4

ヒント:これをデバッガで実行してみてください。あるいは、ペンを使って紙の上でさえ。それは自分のコードを理解するための良い方法です。あなたに明白なことを説明させるために他の人に向けるのと比較して。 (意味ではっきりしています:コードはすべてそこにあります、あなたはそれが何をしているかを注意深く分析する必要があります)。 – GhostCat

答えて

2

/P O

public static void main(String[] args) { 
    Scanner in = new Scanner(System.in); 
    int n = in.nextInt(); 
    for(int i=n;i>=0;i--){ 
     int count=0; 
     while(count<i){ 
      System.out.print(" "); 
      count++; 
     } 
     while(count!=n){ 
      System.out.print("#"); 
      count++; 
     } 
     System.out.println(); 
    } 
} 

テストケースn空白だけを印刷し、新しい行を印刷します。

int n = in.nextInt(); 
for(int i = n; i >= 0; i--) { 
    int count=0; 
    // At the first for iteration print exactly n spaces 
    while(count < i){ 
     System.out.print(" "); 
     count++; 
    } 
    // Here count equals i that equals n in the first for iteration 
    // SO doesn't enter in the while 
    while(count!=n){ 
     System.out.print("#"); 
     count++; 
    } 
    // And prints the new line 
    System.out.println(); 
} 

で置き換えます。出力する必要があります: - あなたが唯一の空白の行を印刷する必要はありませんという事実に1

...... 
.....# 
....## 
...### 
..#### 
.##### 
###### 

問題を解決するためには、単純にn個からforループを開始します。

0
for(int i=n;i>=1;i--){ 
     int count=0; 
     while(count<i-1){ 
      System.out.print(" "); 
      count++; 
     } 
     while(count!=n){ 
      System.out.print("#"); 
      count++; 
     } 
     System.out.println(); 
    } 

あなたがすでに6回実行しているので、ちょうど "#"記号を配置する場所がもうないので、この方法を試してください。

関連する問題