-3

I am wanting to print a character z for example the amount of times that matches the integer specified. So if int Z = 9 I then want "z" to print out 9 times

String newString = "";


    if (0<X)
    {
        for (int i = 0; i < X ;i++ ){
            newString+=("x");
            }
        }
    if (0<Y)
    {
        for (int i = 0; i < Y ;i++ ){
            newString+=("y");
            }
        }
    if (0<Z)
    {
        for (int i = 0; i < Z ;i++ ){
            newString+=("z");
            }

    }
return newString;
}

}

sr864
  • 1
  • 2
  • 2
    Try [`System.out.println("z".repeat(Z));`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#repeat(int)) – Andreas Nov 02 '19 at 16:59
  • 1
    Does this answer your question? [Simple way to repeat a String in java](https://stackoverflow.com/questions/1235179/simple-way-to-repeat-a-string-in-java) – Socowi Nov 02 '19 at 17:02
  • Please search before jumping to ask a question. This exact thing has been asked hundreds of times over the last decade. – Qix - MONICA WAS MISTREATED Nov 02 '19 at 17:41

2 Answers2

0

Just remove the while-loop. If you have it there, it will execute your code forever resulting in a StackoverflowError

String newString = "";
int Z = 9;
if (0 < Z) {
    for (int i = 0; i < Z; i++) {
        newString += ("z");
    }
    System.out.println(newString);
}
alea
  • 980
  • 1
  • 13
  • 18
  • 2
    Um, pretty sure that loops alone do not result in a stackoverflow. Stackoverflows happen for deeply nested function calls -- typically when using recursion. – Socowi Nov 02 '19 at 16:59
  • Thank you, im doing this with three integers XYZ together, but there can't be three of the same characters in a row. So say X=3 Y=8 and Z= 1, the output could be xxzyyxyy - 3 Xs, 1 Z and only 4 Y because anymore would mean there was 3 in a row. – sr864 Nov 02 '19 at 17:17
  • String newString = ""; if (0 – sr864 Nov 02 '19 at 17:19
  • I have edited the original code with what I have but the output I get is just xxxyyyyyyyyz, any help appreciated – sr864 Nov 02 '19 at 17:21
0
String newString = "";
int i = 0;
int z = 7; // any positive int

while (i < z)
{
    newString += "z";
}
System.out.println(newString);

If you want to keep the while loop approach for personal preference reasons, you can do so by the logic above. This is contingent on a proper value for z, which if less than i will result in never executing the wile loop. If you want to do this in one line, however, String has a .repeat method that can be called as follows : `System.out.println("z".repeat(7));

A Bear
  • 59
  • 6