-3

I have a do while loop that asks for 2 forms of input 3 times.

I thought about putting these inputs into 2 arrays to be output later, but it ain't working.

Here's my code for you to look at:

int i = 0;
do {
   System.out.print("Enter a name ");
   String name = scanner.nextLine();

   System.out.print("Enter age ");
   String age = input.nextLine();
   newAge = Integer.parseInt(age);
   i++;
} while (i <= 3);

I want to output the values as such:

Names are: Name1; Name2; Name3

But I want to add the 3 ages together to make a totalAge variable.

  • 2
    You "thought" about putting the inputs into arrays, but did you actually try writing code that did that? If so, please post the code you tried. – ajb Jun 25 '16 at 15:49
  • 1
    You say you tried arrays, but there are none in your code. Show us the code you tried that isn't working. – takendarkk Jun 25 '16 at 15:50
  • That's why I posted on here, I don't know how to get started. – user6512771 Jun 25 '16 at 15:52
  • 6
    Good place to start then: [Java Tutorials](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html) – Jorn Vernee Jun 25 '16 at 15:53

2 Answers2

-2

You can declare two arrays for name and age inputs, or you can create a class that holds them both, call it Person or something like that and create an array of these.

class Person {
    public String name;
    public Integer age;
}

You don't need a do-while loop, it will look better with a for, or even better with enhanced for:

int personsAmount = 3;
Person[] persons = new Person[personsAmount];
for (Person person : persons) {
    person = new Person();

    System.out.print("Enter a name ");
    person.name = scanner.nextLine();

    System.out.print("Enter age ");
    person.age = Integer.parseInt(scanner.nextLine());
}
Community
  • 1
  • 1
Jezor
  • 3,253
  • 2
  • 19
  • 43
  • @Shank So you think a Java course or a tutorial would teach arrays before arbitrary classes? Would be funny. – Tom Jun 25 '16 at 16:00
  • Albeit I don't think that classes are confusing for newbies, this answer isn't working anyway. But it proofs that [Java uses pass-by-value](http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value). – Tom Jun 25 '16 at 16:07
-2
int i = 0;
String[] name = new String[3];
int[] age = new int[3];
do {
   System.out.print("Enter a name ");
   name[i] = scanner.nextLine();

   System.out.print("Enter age ");
   age[i] = Integer.parseInteger(input.nextLine());
   ;
   i++;
} while (i <= 3);
Shiro
  • 2,610
  • 2
  • 20
  • 36