• Sign in to Neowin Faster!

    Create an account on Neowin to contribute and support the site.

  • 0
Sign in to follow this  

How to get the name of the oldest person with java array and split string?


bimyou    0
Posted (edited)

I've been staring at this problem for too long.. This is an exercise from https://java-programming.mooc.fi/part-3/4-using-strings and I have to get the name of the oldest person through splitting the strings, and finding the name with the oldest age.


Sample Input: Johnny, 5

                          Rose, 19

                          Sam, 10

Desired Output: Rose



Any help would genuinely be appreciated. Thanks!




import java.util.Scanner;

public class NameOfTheOldest {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        String name = "";

        while (true) {

            String input = scanner.nextLine();

            if (input.equals("")) {



            String[] pieces = input.split(",");

            int age = Integer.valueOf(pieces[1]);

            int oldest = 0;

            if (age > oldest) {

                name = pieces[0];

                oldest = age;


        System.out.println("Name of the oldest: " + name);

Edited by bimyou

Share this post

Link to post
Share on other sites

2 answers to this question

Recommended Posts

  • 1
+virtorio    3,270

I assume the problem is that it's always printing the last name you entered.
Here's a hint, there's an issue with where you've declared the "oldest" variable. 

Share this post

Link to post
Share on other sites
  • 0
JaykeBird    106

The issue I always have with things like this is I end up creating code that gets the job done, but is probably not what they're looking for at this stage. I'd personally just create a Person class and parse each string into its own instance of the class, and then compare it that way lol. It's a solution that totally works (and is also expandable), but it's a more advanced solution that wouldn't really be considered or taught at this point of such a course.


Anyway, sometimes it helps to just "run" the code by hand. Use a pencil and paper and just go line by line as if you were the computer, following the loops (like the while (true) loop you have) and writing variables and how they change as you go along. For logic questions like this, it can be a nice strategy to use. Actual programmers do a similar thing, it's called "stepping through code" - it's just done using a computer tool called a debugger rather than using a pencil and paper.

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.