首页 > 解决方案 > 如何从java中的拆分字符串打印值的名称?

问题描述

我应该编写一个程序,询问人们的姓名和年龄,然后打印最年长的人的名字。(对不起,编程的某些部分不是英文的,但我希望有人足够理解以提供帮助)。这是一项任务,我必须通过拆分字符串来完成。

打印应该是这样的:

詹姆斯,2 玛丽,2 杰西卡,1 詹妮弗,5 加布里埃尔,10

最古老的名字:加布里埃尔

我知道如何打印最高年龄,但不知道它的名称。这就是我的做法:

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

    int oldest = -1;
    while (true) {
        String mjono = lukija.nextLine();
        if (mjono.equals("")) {
            break;
        }
        String[] pieces = mjono.split(",");
        int age = Integer.valueOf(pieces[1]);
        if (age > oldest) {
            oldest = age;
        }
    }
    System.out.println("The oldest age: " + oldest);

标签: javasplit

解决方案


假设我们有以下输入:

James,2
Mary,2
Jessica,1
Jennifer,5
Gabriel,10

我们可以逐行阅读,然后通过以下类获取最年长的人:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.*;

public class OldestPerson {
    public static class Person {
        private String name;
        private int age;

        Person(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public int getAge() {
            return this.age;
        }

        public String getName() {
            return this.name;
        }
    }

    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String line;
        PriorityQueue<Person> queue = new PriorityQueue<Person>((a, b) -> b.getAge() - a.getAge());
        while ((line = reader.readLine()) != null) {
            String[] tmp = line.split(",");
            queue.add(new Person(tmp[0], Integer.parseInt(tmp[1])));
        }
        if (!queue.isEmpty()) {
            Person oldestPerson = queue.poll();
            System.out.println(oldestPerson.getName());
        }
    }
}

另一种方法是直接比较人的年龄:

public static void main(String[] args) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    String line;
    String oldestPerson = "";
    int age = Integer.MIN_VALUE;
    while ((line = reader.readLine()) != null) {
        String[] tmp = line.split(",");
        if (age < Integer.parseInt(tmp[1])) {
            age = Integer.parseInt(tmp[1]);
            oldestPerson = tmp[0];
        }
    }
    System.out.println(oldestPerson);
}

推荐阅读