你好,基本上我的目标是读取一个 txt
文件,将其存储在一个数组中,并在方法参数之后打印数组元素。文本文件的格式如图所示(一行中每个字符串之间有一个空格)
alan 1000
lee 20
rodney 28
例如如果我的参数是 lee
,该方法应该打印出 20
。如果 rodney
那么 28
public class practice
{
public void dataReader(String fName, String pname)
{
try
{
FileReader fr=new FileReader(fName);
BufferedReader br=new BufferedReader(fr);
String[] a={};
String line= br.readLine();
while(line !=null)
{
a= line.split(" "); // deliminator white space
}
for(int i=0; i <a.length; i++)
{
if(a[i].equals(pname))
{
System.out.println(a[i]+1);
}
}
}
catch(IOException e)
{
}
}
最佳答案
您发布的代码无效,因为您只读过第一行,然后一直循环遍历该行。
你的代码,修剪和注释:
String line= br.readLine(); // returns the first line of the file
while(line !=null) { // checks if the line is null - it's not at the first line
a= line.split(" "); // deliminator white space
}
// we never get here, because nowhere in the loop do we set line to null
您需要调用br.readLine()
在一个循环中,直到它返回 null,像这样:
BufferedReader br=new BufferedReader(new FileReader(fName));
String line= br.readLine(); // reads the first line, or nothing
while(line != null) {
a= line.split(" "); // deliminator white space
String[] arr = line.split("\\s+"); // splits a string by any amount of whitespace
if(arr.length >= 2 && arr[0].equals(lookup)) {
System.out.println(arr[1]);
}
line = br.readLine(); // this will eventually set line to null, terminating the loop
}
原始代码中的 for 循环将不起作用,如果您点击它,您的输出将是 lee1
或 rodney1
分别。如果您将其更改为 arr[i+1]
相反,我假设您正在尝试这样做,如果数组中的最后一项与 pname
匹配,它会因 IndexOutOfBoundsException 而崩溃。 .
原始答案
这是 Scanner 的理想用例.它会“扫描”字符串或文件以查找您要查找的内容,从而显着简化许多用例的文件解析,尤其是用空格分隔的文件。
public void searchFile(String fName, String lookup){
Scanner in = new Scanner(new File(fName));
// Assumes the file has two "words" per line
while(in.hasNext()){
String name = in.next();
String number = in.next():
if(name.equals(lookup){
System.out.println(number);
}
}
}
如果你不能使用扫描仪来解析每一行,你仍然可以使用它来简化读取每一行,然后做任何需要完成的更复杂的行解析,就像这样:
public void searchFile2(String fName, String lookup){
Scanner in = new Scanner(new File(fName));
while(in.hasNextLine()){
String line = in.nextLine();
String[] arr = line.split("\\s+"); // splits a string by any amount of whitespace
if(arr[0].equals(lookup)){
System.out.println(arr[1]);
}
}
}
顺便说一句,如果您知道名称是唯一的,您可以使用 Map (具体来说,一个 HashMap )来有效地存储和查找名称到数字的映射。因此,您可以使用一种方法来解析文件并返回所有 名称到数字的映射,而不是使用需要查找文件名和名称的方法,然后您可以简单地调用 map.get("name")
在返回的 map 上高效地获取给定人员的号码,而无需每次都重新读取文件。
关于java - 将一个txt文件拆分成一个数组,并在数组中查找元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11939954/