简体   繁体   中英

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. 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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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