【发布时间】:2016-12-28 18:49:43
【问题描述】:
我有一个项目,其主要功能是将 .txt 文件读入字符串数组,并按每行中的特定字符串值对其进行排序。我的 .txt 文件是一份员工名单,上面有他们的姓名、薪水和经验。以下是我的示例列表:
- 姓名:托马斯·格林 |总工资:10 000 |经验:30 个月
- 姓名:安娜·朗 |工资总额:6 000 |经验:12 个月
- 姓名:迈克尔·霍尔斯 |工资总额:8 000 |经验:27 个月
现在我想要的是在使用 Scanner 将此列表更改为数组之后,通过名字、薪水值或经验值对该列表进行排序。我已阅读有关比较器的信息,但找不到正确的示例。如您所见,该程序要做的是跳过“名称:”值并按名字的字母顺序对其进行排序。或者跳过其他字符串并按最低工资值对列表进行排序。经验也是一样的,它应该按从最低到最高的月份数排序。
到现在为止我可以做的事情是:
import java.io.File;
import java.io.IOException;
import java.util.*;
public class SortList {
public static int loadInt() {
Scanner s = new Scanner(System.in);
if(!s.hasNextInt()) {
s.next();
s.nextLine();
return loadInt();
}
return s.nextInt();
}
public static void main (String[] args) throws IOException{
//show the list
String token1 = "";
Scanner inFile1 = new Scanner (new File ("list.txt")).useDelimiter(",\\s*");
List<String> temps = new ArrayList<String>();
while(inFile1.hasNext()) {
token1 = inFile1.next();
temps.add(token1);
}
inFile1.close();
String[] tempsArray = temps.toArray(new String[0]);
for(String s : tempsArray) {
System.out.println(s);
}
//Sort the list
System.out.println("How do you want to sort?" + "\n" + "1. By name" + "\n" + "2. By salary" + "\n" + "3. By experience");
int b;
b = loadInt();
if (b == 1){
ArrayList<String> namesList = new ArrayList<>();
for(int i = 0; i<tempsArray.length; i++){
namesList.add(tempsArray[i]);
}
Collections.sort(namesList, (name1, name5) -> name1.split(" ")[1].compareTo(name5.split(" ")[1]));
for(String name : namesList){
System.out.println(name);
}
}
if (b == 2){
ArrayList<String> salaryList = new ArrayList<>();
for(int i = 0; i<tempsArray.length; i++){
salaryList.add(tempsArray[i]);
}
Collections.sort(salaryList, (salary1, salary2) -> salary1.split(" ")[10].compareTo(salary2.split(" ")[10]));
for(String salary : salaryList){
System.out.println(salary);
}
}
if (b == 3){
ArrayList<String> experienceList = new ArrayList<>();
for(int i = 0; i<tempsArray.length; i++){
experienceList.add(tempsArray[i]);
}
Collections.sort(experienceList, (experience1, experience2) -> experience1.split(" ")[14].compareTo(experience2.split(" ")[14]));
for(String experience : experienceList){
System.out.println(experience);
}
}
}
}
目前,当我输入整数值时,我的代码不会对列表进行排序。我这样做的方式是否正确?我通过互联网找到了 Collection 的示例,但它对我不起作用。
【问题讨论】:
-
真正的问题是,在对各种排序事物进行任何操作之前,您需要一个合理的“对象”模型。从这个意义上说,dimo 的答案是绝对必须供您研究。
-
感谢您的解释。但是如果我创建一个名为 Employee 的对象,我将如何从 txt 文件中加载列表?我是 Java 的初学者,因此我无法想象如何从 txt 文件中加载对象。
-
哇,花了一些时间为你写了一个答案。希望这会有所帮助,因为我有一种模糊的感觉,我什至不会看到太多的赞成票......
标签: java arrays string sorting collections