gpt4 book ai didi

java - do while 循环出现逻辑错误

转载 作者:行者123 更新时间:2023-12-01 23:45:23 25 4
gpt4 key购买 nike

有人可以帮我解决我的逻辑错误吗?我很新,确实需要一些帮助。这是一个介绍类的简单程序(我想这是非常明显的)。我希望用户留在循环中,除非他们输入 -99 退出。然后它将显示最高和最低的条目。

谢谢!

import java.util.Scanner;

public class LeastGreatest {

public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);
int input = 0, high = 0, low = 0;

System.out.println("Welcome to fun with Loops and Numbers!\n");
System.out.println("Please Enter the AN INTEGER: \n");
input = keyboard.nextInt();

high = input;
low = input;
//System.out.println(input);
do
{
System.out.println("Please Enter the AN INTEGER (Press -99 to Exit): \n");
input = keyboard.nextInt();

if (input > high)
{
input = high;
}
if (input < low)
{
input = low;
}
} while(input != -99);

System.out.println("The highest INT entered was: " + high);
System.out.println("The lowest INT entered was: " + low);
System.out.println("Thank You! Goodbye!");
}
}

最佳答案

您正在重复分配 input恢复到原来的值:

high = input;
low = input;
...
if (input > high)
{
input = high; // input = input
}
if (input < low)
{
input = low; // input = input
}

这是正确的:

if (input > high)
{
high = input;
}
if (input < low)
{
low = input;
}

此外,假设input < -99无效,最低值始终为 -99。以下内容将纠正此问题:

while (input != -99) { // Break BEFORE setting low to -99.
if (input > high)
{
high = input;
}
if (input < low)
{
low = input;
}

System.out.println("Please Enter the AN INTEGER (Press -99 to Exit): \n");
input = keyboard.nextInt();
}

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

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