从文本文件中读取信息以获取特定信息



我正在做一项任务,我必须创建一个间隔(我已经完成了(,并从文本文件中读取在间隔内找到的女孩的名字,并将它们放入数组列表中。我还必须读取所有以字母"J"开头的男性姓名,然后计算有多少男性出生以字母"J"开头,并打印出这些信息。以下是我迄今为止的代码:

public static int generateRandomInt(int lowerLimit, int upperLimit) {
int value = lowerLimit + (int)Math.ceil( Math.random() * ((upperLimit - lowerLimit) + 1)); //generates a random number between 1 and 10
return value;
}// end generateRandomInt
public static void main(String[] args) {
// Read from filename: top20namesNM1994.txt
// Generating a interval, the lower random number comes from 50 to 100, and the upper random number comes from 150 to 200.
// Print out this interval
// Read all the girls names, which birth numbers are inside of the interval you construct, into a array or ArrayList.
// Print out the array.
//Print out all the males names, which start with letter "J".
//Determine how many male births start with names starting with the letter "J", and print out the summary information.

final int LOW1 = 50;
final int LOW2 = 100;
final int HIGH1 = 150;
final int HIGH2 = 200;
ArrayList<String>girlNames = new ArrayList<String>();
String line = "";
int interval_low = generateRandomInt(LOW1, LOW2);
int interval_high = generateRandomInt(HIGH1, HIGH2);
System.out.println("The interval is ( " + interval_low + " , " + interval_high + " )" );
try {
FileReader inputFile = new FileReader("C:\Users\drago\eclipse-workspace-Ch6to7FinalExam2\MorrisJFinalExam2\src\top20namesNM1994.txt");
//Scanner scan = new Scanner (inputFile);
BufferedReader br = new BufferedReader(inputFile);
while((line = br.readLine()) != null) {
line.split("\s+");
if()
girlNames.add();
}
}
catch(IOException e) {
System.out.println("File not Found!");
}
if()
System.out.println(girlNames.toString());
}

我一直纠结于如何在创建的间隔内获得女孩的名字,以及如何读取男孩的名字。附件是文本文件。文本文件

好的。。。你知道如何读取文本文件(有点(,这很好,但你可以稍微简化代码:

ArrayList<String> girlNames = new ArrayList<>();
String filePath = "C:\Users\drago\eclipse-workspace-Ch6to7FinalExam2\"
+ "MorrisJFinalExam2\src\top20namesNM1994.txt"; 
String line = "";
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
while ((line = br.readLine()) != null) {
// ..................... 
// ..... Your Code .....
// .....................    
}
}
catch (IOException ex) {
ex.printStackTrace();
}

此处使用Try With Resources,以便自动关闭BufferedReader。如果你要做的只是读取所需的文本文件,那么如果使用得当,你在代码中注释掉的Scanner对象也是读取文本文件的一个很好的选择。

从您不完整的代码中可以明显看出,该文件中的每个数据行都是基于String#split((方法中使用的正则表达式("\s+"(分隔的空白制表符("\s+"表达式将在该字符串中包含的任意数量的空白和/或制表符上拆分字符串(请注意但是,使用String#split((方法的代码行没有正确完成。。。。如果您阅读链接教程,您会发现此方法用于填充字符串数组,这很好,因为通常,这就是您想要对文件数据行执行的操作。这样做当然可以让您从每个数据文件行中检索所需的确切数据部分。

这里没有人知道你的特定数据文本文件中包含什么,因为和其他许多文件一样,其中的内容显然是超级机密的,即使是虚构的数据也不够。因此,无法为您提供准确的数组索引值值符串数组从每个数据文件行检索所需的数据。然而,这是好的,因为是你需要弄清楚这一点,一旦你做到了,你就会把任务打败。

最新更新