int target = 42; int guess = 0; while (guess != target) {
System.out.print("请输入你的猜测:");
// 这里应该有获取用户输入的代码
// 假设guess会被更新
}
int count = 0; while (count < 5) {
System.out.println("当前计数:" + count);
count++;
}
Scanner scanner = new Scanner(System.in); int userInput = 0; boolean isValid = false;
while (!isValid) {
System.out.print("请输入1-100之间的数字:");
if (scanner.hasNextInt()) {
userInput = scanner.nextInt();
if (userInput >= 1 && userInput <= 100) {
isValid = true;
} else {
System.out.println("数字超出范围,请重新输入。");
}
} else {
System.out.println("输入的不是有效数字,请重新输入。");
scanner.next(); // 清除无效输入
}
}
System.out.println("您输入的有效数字是:" + userInput);
// 经典的无限循环示例 int count = 0; while (count < 10) {
System.out.println("这是第" + count + "次循环");
// 忘记递增count,导致条件永远满足
}
// 遍历数组 - for循环更合适 for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}