1

I am trying to write a java program with 2 arrays 1 for name (String) and the other representing age (integer) the program should iterate and ask for a max of 10 names and ages of each, then display all array items as well as max and min ages of each, or unless the user enters 'done' or 'DONE' mid-way through.

I have the following code although struggling to loop around and ask user for names and ages x10.

Any suggestions?

Thank you.

import java.util.Scanner;
public class AgeName {
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);

        int numTried = 1;  
        int ageTried = 1;
        boolean stop = false;
        String name = "";

        String[] num = new String[10];
        int[] age = new int[10];

        while(numTried <= 10 && ageTried <=10 && !stop){
            System.out.print("Enter name " + numTried + ": ");
            name = input.nextLine();

            System.out.print("Now enter age of " + name + ": ");
            int userAge = input.nextInt();

            if(name.toUpperCase().equals("DONE")){
                stop = true;
            }else{
                num[numTried - 1] = name;
                age[ageTried -1] = userAge;
            }

            numTried ++;
            ageTried ++;
        }

        for(String output : num){
            if(!(output == null)){
                System.out.print(output + "," );
            }
        }

        input.close();
    }
}
APPAPA
  • 25
  • 1
  • 6

2 Answers2

1

You can use a Map<String,Integer>:

HashMap<String, Integer> map = new HashMap<String, Integer>();
String[] num = new String[10];
for (int i = 0; i < 10; i++) {
    System.out.print("Enter name " + numTried + ": ");
    name = input.nextLine();

    System.out.print("Now enter age of " + name + ": ");
    int userAge = input.nextInt();
    num[i] = name;
    map.put(name, userAge);
}

for (String output : num) {
    if (!(output == null)) {
        System.out.print(output + ","+ map.get(output));
    }
}

Map as its name suggests allows you to map one object type to another. the .put() method adds a record that contains a pair of String and an integer and maps the string to the int.
The String has to be UNIQUE!!

ItamarG3
  • 4,092
  • 6
  • 31
  • 44
0

You should ask in any iteration if the user is done. For example you could set a string variable as answer = "NO", and ask the user at the end of any iteration if he is done. If you try this remember to replace stop variable with answer at your iteration block condition.

System.out.println("Are you done: Choose -> YES or NO?");
answer = input.nextLine();
if (answer == "YES")
    break;
Man H
  • 77
  • 1
  • 11