gpt4 book ai didi

java - 为什么这个 while 循环不结束?

转载 作者:行者123 更新时间:2023-11-29 05:41:40 24 4
gpt4 key购买 nike

import java.io.*;
import java.util.Scanner;

public class Solve {
public static void main(String[] args) {
int max = 10;
int i = 0;
long record = 100000;
while (i != 100) {
int x = (int) (Math.random() * max) + 1;
int y = (int) (Math.random() * max) + 1;
int solution = x + y;
long startTime = System.currentTimeMillis();

while (i != solution) {
System.out.println("Enter the solution to " + x + "+" + y);
Scanner sc = new Scanner(System.in);
i = sc.nextInt();
if (i != solution) {
System.out.println("Incorrect");

} else {
System.out.println("Correct!");
}
long endTime = System.currentTimeMillis();
System.out.println("You took: " + (endTime - startTime) + "ms");

if (endTime - startTime < record) {
record = endTime - startTime;
System.out.println("New record time: " + record + "ms");
}
}
}
}
}

这个程序创建一个简单的加法问题并要求用户输入答案。它还跟踪正确回答问题所需的时间。我试图让用户通过为 i 输入 100 来结束第一个 while 循环,但是有没有更好的方法来结束这个循环?

最佳答案

永远不会跳出内部while 循环。您的执行路径将卡在那里。一个快速的解决方法是调整你对内部循环的循环约束:

while (i != solution && i != 100)

关于java - 为什么这个 while 循环不结束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17309893/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com