gpt4 book ai didi

java - while 循环出现问题

转载 作者:太空宇宙 更新时间:2023-11-04 10:05:08 25 4
gpt4 key购买 nike

现在对于编程来说还是全新的一周。一直在编写小程序来帮助我记住基础知识。当我运行此代码时,如果我正确输入第一个问题,它会正确运行,但如果我回答错误,然后它会循环回来,我再次回答正确,它会继续循环而不继续执行其余代码。

import java.util.Scanner;

public class Parker {
public static void main(String []args) {
Scanner scan = new Scanner(System.in);
System.out.print("How old are you: ");
int age = scan.nextInt();
if (age > 6) {
System.out.println("You are to old for the program");
}
else {
System.out.println("Welcome to the program, enjoy!");
System.out.println("What is 5 + 3? ");
int num1 = scan.nextInt();
if (num1 == 8) {
System.out.println("Correct!");
} else {
System.out.println("Wrong! I'm telling your DADDY!");
}
while (num1 != 8) {
System.out.println("What is 5 + 3? ");
int num9 = scan.nextInt();
if (num9 == 8) {
System.out.println("Correct!");
} else {
System.out.println("Wrong! I'm telling your DADDY!");
}
}
System.out.println("What is 3 + 11? ");
int num2 = scan.nextInt();
if (num2 == 14) {
System.out.println("Correct!");
} else {
System.out.println("Wrong! I'm telling your DADDY!");
}
System.out.println("What is 7 + 6? ");
int num3 = scan.nextInt();
if (num3 == 13) {
System.out.println("Correct!");
}
else {
System.out.println("Wrong! I'm telling your DADDY!");
}
System.out.println("What is 11 - 5? ");
int num4 = scan.nextInt();
if (num4 == 6) {
System.out.println("Correct!");
}
else {
System.out.println("Wrong! I'm telling your DADDY!");
}
System.out.println("What is 4 + 9? ");
int num5 = scan.nextInt();
if (num5 == 13) {
System.out.println("Correct!");
}
else {
System.out.println("Wrong! I'm telling your DADDY!");
}
}
}
}

最佳答案

while (num1 != 8) {
System.out.println("What is 5 + 3? ");

int num9 = scan.nextInt();

if (num9 == 8) {
System.out.println("Correct!");
} else {
System.out.println("Wrong! I'm telling your DADDY!");
}
}

代码中的上述条件取决于 num1,但您永远不会在该循环内更改 num1 的值。因此,该循环永远不会终止。

关于java - while 循环出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53036908/

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