且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-06-17 17:25:39

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

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

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.");
}