[英]Random string condition in java
我编写了一个程序,该程序具有名为Word_generator()
的构造函数。 在此构造函数内部,有一个名为count
int
类型的实例变量。 当我运行该程序并查看结果时,我注意到该程序已完成,即使我看不到count
增加的任何方式。 之所以困扰我,是因为count
用作构造函数结尾处while
循环的条件检查的一部分。
供参考,这是我正在处理的代码:
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();
}
如果(count ++ == max){...} , 则在此行增加count的值。在这里,首先检查count是否等于max,如果等于,则运行设置为false并结束循环; 否则,计数增加一。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.