簡體   English   中英

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

[英]How do I display the asterisks according to the number entered?

我目前正在自學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();
    }
}

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

您的代碼很好。 您只是缺少變量聲明。 可能您來自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();
}
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("");
        }

    }       
}

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

導入 java.util.Scanner; //程序使用class掃描儀

公共 class 打印{

public static void main(String[] args){
  //declare variables
  int num; 
  int x; //outer counter
  int y; //inner counter

  //use Scanner to obtain input
  Scanner input = new Scanner(System.in);
  System.out.print("Enter number: ");
  num = input.nextInt();

   //use for loop to generate the size of bar chart
   for(x = 0; x < num; x++)
   {
       for(y = 0; y < num; y++)
       {
          System.out.print("* ");
        } 

        System.out.println();
    }     
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM