如何将一个数组输入与另一个数组输入相关联? [英] How do I relate one array input to another?

查看:39
本文介绍了如何将一个数组输入与另一个数组输入相关联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有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.");
}

这篇关于如何将一个数组输入与另一个数组输入相关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆