Dawesy
Dawesy

Reputation: 37

Java Beginner - How to print a character multiple time on one line

I am trying to code a program to print a box of * when a value is entered. e.g if a user enters 5 the system will print out 5 line of a star (*) printed 5 times on each line.

I've currently got the system to print out the correct amount of lines, but not the correct amount of '*' on the line.

How can I get the system to print '*' the amount of times the user entered, on one line?

my current code:

import java.util.Scanner;
public class Main
{
    public static void main(String args[])
    {
        Scanner in = new Scanner(System.in);

        int size;
        int line = 1;

       System.out.print(" #Enter size of square:   ");
       size = in.nextInt();

       while (line <= size)
       {
            System.out.println("*");
            line = line + 1;
        }
    }
}

Upvotes: 1

Views: 2218

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533530

You can do this in Java 8 with

IntStream.range(0, n).forEach(i -> System.out.print("*"));

or in older versions

for (int i = 0; i < n; i++)
    System.out.print("*");

Upvotes: 2

Related Questions