[英]I need to get a file reader to read a text file line by line and format them in Java
[英]I need to take an array of three lines in a text file and sort them base on the first line in Java
我需要在文本文件中使用三行数组,并根据Java中的第一行对其进行排序。 我还需要操纵它,然后打印到屏幕上。
我有一个格式如下的测试文件:
10
Michael
Jackson
12
Richard
Woolsey
我需要从文本文件中输入此内容,然后根据与名称关联的数字重新排列它。 那时,我需要使用随机数生成器,并根据随机数为每个名称分配一个变量。 然后,我需要打印以不同的格式来筛选添加的变量和名称。 这是输出示例:
12:
Woolsey, Richard
Variable assigned
10:
Jackson, Michael
Other variable assigned
我非常感谢您的帮助。 我问是因为我真的不知道如何将三行作为一个变量输入,然后在程序中稍后进行操作。 谢谢,科里
我不确定我是否理解您的问题。 除了排序之外,下面的类似内容可能会有所帮助。 请注意,这是一个不完整的解决方案,其中不存储任何输入,并且仅将输出打印一次(然后丢弃)。
Random generator = new Random();
try { BufferedReader in = new BufferedReader(new FileReader("filename"));
String str;
String firstName = null:
while ((str = in.readLine()) != null) {
// try to create an Integer out of the "str"-variable
Integer nr = null;
try{
nr = Integer.parseInt(str);
firstName = null;
}
catch (NumberFormatException e) {
//line was not a number
if (firstName != null) {
// str is the last name
System.out.println(nr);
System.out.println(str + ", " firstName + " " + generator.nextInt());
}
else {
firstName = str;
}
}
}
in.close();
}
catch (IOException e) { }
请注意,此操作不会进行任何排序。 看一下该部分的比较器。 您也可以使用java.util.Scanner
从命令行读取输入(如果它不在文件中)。
Scanner
读取输入中的行 Random
生成随机数 Entry
类以封装每个条目的数据 Comparator<Entry>
和Collections.sort
List<Entry>
此代码段应具有指导意义:
import java.util.*;
import java.io.*;
public class Entry implements Comparable<Entry> {
final int id;
final int whatever;
final String firstName;
final String lastName;
Entry(int id , String firstName, String lastName, int whatever) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.whatever = whatever;
}
@Override public String toString() {
return String.format(
"%d:%n%s, %s%n(%d)%n",
id, lastName, firstName, whatever);
}
@Override public int compareTo(Entry other) {
return
(this.id < other.id) ? +1 :
(this.id > other.id) ? -1 :
0;
}
}
在这里,我们将每个Entry
封装在其自己的不可变值类型类中。 它还implements Comparable<Entry>
,以降序比较id
(假定为唯一)。
现在,我们可以使用SortedSet<Entry>
进行其余操作:
public static void main(String[] args) throws FileNotFoundException {
SortedSet<Entry> entries = new TreeSet<Entry>();
Scanner sc = new Scanner(new File("sample.txt"));
Random r = new Random();
while (sc.hasNextInt()) {
int id = sc.nextInt();
sc.nextLine();
String firstName = sc.nextLine();
String lastName = sc.nextLine();
int whatever = r.nextInt();
entries.add(new Entry(id, firstName, lastName, whatever));
}
for (Entry e : entries) {
System.out.println(e);
}
}
如果sample.txt
包含以下内容:
10
Michael
Jackson
12
Richard
Woolsey
那么输出可能是:
12:
Woolsey, Richard
(-1279824163)
10:
Jackson, Michael
(320574093)
@Override
我看到了您的帖子,并想给您一个快速的答案。
检查此链接: 逐行读取文件
您也应该阅读Java教程。
每行之后,您可以使用以下内容将其保存到二维数组中:
String str;
i = 0;
j = 0;
while ((str = in.readLine()) != null) {
array[i][j] = str;
j++;
if (j == 3){
j = 0;
i++;
}
}
in.close();
然后,您可以按自己喜欢的任何方式使用数组值。
祝好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.