• 0

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


Question

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("")) {

                break;

            }

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

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

            int oldest = 0;

            if (age > oldest) {

                name = pieces[0];

                oldest = age;

            }
        }

        System.out.println("Namehe oldest: " + name);
    }
}
 

Edited by bimyou

2 answers to this question

Recommended Posts

  • 1

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. 

  • 0

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.

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
  • Posts

    • Swatle AI — the smarter way to manage your teams, projects, and tasks now 75% off by Steven Parker Today's highlighted deal comes via our Apps + Software section of the Neowin Deals store, where you can save 75% off on Swatle All-in-One AI Assistant (Premium lifetime subscription). Stop over-hiring and overspending to meet your productivity goals. Swatle is all you need to achieve more with less. Swatle is an all-in-one AI solution designed to supercharge your productivity without over-hiring or overspending. Whether you're managing projects, automating repetitive tasks, or organizing your team's workflow, Swatle can help you achieve more with less. Powered by cutting-edge artificial intelligence, it adapts to your needs, streamlines operations, and eliminates inefficiencies so you can focus on what matters most—growing your business. With Swatle, working smarter isn’t just a goal—it’s your new reality. Let Swatle AI handle the necessary mundane tasks. SWATLE AI PROJECT ASSISTANT Step-by-Step Guidance: For every task you assign, either write step-by-step instructions yourself or let Swatle AI write on your behalf Skip the Standups: Ask Swatle AI about project progress and get instant, actionable updates—no daily meetings needed Accurate Time Estimates: Plan your day better by estimating the time required to complete your tasks Message Refinement: Send crystal clear messages; Swatle AI will rephrase your message & make it crisp and clear Project Quality Boost: Turn normal project descriptions into a crystal-clear description TEAM COLLABORATION MADE EASY Streamline Communication: Send & receive messages and updates within Swatle for real-time, tool-free collaboration Centralized Team Portfolios: Create dedicated portfolios to highlight your team's expertise & track their contributions effectively Conversational Task Creation: Instantly create tasks while having casual conversations with a single click. Make sure nothing falls through the crack Share Files & Feedback Directly: Eliminate scattered documents and email threads by sharing files and providing feedback directly in Swatle chat SWATLE TASKDESK Non-Technical Projects: Specifically designed for projects like marketing campaigns, content creation, and event planning Visualize Work Your Way: Manage tasks through Kanban boards, lists, Gantt charts, or Timelines—whatever fits your flow AI Task Assistant: Break down complex tasks into manageable subtasks quickly & easily Workload Tracking: View the workload of your team members & distribute tasks across the team to encourage a balanced workload. Proactive Notifications: Effortlessly keep your projects on track with timely, proactive notifications SWATLE DEVBOARD Technical Projects: Create unlimited sprints & backlogs for full control and visibility into every phase of your projects Burndown Chart: Provides a clear, real-time visual representation of your team's work remaining against the sprint timeline Set Goals, Create Sprints, Achieve More: Define your objectives and launch focused sprints that empower your team to concentrate on key tasks within short, impactful cycles Why choose Swatle? No Learning Curve: Swatle offers a remarkably easy-to-use interface. Empower your entire team to understand project progress without requiring technical expertise. Actionable Intelligence: Swatle turns raw project data into visualizations, like Assigned vs Completed charts, enabling focused analysis without manual effort. Proactively Mitigate Risks: Swatle visual dashboards make it easy to spot potential delays, bottlenecks, and resource imbalances, enabling you to take timely action and keep your projects on track. Ensure Resources Are Optimized: By visualizing workloads, you can strategically distribute tasks, promote a balanced environment, and prevent team burnout. Maintain Project Alignment & Stakeholder Confidence: Keep everyone from your internal team to clients and stakeholders on the same page with clear Gantt and Timeline views. Good to know Length of access: lifetime Redemption deadline: redeem your code within 30 days of purchase Access options: desktop or mobile Max number of device(s): unlimited Available to both NEW and Existing users Updates included This Swatle All-in-One AI Assistant (Premium lifetime subscription) normally costs $240, but this deal can be yours for just $59.99, that's a saving of $180. For full terms, specifications, and license info please click the link below. Get this lifetime Swatle Premium deal for just $59.99 (75% off) or learn more Although priced in U.S. dollars, this deal is available for digital purchase worldwide. We post these because we earn commission on each sale so as not to rely solely on advertising, which many of our readers block. It all helps toward paying staff reporters, servers and hosting costs. Other ways to support Neowin Whitelist Neowin by not blocking our ads Create a free member account to see fewer ads Make a donation to support our day to day running costs Subscribe to Neowin - for $14 a year, or $28 a year for an ad-free experience Disclosure: Neowin benefits from revenue of each sale made through our branded deals site powered by StackCommerce.
    • Meta is also trying to push that data scrapping copy protected work is "fair use" in the US to try and get out of a lawsuit. OpenAI is also trying to use that angle as well. This is after Meta they got caught downloading books from piracy book sites to feed their AI.
    • Stick to your weed and keep your medical "knowledge" to yourself.
    • Elder abuse lie? It's on the record. He couldn't stand prosecution for his mishandling of classified records because he was a doddering old fool literally puppeteered by his handlers and family. But you just want to steal content let's be honest here.
    • Not Netflix's fault and they had to switch to content creation. Content owners jacked up prices, won't allow them renew, and didn't give them the option to license new content.
  • Recent Achievements

    • Reacting Well
      sultangris earned a badge
      Reacting Well
    • First Post
      ClarkB earned a badge
      First Post
    • Week One Done
      Epaminombas earned a badge
      Week One Done
    • Week One Done
      Prestige Podiatry Care earned a badge
      Week One Done
    • Week One Done
      rollconults earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      144
    2. 2
      Xenon
      128
    3. 3
      ATLien_0
      124
    4. 4
      +Edouard
      102
    5. 5
      snowy owl
      97
  • Tell a friend

    Love Neowin? Tell a friend!