0
我寫了一個程序,它有一個名爲Word_generator()
的構造函數。在此構造函數內部,有一個int
類型的實例變量,名爲count
。當我運行該程序並查看結果時,我注意到該程序已完成,即使我看不到count
增加的方式。這是困擾我的原因是因爲count
被用作構造函數末尾while
循環的條件檢查的一部分。java中的隨機字符串條件
僅供參考,這裏是我的工作代碼:
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();
}
你應該做什麼? –
如何完成打印和程序終止? –
在while循環中,每次檢查條件'count ++ == max'時,計數都會增加。當它達到最大值時,程序終止 – OutOfMind