2016-08-23 69 views
0

我目前正在學習Java,我真的很想學很多東西。我問我的程序員朋友給我一些任務,他給了我這個。如何根據輸入的號碼顯示星號?

如何根據輸入的數字顯示星號?

Enter Number:7 
* 
** 
*** 
* 

我已經寫了代碼,但我仍然不能得到它。請舉一些例子嗎?

import java.util.Scanner; 

public class Diamond { 

    public static void main(String[] args) { 

     Scanner input = new Scanner(System.in); 

     /*promt for input*/ 
     System.out.println("Enter number: "); 
     int how_many = input.nextInt(); 

     for(int i = 1; i <= how_many; i++) { 
      for(int j = 1; j <= i; j++) { 
       System.out.print("*"); 
      } 
      System.out.println(""); 
     } 

     input.close(); 
    } 
} 

任何幫助或建議將不勝感激。

+1

您需要爲'how_many'指定一個類型。 ---例如'int how_many = input.nextInt();' – byxor

+0

已經做到了。那只是一個整個代碼先生的一部分:) –

+0

所以只是一個跟進的問題,如果我進入5應該看起來像: * ** ** 它 – bszeliga

回答

1

你的代碼沒問題。你只是缺少變量聲明。可能你來自JavaScript背景。在每個變量(how_many,i和j)之前聲明int並嘗試編譯&再次執行它。

System.out.println("Enter number: "); 

int how_many = input.nextInt(); 

for(int i = 1; i <= how_many; i++) { 
    for(int j = 1; j <= i; j++) { 
     System.out.print("*"); 
    } 
    System.out.println(""); 
} 

另外。我假設你已經在Scanner對象的一切

import java.util.*; 
// etc, etc 

Scanner input = new Scanner(System.in); 

之前聲明,我想我明白你問的是什麼:

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

    System.out.println("Enter number: "); 

    int how_many = input.nextInt(); 

    outer: 
    for(int i = 1, count = 0; i <= how_many; i++) { 
     for(int j = 1; j <= i; j++) { 
      if(count >= how_many) 
       break outer; 
      System.out.print("*"); 
     } 
     System.out.println(""); 
    } 

    input.close(); 
} 
+0

先生。看看編輯過的帖子。我的意思是,如果我輸入7,那麼只有7個星號,如下所示: * ** *** * –

+0

這是使用您的代碼的結果,先生,這是我的。 輸入數字: * ** *** **** ***** ****** ******* –

+0

我不跟着你。問題是什麼? –

1
class Print{ 

    public static void main(String argas []){ 


     Scanner in=new Scanner(System.in); 
     System.out.println("Enter number: "); 

     int how_many = in.nextInt(); 
     int count=0; 

     for(int i = 1; i <= how_many; i++) 
     { 
      for(int j = 1; j <= i; j++) 
      { **if(count==how_many) 
       return;** 
       System.out.print("*"); 
       count++; 
      } 
      System.out.println(""); 
     } 

    }  
} 

添加條件檢查*數量是否小於輸入。

+0

哦,我的上帝。謝謝你,先生 !!你能解釋我是怎麼得到的嗎? –

+0

爲什麼先生?他的回答是我在找什麼?你爲什麼低估他? –

+0

我想我終於明白你在問什麼了。我會鼓勵你們兩個。看我的編輯。我做了一個稍微不同的版本。此外,@ mukulshukla的代碼將無法關閉掃描儀,除非在返回之前將其關閉。 –