gpt4 book ai didi

java - 在不使用数组的情况下获取整数的最低和最高值?

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

我正在尝试编写一个类,它从用户读取 5 个整数并返回最高值和最低值。这必须使用循环来完成,并且不能使用数组和 Integer.MIN.Value/Integer.MAX.Value。我已经成功编写了从用户那里获取 5 个整数并返回最高值的代码,但我无法同时获得同一类中返回的最高值和最低值。

这是我上面提到的代码:

import java.util.Scanner;

public class Ovning_321 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int number;
int max = 0;

for (int x = 0; x<5; x++){
System.out.print("Give me an integer: ");
number = input.nextInt();

if (number > max){
max = number;
}
}
System.out.println("Highest value: " + max);
}
}

最佳答案

给你:)

import java.util.Scanner;

public class Ovning_321 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int number;
int max = 0;
int min = 0;

for (int x = 0; x<5; x++){
System.out.print("Give me an integer: ");
number = input.nextInt();

if (x == 0 || number > max){
max = number;
}
if (x == 0 || number < min){
min = number;
}
}
System.out.println("Highest value: " + max);
System.out.println("Lowest value: " + min);
}
}

关于java - 在不使用数组的情况下获取整数的最低和最高值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19435242/

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