John_K
John_K

Reputation: 112

How to multiply a String by an Integer?

I know there's some way to change a string into an integer but it's not really working out for me when I try to do it.

I was asked to take in an integer 'n' and 'a' string 's' and print 's' 'n' times

Here's my code and my main question / question is how do I easily turn the string into an integer so I can multiply the two together:

public static void main(String args[])
{
        System.out.println("Enter the number of times you want to print a string");
        Scanner n = new Scanner(System.in);
        int x = n.nextInt();

        System.out.println("Enter the string you want printed");
        Scanner y = new Scanner(System.in);
        String s = y.nextLine();
}

Upvotes: -1

Views: 10252

Answers (2)

Ben
Ben

Reputation: 1

You can also always use the .repeat to multiply a string.

public static void main(String[] args) {
    for (int i = 0; i < 10; i++) {
        System.out.println("*".repeat(i));

    }
}

The expected output:

*
**
***
****
*****
******
*******
********
*********

It only gives back 9 * and rows, because in Java counting starts at 0 and x times 0 gives back 0. ==> x*0 = 0. If you want to give back 10 * and rows you need to add one:

public static void main(String[] args) {
    for (int i = 0; i < 10; i++) {
        System.out.println("*".repeat(i + 1));

    }
}

Hope that helps.

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201537

You only need one Scanner, and if I understand your question then you might use a loop like, also an int n.

System.out.println("Enter the number of times you want to "
        + "print a string");
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
System.out.println("Enter the string you want printed");
String s = scan.nextLine();
for (int i = 0; i < n; i++) {
    System.out.print(s);
}
System.out.println();

Of course, you could put the loop in a method like

private static String multiply(String str, int n) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < n; i++) {
        sb.append(str);
    }
    return sb.toString();
}

Then you could call it like,

Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
System.out.println("Enter the string you want printed");
String s = scan.nextLine();
System.out.println(multiply(s, n));

Upvotes: 3

Related Questions