Reputation: 1
I wrote a program that has a constructor called Word_generator()
. Inside of this constructor, there is an instance variable of type int
called count
. When I run the program, and look at the results, I noticed that the program finished even though I see no way for count
to have increased. The reason that this is bothering me is because count
is used as part of the conditional check for a while
loop at the end of the constructor.
For reference, here is the code I am working on:
private String[] array = {"hello", "hi", "what is your name"};
private String getRandomCharacter() {
return array[random(array.length)];
}
private int random(int length) {
return new Random().nextInt(length);
}
protected Word_generator() {
boolean running = true;
int count = 0;
int max = 200;
while (running) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1; i++) {
sb.append(getRandomCharacter());
System.out.println();
System.out.println("Word-->");
}
System.out.println(sb.toString());
if (count++ == max) {
running = false;
System.out.println("finished");
}
}
}
public static void main(String[] args) {
new Word_generator();
}
Upvotes: 0
Views: 117
Reputation: 417
The value of count is being increased at this line if (count++ == max){...} Here, first of all count is checked whether equal to max, if equals then running is set to false and loop is finished; else count is incremented by one.
Upvotes: 1