从阵列打印单个值?

时间:2014-11-30 22:30:50

标签: java arrays

我在一个学校项目上工作,我需要让用户输入一个家庭成员列表及其使用三个阵列的年龄和状态。计划需要打印家庭的平均年龄和生活在德克萨斯州的人的姓名。我目前已经完成了所有工作,除非经过几个小时的研究,我仍然无法弄清楚如何打印生活在tx中的人的姓名。任何指针都将非常感激。如果这是重复的,我会高兴地删除,到目前为止,我无法找到我能理解的解决方案。提前谢谢!

import java.util.Scanner;

public class Family
{
public static void main ( String [] args )
{
    int age_total = 0;
    int counter = 0;
    String stop = "stop";
    int num = 0;
    double age_average =0;

    Scanner scan = new Scanner (System.in);

    System.out.println("How many family members would you like to add?");
    num = scan.nextInt();

    String [] name = new String [num]; 
    int [] age = new int [num];
    String [] state = new String[num];

    for ( int i = 0; i < name.length; i++ ) 
    {               
        System.out.println("Please enter a family member's name:");
        name[i] = scan.next();

        System.out.println("Thanks, please enter his/her age here:");
        age[i] = scan.nextInt();

        System.out.println("Awesome! Please enter the two letter abbreviation "
                             "for the state where he/she currently resides? ");
        state[i] = scan.next();

        age_total += age[i]; 
        counter ++;
    }   


for ( int i = 0; i < name.length; i++ )
{
  System.out.println ( name[i] );
}

    age_average = age_total/counter;

    System.out.println("The average age is " + age_average + " years old."); 

 }
}

3 个答案:

答案 0 :(得分:2)

how to print the names of those living in tx

您需要做的就是:

for (int i = 0; i < name.length; i++)
    if ("tx".equals(state[i])) System.out.println(name[i]);

答案 1 :(得分:-1)

试试这个:

int i = 0;

while (i < name.length)
{
     System.out.printf("%d", age[i]);
     i++;
}

答案 2 :(得分:-1)

for (int i = 0; i < num.length; i++)
    if (state[i].equals("tx")) System.out.println(name[i]);

也将name.length更改为num.length。