gpt4 book ai didi

java - 用另一个 while 循环 Java 扩展我的程序

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

首先,我对 java 很陌生,所以请原谅下面代码的困惑。

我当前的程序从 StdIn 获取输入并打印出输入的最高和最低值。

如果他们输入的整数不是正数,是否可以扩展到再次询问用户?我几乎可以肯定 while 循环可以做到这一点,但不确定是否可以使用我当前的代码执行。再说一次,我是个新人,有音乐背景,所以我的逻辑感不是最好的。

public class PositiveIntegers
{
public static void main(String[] args)
{

do {
StdOut.println("Enter your integers:");
} while (StdIn.isEmpty());

int max = StdIn.readInt();
int min = max;

while (!StdIn.isEmpty()) {
int value = StdIn.readInt();
if (value > max) max = value;
if (value < min) min = value;
}

do {
StdOut.println("Maximum = " + max + ", Minimum = " + min);
return;
} while (StdIn.readInt() > 0);


}
}

干杯

最佳答案

您可以通过添加一个 if 语句来检查给定的数字是否为负数,然后打印消息以再次添加它来完成此操作。

检查下面的增强代码:

public class PositiveIntegers
{
public static void main(String[] args)
{

StdOut.println("Enter your integers:");

int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;

while (!StdIn.isEmpty()) {

int value = StdIn.readInt();

// Adding the if-statement here to check if number is negative.
if(value < 0){
StdOut.println("You entered negative number, try positive numbers.");
// just reset the max and min variables..
max = Integer.MIN_VALUE;
min = Integer.MAX_VALUE;
continue;
}

if (value > max) max = value;
if (value < min) min = value;
}

StdOut.println("Maximum = " + max + ", Minimum = " + min);

}
}

关于java - 用另一个 while 循环 Java 扩展我的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47241386/

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