编写一个Java程序来查找数组中的最小数,并提供示例。或者编写一个使用for循环和函数的程序来打印或返回给定数组中的最小数。
Java 程序使用 for 循环查找数组中的最小数
在此最小数组数示例中,我们允许用户输入大小和数组项。接下来,我们将第一个数组项指定为最小项,并将其与其它项进行比较。在 For 循环 中,我们使用 If 语句 来检查条件 Sml > sm_arr[i]。如果任何其他元素小于该值,我们将变量值替换为该项。
import java.util.Scanner;
public class Simple {
private static Scanner sc;
public static void main(String[] args) {
int Size, i, Sml, Pos = 0;
int[] sm_arr = new int[10];
sc = new Scanner(System.in);
System.out.print("\n Please Enter the size : ");
Size = sc.nextInt();
System.out.format("\nPlease Enter %d Items : ", Size);
for(i = 0; i < Size; i++) {
sm_arr[i] = sc.nextInt();
}
Sml = sm_arr[0];
for(i = 1; i < Size; i++) {
if(Sml > sm_arr[i]) {
Sml = sm_arr[i];
Pos = i;
}
}
System.out.format("\nSmallest element in an Array = %d\n", Sml);
System.out.format("Index position of the Smallest element = %d", Pos);
}
}

使用函数查找最小数组数
在此示例 代码 中,我们创建了一个单独的函数,该函数从给定的 数组 中返回最小的数字。请参考 C 语言程序查找最小数字 的文章,以了解 Java 示例中的 For 循环迭代。
package ArrayPrograms;
import java.util.Scanner;
public class SmEleUsingMethod {
private static Scanner sc;
static int Size, i, Sm, Position = 0;
public static void main(String[] args) {
sc = new Scanner(System.in);
System.out.print("\nPlease Enter the SM size : ");
Size = sc.nextInt();
int[] sm_arr = new int[Size];
System.out.format("\nEnter SM %d Items : ", Size);
for(i = 0; i < Size; i++) {
sm_arr[i] = sc.nextInt();
}
Sm = SmlstEle(sm_arr);
System.out.format("\nSmallest element in SM = %d", Sm);
}
public static int SmlstEle(int[] sm_arr ) {
Sm = sm_arr[0];
for(i = 1; i < Size; i++) {
if(Sm > sm_arr[i]) {
Sm = sm_arr[i];
Position = i;
}
}
return Sm;
}
}
Please Enter the SM size : 8
Enter SM 8 Items : 10 8 11 22 6 9 22 67
Smallest element in SM = 6