编写一个 Java 程序来查找数组的第二大数字,并提供示例,或查找给定数组中的第二大元素或项。
Java 程序使用 for 循环查找数组中的第二大数字
此 Java 数组示例允许用户输入 secLrg_arr 的大小和各项。接下来,for 循环会遍历数组中的各项。在循环中,我们使用 Else If 语句来查找此 secLrg_arr 中的最大和第二大项。
import java.util.Scanner;
public class Simple {
private static Scanner sc;
public static void main(String[] args) {
int Size, i, first, snd, lg_Position = 0;
sc = new Scanner(System.in);
System.out.print("\nPlease Enter the SEC LRG size : ");
Size = sc.nextInt();
int[] secLrg_arr = new int[Size];
System.out.format("\nEnter SEC LRG %d elements : ", Size);
for(i = 0; i < Size; i++)
{
secLrg_arr[i] = sc.nextInt();
}
first = snd = Integer.MIN_VALUE;
for(i = 0; i < Size; i++)
{
if(secLrg_arr[i] > first) {
snd = first;
first = secLrg_arr[i];
lg_Position = i;
}
else if(secLrg_arr[i] > snd && secLrg_arr[i] < first)
{
snd = secLrg_arr[i];
}
}
System.out.format("\nMaximum Value in SEC LRG Array = %d", first);
System.out.format("\nMaximum Value Index position = %d", lg_Position);
System.out.format("\n\nSecond Largest Item in SEC LRG Array = %d", snd);
}
}

使用函数查找数组的第二大数字
在此 代码中,我们创建了一个单独的 SecLargElem 函数。它有助于查找并返回给定数组中的第二大项。
package ArrayPrograms;
import java.util.Scanner;
public class Example {
private static Scanner sc;
public static void main(String[] args) {
int Sz, i;
sc = new Scanner(System.in);
System.out.print("\nPlease Enter the SEC LRG size : ");
Sz = sc.nextInt();
int[] secLrg_arr = new int[Sz];
System.out.format("\nEnter SEC LRG %d elements : ", Sz);
for(i = 0; i < Sz; i++)
{
secLrg_arr[i] = sc.nextInt();
}
SecLargElem(secLrg_arr, Sz);
}
public static void SecLargElem(int[] secLrg_arr, int Sz) {
int i, first, sec, lg_Position = 0;
first = sec = Integer.MIN_VALUE;
for(i = 0; i < Sz; i++)
{
if(secLrg_arr[i] > first) {
sec = first;
first = secLrg_arr[i];
lg_Position = i;
}
else if(secLrg_arr[i] > sec && secLrg_arr[i] < first)
{
sec = secLrg_arr[i];
}
}
System.out.format("\\nHighest Item in SEC LRG = %d", first);
System.out.format("\nIndex position of Highest = %d", lg_Position);
System.out.format("\n\nSecond Largest Item in SEC LRG = %d", sec);
}
}
Please Enter the SEC LRG size : 11
Enter SEC LRG 11 elements : 10 20 44 77 89 95 200 22 88 250 111
Highest Item in SEC LRG = 250
Index position of Highest = 9
Second Largest Item in SEC LRG = 200