java - 如何从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);
解决方案
假设我们有以下输入:
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);
}
推荐阅读
- c# - Cecil 自定义属性值为空
- service - 未找到 Google 表格返回的服务帐户
- php - 如何在没有php的网页中显示来自数据库的信息
- dolphindb - DolphinDB 中的用户定义函数和流聚合器
- azure - 如何解决 Azure Devops Pipeline 中的 -apptype 缺失错误
- javascript - src/app/koszyk.service.ts(21,28) 中的角度错误:错误 TS2339:“{}”类型上不存在属性“przedmioty”
- node.js - IBM Cloud Foundry 上的节点包依赖项 - 未定义要求/模块(未加载包)
- python - 当仅在浏览器中单击时显示时如何使用python获取重定向位置
- html - CSS:在填充内设置内联元素
- java - 在java中输出文本文件的CaesarCipher程序