比较IF语句中的多个整数,Java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28020093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Comparing multiple integers in IF statement, Java
提问by nanthil
I am brand new to coding. I'm currently using "Java:How to program" by Deitel, and one of the early exercises has me stumped.
我是编码新手。我目前正在使用 Deitel 的“Java:How to program”,其中一项早期练习让我难住了。
It is asking me to use simple, chapter 1 if statements to compare 5 integers (input by the user) and display both the largest and the smallest. I am limited to the language used in the first chapter, so I made the assumption that I could list int values in the parenthetical after the if statement. Something like:
它要求我使用简单的第 1 章 if 语句来比较 5 个整数(由用户输入)并显示最大和最小。我仅限于第一章中使用的语言,因此我假设我可以在 if 语句后的括号中列出 int 值。就像是:
int firstInt;
int secondInt;
int thirdInt;
int fourthInt;
int fifthInt;
if (first Int> secondIt, thirdInt, fourthInt, fifthInt)
etc. but this is a syntax error. Does anyone know how to compare multiple values simultaneously? A google search proves to be no help since all the answers have some convoluted solution that I don't understand.
等等,但这是一个语法错误。有谁知道如何同时比较多个值?谷歌搜索证明没有帮助,因为所有答案都有一些我不明白的复杂解决方案。
If I try something like this:
如果我尝试这样的事情:
if (one > two)
System.out.println("%d is the largest number!", one);
if (one > three)
etc. for all 1 - 5, The issue I run into is when I continue with if statements 1>2,3,4,5 2>1,3,4,5 etc. then there will be 1 true for each integer regardless except for the smallest number, and it will display 4 outputs, when all I'm after is the larges and the smallest.
等等,对于所有 1 - 5,我遇到的问题是,当我继续使用 if 语句 1>2,3,4,5 2>1,3,4,5 等时,每个整数都会有 1 个真,无论除了最小的数字,它会显示 4 个输出,当我所追求的是最大和最小的时候。
I'm stumped.
我难住了。
采纳答案by paxdiablo
The expression:
表达方式:
firstInt > secondInt, thirdInt, fourthInt, fifthInt
is not valid because Java is a computer language rather than a natural language (like English).
无效,因为 Java 是一种计算机语言,而不是一种自然语言(如英语)。
If you want to do it that way, what you need is the and
conjunction, with multiple completeconditions (using a,b,c,d,e
to minimise the code):
如果你想这样做,你需要的是and
具有多个完整条件的连接(a,b,c,d,e
用于最小化代码):
if ((a >= b) && (a >= c) && (a >= d) && (a >= e)) { // a >= b,c,d,e
System.out.println ("Largest is: " + a);
} else if ((b >= c) && (b >= d) && (b >= e)) { // b >= c,d,e
System.out.println ("Largest is: " + b);
} else if ((c >= d) && (c >= e)) { // c >= d,e
System.out.println ("Largest is: " + c);
} else if (d >= e) { // d >= e
System.out.println ("Largest is: " + d);
} else { // e > d
System.out.println ("Largest is: " + e);
}
keeping in mind that, once you decide a
(or any of the others in later steps) isn'tthe largest, you never need to check it again, as one of the others willbe larger than it.
同时要注意的是,一旦你决定a
(或任何其他人在后面的步骤)不是最大的,你永远需要再次检查,因为其他的一个将是比它大。
Or you can use the facilities of the Java standard Math
package, where Math.max(a,b)
will give you the largest of the values from a
and b
:
或者,您可以使用 Java 标准Math
包的工具,其中Math.max(a,b)
将为您提供来自a
和的最大值b
:
int largest = Math.max(a,Math.max(b,Math.max(c,Math.max(d,e))));
Here, you define the largest of all five numbers as the maximum of the pair {a, maximum-of-bcde}
then use a similar method to work out maximum-of-bcde
as the maximum of the set {b, maximum-of-cde}
and so on.
在这里,您将所有五个数字中的最大值定义为该对的最大值,{a, maximum-of-bcde}
然后使用类似的方法计算出maximum-of-bcde
该集合的最大值,{b, maximum-of-cde}
依此类推。
Or, in other words, choose the largest from {d,e}
and call it x
. Then choose the largest from {c,x}
and call it y
. Then the largest from {b,y}
and call it z
. Finally the largest from {a,z}
and that's your largest value of the five.
或者,换句话说,从中选择最大的{d,e}
并将其称为x
。然后从中选择最大的{c,x}
并调用它y
。然后最大的自{b,y}
和调用它z
。最后是最大的{a,z}
,这是五个中最大的值。
Though, to be honest, if you're on chapter one of an introductory text, it probably hasn't covered much in the Java standard libraries yet.
不过,老实说,如果您正在阅读介绍性文本的第一章,它可能还没有涉及 Java 标准库中的太多内容。
But, if you're after a method where it's perhaps easierfor a beginner to understand the flow, I don't think you can go past this one:
但是,如果您追求一种初学者可能更容易理解流程的方法,我认为您无法超越这个方法:
int maxOfFive (int a, int b, int c, int d, int e) {
int largest = a;
if (b > largest) largest = b;
if (c > largest) largest = c;
if (d > largest) largest = d;
if (e > largest) largest = e;
return largest;
}
This is basic selection of the largest value as a person would do it,scanning the list one by one and just remembering which value was the highest, then returning that.
这是一个人会做的最大值的基本选择,逐个扫描列表并记住哪个值最高,然后返回。
Or, if you haven't learned about functions yet (and reverting to your original variables), just implement the same code withouta function call:
或者,如果您还没有了解函数(并恢复到您的原始变量),只需实现相同的代码而不调用函数:
int largest = firstInt;
if (secondInt > largest) largest = secondInt;
if (thirdInt > largest) largest = thirdInt;
if (fourthInt > largest) largest = fourthInt;
if (fifthInt > largest) largest = fifthInt;
System.out.println ("Largest is: " + largest);
I believe that's probably only using stuff you've already indicated that you know about (variables, single-condition if
statement, and output).
我相信这可能只使用了您已经表示知道的东西(变量、单条件if
语句和输出)。
回答by JClassic
The only way to compare multiple if statements is to use:
比较多个 if 语句的唯一方法是使用:
if(integer > 1 && integer > 2 && integer > 3) //etc
Otherwise you can have:
否则你可以有:
if(integer>1)
if(integer>2) //etc
You cannot list multiple integers in an if statement using commas
不能使用逗号在 if 语句中列出多个整数
回答by Salah
You can use the following approach:
您可以使用以下方法:
if (one > two && one > three)
System.out.println("%d is the largest number!", one);
Or the best solution, fill your values in array, then iterate over them like:
或者最好的解决方案,在数组中填充你的值,然后像这样迭代它们:
for(int i=1; i<list.length; i++) { //suppose the first element is one
if(one <= list[i]) {
break;
}
System.out.println("%d is the largest number!", one);
}
回答by user3437460
Using multiple integers to store number does work BUT it is not the way to code. You should at least use an array.
使用多个整数来存储数字确实有效,但它不是编码的方式。你至少应该使用一个数组。
Array crash course:
阵列速成课程:
Array is a group of variables with similar datatype.
数组是一组具有相似数据类型的变量。
To create an array:
创建数组:
<datatype>[] arrayName = new <datatype>[size];
//Example
int[] myValues = new int[5]; //create 5 int variables.
myValues[0]; //is similar to your firstInt
myValues[1]; //is similar to your secondInt
myValues[2]; //is similar to your thirdInt
myValues[3]; //is similar to your forthInt
myValues[4]; //is similar to your fifthInt
Using an array, you can just use a for loop to iterate through the variables. Doing it simultaneously (I guess you mean iteratively), you need arrays.
使用数组,您可以只使用 for 循环来遍历变量。同时做(我猜你的意思是迭代),你需要arrays。
Solution 1:
解决方案1:
//To find the largest
int largest = array[0];
for(int x=0; x<5; x++)
if (array[x] > largest)
largest = array[x];
//To find the smallest
int smallest= array[0];
for(int x=0; x<5; x++)
if (array[x] < smallest)
smallest= array[x];
Alternatively, without using loop and array (Not so elegant but might be what you want):
Use Math.max()
or Math.min()
.
或者,不使用循环和数组(不太优雅,但可能是您想要的):使用Math.max()
或Math.min()
。
Solution 2:
解决方案2:
int largest = Math.max(var1, var2);
largest = Math.max(largest, var3);
largest = Math.max(largest, var4);
largest = Math.max(largest, var5);
Solution 3:
解决方案3:
Lastly, withoutusing loopsand arrays.
最后,不使用循环和数组。
int largest = 0;
if(firstInt > secondInt)
largest = firstInt
else
largest = secondInt;
if(thirdInt > largest)
largest = thirdInt;
if(forthInt > largest)
largest = forthInt;
if(fifthInt > largest)
largest = fifthInt;
To find smallest, just change the operator from >
to <
.
要找到最小的,只需将运算符从 更改>
为<
。
回答by Adrian Shum
I believe what you are trying to do is
我相信你想做的是
if (i1 > i2
&& i1 > i3
&& i1 > i4
&& i1 > i5) {
// i1 is the largest
}
It does not look very elegant though. Normally we would want to store multiple integer in a List
or an array, and find the biggest value by sorting it or iterate through the list.
不过看起来不是很优雅。通常我们希望在一个List
或一个数组中存储多个整数,并通过对其进行排序或遍历列表来找到最大值。
回答by Gaurav Dave
Create an array of given 5 numbers, and try this:
创建一个给定 5 个数字的数组,然后试试这个:
int numbers[] = new int[]{1,2,3,4,5};
//assign first element of an array to largest and smallest
int smallest = numbers[0];
int largetst = numbers[0];
for(int i=1; i< numbers.length; i++)
{
if(numbers[i] > largetst)
largetst = numbers[i];
else if (numbers[i] < smallest)
smallest = numbers[i];
}
System.out.println("Largest Number is : " + largetst);
System.out.println("Smallest Number is : " + smallest);
回答by SubOptimal
Depending on how you want to use your variable after the assignment you also might create an array and sort it
根据您在赋值后如何使用变量,您还可以创建一个数组并对其进行排序
int firstInt = 4;
int secondInt = 2;
int thirdInt = 3;
int fourthInt = 1;
int fifthInt = 5;
int[] arr = new int[5];
arr[0] = firstInt;
arr[1] = secondInt;
arr[2] = thirdInt;
arr[3] = fourthInt;
arr[4] = fifthInt;
Arrays.sort(arr);
System.out.println("smallest = " + arr[0]);
System.out.println("largest = " + arr[arr.length - 1]);
回答by Muhammed Refaat
I don't know how simple chapter1 is and what is the functionalists that you didn't study yest, but simple define two variables and give them min and max value:
我不知道第 1 章有多简单,也不知道你之前没有研究过的功能主义者是什么,但简单地定义两个变量并赋予它们最小值和最大值:
int smallest = firstInt;
int largest = secondInt;
if(firstInt > secondInt ){
largest = firstInt;
if(thirdInt > firstInt ){
largest = thirdInt;
if(fourthInt > thirdInt ){
largest = fourthInt;
if(fifthInt > fourthInt){
largest = fifthInt;
}
}
}
}
if(secondInt < firstInt){
smallest= secondInt;
if(thirdInt < secondInt){
smallest = thirdInt;
if(fourthInt < thirdInt ){
smallest = fourthInt;
if(fifthInt < fourthInt){
smallest = fifthInt;
}
}
}
}
System.out.println(smallest);
System.out.println(largest);
回答by Kartic
I would suggest if you know the number of integers to compare use array instead. Below is a sample code -
如果您知道要比较的整数数量,我建议您改用数组。下面是一个示例代码 -
This is not actual answer as I am not using if statement. Though this is one way to get what you want. As you are new in java, wanted to share my approach.
这不是实际答案,因为我没有使用 if 语句。虽然这是获得你想要的东西的一种方式。由于您是 Java 新手,想分享我的方法。
import java.util.Arrays;
public class JavaTest {
public static void main(String[] args) {
int values[] = {2,6,10,4,8};
Arrays.sort(values);
System.out.println("Min value : "+values[0]);
System.out.println("Max value : "+values[values.length-1]);
}
}
Have a great time with java.
玩得很开心。