简体   繁体   English

从数组中打印单个值?

[英]Printing individual values from an array?

I'm working on a school project where I need to have the user input a list of family members and their age and state using three arrays. 我正在做一个学校项目,我需要让用户使用三个数组输入家庭成员及其年龄和州的列表。 Program needs to print the average of age of the family and names of anyone living in texas. 程序需要打印家庭平均年龄和居住在德克萨斯州的任何人的姓名。 I currently have everything working except after several hours of reaserch I'm still unable to figure out how to print the names of those living in tx. 目前,我可以进行所有工作,但是经过几个小时的重新测试之后,我仍然无法弄清楚如何打印那些居住在tx中的人的名字。 Any pointers would be greatly appreciated. 任何指针将不胜感激。 If this is a duplicate, I'll happily delete, thus far I'm unable to find a solution that I could understand. 如果这是重复项,我会很乐意删除,到目前为止,我找不到我能理解的解决方案。 Thanks in advance! 提前致谢!

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

 }
}

how to print the names of those living in tx ? how to print the names of those living in tx

All you need to do is this: 您需要做的就是:

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

Try this: 尝试这个:

int i = 0;

while (i < name.length)
{
     System.out.printf("%d", age[i]);
     i++;
}
for (int i = 0; i < num.length; i++)
    if (state[i].equals("tx")) System.out.println(name[i]);

Change name.length to num.length too. 也将name.length更改为num.length。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM