简体   繁体   中英

Printing a * on each line as output

I'm fairly new to java. This is how the output to my problem should be: Enter a number between 5 and 20: 5.....5 stars* on the first line. 4 stars on the sec. 3 on the next and so on one star on the last line.

I did everything but I can't get the stars to print that way, here is my code:

    int number; 
    int num_stars; 
    Scanner num = new Scanner(System.in);
    System.out.println("Enter a number between 5 and 20"); user to enter a 
    number = num.nextInt();
    for(int i= 5; i >= number; i--) 
    { 

        //  inner loop to handle number of columns 
        //  values changing acc. to outer loop     
        for(int j = 20; j >= i; j--) 
        { 
            // printing stars 
            System.out.print("* "); 
        } 

        // ending line after each row 
        System.out.println(); 
    } 

thank you for your time

try this:

  for (int i=number;i>0;i--){
            for(int j=i;j>0;j--){
               System.out.print("*");
            }
            System.out.println( );
        }

but try this kind of exercises to solve on your own. It builds up your logic.

you can try fallowing code.. work for me..

    int number;
    int num_stars;
    System.out.println("Enter a number between 5 and 20");
    Scanner s = new Scanner(System.in);
    number = Integer.valueOf(s.nextLine());
    num_stars=number;
    for (int i = 1; i <= number; i--) {

        for (int j = 0; j < num_stars; j++) {
            System.out.print("*");
        }
        num_stars--;
        System.out.println();
    }
    System.out.println("over");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM