英文:
Getting Maximum and Minimum Int instead of Input
问题
我正试图从用户那里收集输入,然后确定他们的数字中哪一个最大,哪一个最小。
英文:
I am trying to gather input from the user, and then denote which one of their numbers is the highest, and which one is the lowest.
int highest = Integer.MAX_VALUE, lowest=Integer.MIN_VALUE, number=0;
Scanner input = new Scanner(System.in);
for (int j=0; j<5; j++) {
System.out.print("Enter five integers: ");
number = input.nextInt();
}
if (number > highest){
highest = number;
}
if (number < lowest){
lowest = number;
}
System.out.println("Your highest number is: " + highest);
System.out.println("Your lowest number is: " + lowest);
It is giving me the maximum and minimum that an Integer can be ( 214... and -214...).
答案1
得分: 1
Swap the highest and lowest value, a number cannot possibly be greater than highest value, highest should start with MIN
and lowest should start with MAX
and move the comparison inside for loop
int highest = Integer.MAX_VALUE, lowest = Integer.MIN_VALUE, number = 0;
英文:
You should swap the highest and lowest value, a number cannot possibly be greater than highest value, highest should start with MIN
and lowest should start with MAX
and move the comparison inside for loop
int highest = Integer.MIN_VALUE, lowest = Integer.MAX_VALUE, number = 0;
答案2
得分: 1
Sure, here is the translated code part:
首先,确保五个整数的提示在循环之前,并且输入和使用输入值在循环内部。
以下是一些替代方法。
- 您还可以使用IntSummaryStatistics。它在流应用程序中经常使用,但也可以在命令式编程中使用。
IntSummaryStatistics stats = new IntSummaryStatistics();
Scanner input = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
stats.accept(input.nextInt());
}
System.out.println("Minimum = " + stats.getMin());
System.out.println("Maximum = " + stats.getMax());
- 或者您可以使用Math.min()和Math.max()。
int max = Integer.MIN_VALUE, min = Integer.MAX_VALUE;
for (int i = 0; i < 5; i++) {
int val = input.nextInt();
max = Math.max(max, val);
min = Math.min(min, val);
}
System.out.println("Minimum = " + min);
System.out.println("Maximum = " + max);
英文:
First, make certain the prompt for five integers is before the loop
and the input and use of the entered values are inside the loop
.
Here are some alternatives.
- You can also use IntSummaryStatistics. It's used quite often in stream applications but it can also be used in imperative programming.
IntSummaryStatistics stats = new IntSummaryStatistics();
Scanner input = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
stats.accept(input.nextInt());
}
System.out.println("Minimum = " + stats.getMin());
System.out.println("Maximum = " + stats.getMax());
- Or you can use Math.min() and Math.max()
int max = Integer.MIN_VALUE, min = Integer.MAX_VALUE;
for (int i = 0; i < 5; i++) {
int val = input.nextInt();
max = Math.max(max, val);
min = Math.min(min, val);
}
System.out.println("Minimum = " + min);
System.out.println("Maximum = " + max);
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论