[英]Java if-statement homework
我有作业要求我找到 4 个输入数字中最大的 2 个。
我尝试了一个 if 语句,但我认为我的做法是错误的。 我必须使用 if 语句或 while 循环。 我该如何继续?
if ((a>b && b>c && c>d)||(a>b && b>d && d>c)){
System.out.println("max1 is : " + a);
System.out.println("max2 is : " + b);}
else if ((b>a && a>c && c>d)||(b>a && a>c && d>c) ){
System.out.println("max1 is : " + b);
System.out.println("max2 is : " + a);}
if ((c>a && a>b && b>d)||(c>a && a>b && d>b)){
System.out.println("max1 is : " + c);
System.out.println("max2 is : " + a);}
使用 java 原始数组:
int[] num = {a, b, c, d};
Arrays.sort(num);
System.out.println("Largest is : " + num[3]);
System.out.println("Second Largest is : " + num[2]);
// 最大的两个数字将占据数组中的最后两个位置 3 和 2。
只需将参数放入数组中,对该数组进行排序并显示最后的元素
public static void main(String[] args) {
dispayMax(5, -13, 7, 88);
}
public static void dispayMax(int a, int b, int c, int d){
int[] array = {a, b, c, d};
Arrays.sort(array);
int length = array.length;
System.out.println("max1 is : " + array[length -2]);
System.out.println("max2 is : " + array[length -1]);
}
您可以使用集合来避免多次编写此类<,>
条件。 在这种情况下,集合或数组可以派上用场。
min1 - 最小的数字,min2 - 第二小。 它们的初始值设置为可能的最大 integer 值
在for循环中,对于每一个元素,如果该元素小于min1值,则将当前min1值赋给min2,并将min1设置为元素本身。 如果元素值小于 min2 但不小于 min1,则将其值赋给 min2,min1 保持不变。
使用它的方法之一是。 :
int min1 = Integer.MAX_VALUE, min2 =Integer.MAX_VALUE;
int[] arr = {a,b,c,d}; // created an array with the four elements
for(int i=0;i<arr.length;i++) {
if(min1>arr[i]) { //array is minimising the checks to be written
min2=min1;
min1=arr[i];
}else if(min2>arr[i]) {
min2=arr[i];
}
}
import java.util.Arrays;
public class Homework{
public static void main(String []args){
int myArray[] = {4, 10, 1, 100}; //insert your 4 numbers
Arrays.sort(myArray);
System.out.println("The max is: " + myArray[3]);
System.out.println("The 2nd max is: " + myArray[2]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.