为什么你需要120个不同的if语句?
你已经得到了关于调用数学函数来完成工作的答案,我已经使用了一种简单的排序方法来完成工作。
您的问题的解决方案分为以下几种:
1)读取用户输入
2)排序
3)从排序的束中找出最大最小值
码:
//Import relevant packages
import java.io.BufferedReader;
import java.io.InputStreamReader;
class MinMax {
public static void main(String[] args) {
int[] myArray = new int[5]; //Array to hold user input of 5 integers
int[] resultArray; //reference var to hold the resultArray object
//Buffered reader is wrapped around the input stream reader to read user input
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
//Loop to get user input, 5 times
for (int i=1;i<=5;i++){
System.out.println("Enter a number: ");
try{
myArray[i-1] = Integer.parseInt(reader.readLine()); //String to integer the user input
}
catch(Exception e){
e.printStackTrace();
}
}
//Calling the function sortme() to do the sorting
resultArray = sortme(myArray);
//After bubble sort has sorted the input array, the min is the first and max is the last, values of the array
System.out.println("The min is: " + resultArray[0] + ", and the max is: "+myArray[4]);
}
//Bubble sort
static int[] sortme(int[] array){
int temp;
for (int i=(array.length-1);i>=0;i--){
for (int j=1;j<=i;j++){
if (array[j-1] > array[j]){
temp = array[j-1];
array[j-1] = array[j];
array[j] = temp;
}
}
}
return array;
}输入:
1 4 6 3 9输出:
The min is: 1, and the max is: 9编辑
Yetti先生指出了排序方法的低效率,因为它首先不需要。这是迭代方法:
import java.io.BufferedReader;
import java.io.InputStreamReader;
class MinMax_nosort {
public static void main(String[] args) {
int[] myArray = new int[5]; //Array to hold user input of 5 integers
//Buffered reader is wrapped around the input stream reader to read user input
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
//Loop to get user input, 5 times
for (int i=1;i<=5;i++){
System.out.println("Enter a number: ");
try{
myArray[i-1] = Integer.parseInt(reader.readLine()); //String to integer the user input
}
catch(Exception e){
e.printStackTrace();
}
}
minmax(myArray);
}
static void minmax(int[] array){
int max, min;
max = min = array[0];
for (int i=1;i
if (array[i] > max)
max = array[i];
else if(array[i] < min)
min = array[i];
}
System.out.println("The min is:" + min + " and the max, is: " + max);
}输入:
1 4 6 3 9输出:
The min is:1 and the max, is: 9