繁体   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