Print a string a number of times in a row

3.6k Views Asked by At

Ok so i know there is a smilier question but I think mine is slightly different so I'll post and risk getting panned by you all ;)

So i want the user to input a word (Java) and then input a number (4) and the programme then prints in this case JavaJavaJavaJava

Here is what I have got so far

Scanner sc = new Scanner(System.in);
    System.out.print("Enter a word: ");
    String str = sc.nextLine(); 

    Scanner sc1 = new Scanner(System.in);
    System.out.print("Enter a number: ");
    String num = sc1.nextLine(); 

    System.out.println(str);
    System.out.println(num);

From what i understand i may be scanning in the number the wrong way as i'm currently scanning it in as a String and not an integer but hey.

Any help massively appreciated :)

4

There are 4 best solutions below

0
On BEST ANSWER

You have to use a for-loop for this, and scan the number as an integer.

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
        System.out.print("Enter a word: ");
        String str = sc.nextLine(); 

        System.out.print("Enter a number: ");
        int num = sc.nextInt(); 

        for (int i=0;i<num;i++) {
            System.out.println(str);
        }
}
0
On

Nearly there. Add the following at the end:

int number = Integer.parseInt(num);

for (int i=0; i<number; i++) {
    System.out.print(str);
}
0
On

There are a couple things you're going to want to change to do this.

1) You're only calling System.out.println(str); once, so the string will only be printed once. Now, you could just put System.out.println(str); 3 times, but then you'd be stuck with num always being 3. What I'd suggest is using a for loop, like the one found here. Basically, it would look like this assuming num is 10 and str is test string

for(int i=0;i<10;i++)
{
    System.out.println("test string");
}

You'll want to change that to fit your exact case, but that should be enough to get you started.

2) You're right here

i may be scanning in the number the wrong way as i'm currently scanning it in as a String and not an integer.

You want to scan it in as an integer, otherwise it's useless for your purposes. For all java knows, you want to print out your string puppy or bacon times rather than 3 or 4.

If you still have any questions about this, lemme know. We've all been there man.

0
On
Scanner sc = new Scanner(System.in);
System.out.print("Enter a word: ");
String str = sc.nextLine(); 

Scanner sc1 = new Scanner(System.in);
System.out.print("Enter a number: ");
String num = sc1.nextLine(); 

int counter = 0;
while (counter < num){
  System.out.print(str);
  counter ++;
}