Search code examples
javanumberscpu-wordrepeat

Print a string a number of times in a row


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 :)


Solution

  • 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);
            }
    }