如何将一个数组输入与另一个数组输入相关联?

2022-03-15 00:00:00 arrays sorting java java.util.scanner
假设我有2个扫描仪填充的数组,name[]age[]。每一张都是按顺序填写的。如果我要查找数组中年龄最大的人,我如何使用数组打印出他们的姓名和年龄? 例如,age[]中最大的条目是78。有没有办法将其与name[]数组关联以将其打印出来?

参考编码:

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("How many entries ?");

    int entries;
    do {
        entries = input.nextInt();
        if (entries < 1) {
            System.out.println("please enter a valid number!");
        }
    } while (entries < 1);

    String[] name = new String[entries];
    String[] gender = new String[entries];
    int[] age = new int[entries];

    for (int i = 0; i < entries; i++) {
        System.out.println("Enter the name of person No" + (i + 1) + ".");
        name[i] = input.next();
    }

    double ageSum = 0;
    int max = 0;
    for (int i = 0; i < entries; i++) {
        System.out.println("How old is " + name[i] + " ?");
        age[i] = input.nextInt();
        ageSum += age[i];
        max = Math.max(max, age[i]);
    }

    System.out.println("the oldest person is "
            + name[] + " whose " + max + " years old.");
}

解决方案

假设您的数组具有相同的大小和与名称对应的期限,那么您可以检查最高期限并存储具有最高期限的元素的索引。

那么您的名字就在这个指示符上。

int highestAgeIndice = 3; //indice of element with age 97 as example

names[highestAgeIndice] // the corresponding name

计算最高年龄并存储其索引

int max = 0;
int highestInd = 0;
for (int i = 0; i < age.length; i++) {
    if (age[i] > max) {
        max = age[i];
        highestInd = i;
    }
}

System.out.println("the oldest person is " +
        name[highestInd] + " whose " + max + " years old.");

代码

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("How many entries ?");

    int entries;
    do {
        entries = input.nextInt();
        if (entries < 1) {
            System.out.println("please enter a valid number!");
        }
    } while (entries < 1);

    String[] name = new String[entries];
    String[] gender = new String[entries];
    int[] age = new int[entries];

    for (int i = 0; i < entries; i++) {
        System.out.println("Enter the name of person No" + (i + 1) + ".");
        name[i] = input.next();
    }

    double ageSum = 0;
    for (int i = 0; i < entries; i++) {
        System.out.println("How old is " + name[i] + " ?");
        age[i] = input.nextInt();
        ageSum += age[i];
    }

    int max = 0;
    int highestInd = 0;
    for (int i = 0; i < age.length; i++) {
        if (age[i] > max) {
            max = age[i];
            highestInd = i;
        }
    }
    System.out.println("the oldest person is " +
            name[highestInd] + " whose " + max + " years old.");
}

相关文章