我的代码要求用户输入动物物种的值,然后将其显示给他们。我只需要最后添加一个部分,它也可以告诉用户最濒危的动物(输入数字最低的动物)。我环顾了一些地方,并使用 x< min 或 x=MAX_VALE 等进行 triec。我似乎无法使任何工作发挥作用。有没有更适合我的程序的方法?
import java.util.Scanner;
public class endangered
{
public static void main(String[] param)
{
animal();
System.exit(0);
}
public static void animal()
{
int[] array = new int[5];
int j = 0;
String[] names = {"Komodo Dragon" , "Manatee" , "Kakapo" , "Florida Panther" , "White Rhino"};
System.out.println("Please enter the number of wild Komodo Dragons, Manatee, Kakapo, Florida Panthers and White Rhinos.");
Scanner scan = new Scanner(System.in);
for (int i=0; i<=4; i++)
{
while(scan.hasNextInt())
{
array[j] = scan.nextInt();
int max = array[j];
j++;
if(j==5)
{
System.out.println(array[0] + ", " + names[0]);
System.out.println(array[1] + ", " + names[1]);
System.out.println(array[2] + ", " + names[2]);
System.out.println(array[3] + ", " + names[3]);
System.out.println(array[4] + ", " + names[4]);
}
}
}
}
}
最佳答案
您可以做的是使用内置方法对数组进行排序,然后检索最后一个值(最大)和第一个值(最小)。
Arrays.sort(array);
int max = array[array.length - 1];
int min = array[0];
有关 Java 的 Arrays
类中的 sort
方法的更多信息,以下是其具体用途的描述,
public static void sort(int[] a)
Sorts the specified array into ascending numerical order.
Parameters: a - the array to be sorted
如果你想获取相应的动物,那么我建议忽略上述内容并使用 Java 8 中的流。将 String 和 int 数组合并为一个 2D String 数组。使行等于动物数量,列等于 2(例如:对于 5 只动物,String[][] array = new String[5][2]
)。对于二维数组中的每一行,第一个元素应该是动物,第二个元素应该是大小(例如:String [][] array = {{"fox", "1"},{"鹿","0"},{"熊", "2"}}
)。下面将返回一个按升序排序的二维数组,并为您提供相应的动物,
String[][] sorted = Arrays.stream(array)
.sorted(Comparator.comparing(x -> Integer.parseInt(x[1])))
.toArray(String[][]::new);
String smallestAnimal = sorted[0][0]; //name of smallest animal
String smallest = sorted[0][1]; //population of smallest animal
String biggestAnimal = sorted[sorted.length - 1][0]; //name of biggest animal
String biggest = sorted[sorted.length - 1][1]; //population of biggest animal
关于java - 我如何确定输入的最小值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39934311/