编写一个 Java 程序来查找数组中的最大值和最小值,并附带示例。或如何编写一个程序来查找给定数组中的最高和最低元素或项。
Java 程序使用 for 循环查找数组中的最大值和最小值
此 Java 示例使用 For 循环 迭代数组项,并使用 Else If 语句 提取项。第一个 If 语句检查并查找最小的数字,else if 语句查找最大的数字。请参阅 查找最大数组号的 Java 程序 和 查找最小数组号的 Java 程序 文章以了解代码。
首先,我们将数组的第一个索引值分配给 Smallest 和 Largest 变量。接下来,Else if 语句将每个数组项与这些值进行比较。如果任何其他项小于 Smallest 变量,则将其打印为最小值。如果任何其他项大于 Largest 变量值,则将其打印为最大值。此过程从第一项开始,直到最后一项。
import java.util.Scanner;
public class LargestSmallestArrayItem1 {
private static Scanner sc;
public static void main(String[] args) {
int Size, i, Largest, Smallest, min_Position = 0, max_Position = 0;
sc = new Scanner(System.in);
System.out.print("\nPlease Enter the SMLRG Array size = ");
Size = sc.nextInt();
int[] smlLrg_arr = new int[Size];
System.out.format("\nEnter SMLRG Array %d elements = ", Size);
for(i = 0; i < Size; i++) {
smlLrg_arr[i] = sc.nextInt();
}
Smallest = smlLrg_arr[0];
Largest = smlLrg_arr[0];
for(i = 1; i < Size; i++) {
if(Smallest > smlLrg_arr[i])
{
Smallest = smlLrg_arr[i];
min_Position = i;
}
else if(Largest < smlLrg_arr[i])
{
Largest = smlLrg_arr[i];
max_Position = i;
}
}
System.out.format("\nLargest element in SMLRG Array = %d", Largest);
System.out.format("\nIndex position of the Largest element = %d", max_Position);
System.out.format("\n\nSmallest element in SMLRG Array = %d", Smallest);
System.out.format("\nIndex position of the Smallest element = %d", min_Position);
}
}

Java 程序使用函数查找数组中的最大值和最小值
在此 代码 示例中,我们创建了单独的函数来查找和返回给定 数组 中的最小和最大项。
import java.util.Scanner;
public class LaSmArrItem2 {
private static Scanner sc;
static int Size, i, La, Sm, min_Position = 0, max_Position = 0;
public static void main(String[] args) {
sc = new Scanner(System.in);
System.out.print("\nPlease Enter the SMLRG size = ");
Size = sc.nextInt();
int[] smlLrg_arr = new int[Size];
System.out.format("\nEnter SMLRG %d elements = ", Size);
for(i = 0; i < Size; i++) {
smlLrg_arr[i] = sc.nextInt();
}
LaEle(smlLrg_arr);
SmEle(smlLrg_arr);
}
public static void LaEle(int[] lrg_arr ) {
La = lrg_arr[0];
for(i = 1; i < Size; i++) {
if(La < lrg_arr[i]) {
La = lrg_arr[i];
max_Position = i;
}
}
System.out.format("\nLargest element in SMLRG = %d", La);
System.out.format("\nIndex position of it = %d", max_Position);
}
public static void SmEle(int[] sm_arr ) {
Sm = sm_arr[0];
for(i = 1; i < Size; i++) {
if(Sm > sm_arr[i]) {
Sm = sm_arr[i];
min_Position = i;
}
}
System.out.format("\n\nSmallest element in SMLRG = %d", Sm);
System.out.format("\nIndex position of it = %d", min_Position);
}
}
最大和最小数组项输出。
