1

I created a for loop in java with string variabe. I want to add a character to the variable until that variable is equal to a set of characters. I created that for loop. No errors was shown in console. But also no output "( Where did I wrong?

for (String s = "*"; s == "* * * *"; s += " *") {
        System.out.println(s);
    }
Galactus
  • 11
  • 1
  • 2
    [Don't use `==` to compare strings.](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java/513839#513839) – jsheeran Apr 06 '22 at 15:17
  • 2
    @jsheeran That is one problem, but even changing to `equals()` won't entirely solve the issue. – Code-Apprentice Apr 06 '22 at 15:18
  • 3
    The condition in the `for` loop is _not_ about "stopping once true" but rather "iterating while true". – sp00m Apr 06 '22 at 15:22

1 Answers1

2

This is actually a very creative solution to a common beginner coding problem. However, it has two problems:

  1. == doesn't work to compare strings. Instead, you need to use the equals() method: s.equals("* * * *").

  2. Even after fixing #1, the bigger problem is that the condition will never be true. The condition must be true to execute the code inside the loop. Since s.equals("* * * *") returns false the first time, the loop never executes.

You can try to fix this by making a different condition using a string. Alternatively, find a different way by using an int counter in the for loop.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268