gpt4 book ai didi

java - 如何仅选择性地从 .txt 文件中读取数字和/或单词?

转载 作者:太空宇宙 更新时间:2023-11-04 11:37:10 26 4
gpt4 key购买 nike

我有一个简单的 .txt 文件(“theFile.txt”),其格式如下,其中左列是 lineNumber,右列是 word:

5     today
2 It's
1 "
4 sunny
3 a
6 "

对于这个 txt 文件,我使用两个单独的方法每个获取数字和字符串,再加上另一种方法来扫描文件并将每个 lineNumberword 放入双链表 DLL 中:

  String fileName = "theFile.txt";

public int getNumberOnly() {
int lineNumber;

//code to only get the lineNumber but NOT the words
//This is as far as I got and I need help on this part

return lineNumber;
}

public String getWordsOnly() {
String words;

//code to only get the words but NOT the lineNumber
//This is as far as I got and I need help on this part

return words;
}

public void readAndPrintWholeFile(String fileName){

String fileContents = new String();
File file = new File("theFile.txt");
Scanner scanner = new Scanner(new FileInputStream(fileName));
DLL<T> list = new DLL<T>();

//Print each lineNumber and corresponding words for example
// 5 Today
// 2 It's

while (scanner.hasNextLine())
{
fileContents = scanner.nextLine();
System.out.println(list.getNumbersOnly() + " " + list.getWordOnly());
//prints the lineNumber then space then the word
}
}

//I already have all DLL accessors and mutators such as get & set next/previous nodes here, etc.

我不知道如何为 getNumbersOnly()getWordOnly() 编写方法体

我已经尽力做到这一点。感谢您的帮助。

最佳答案

public static void readAndPrintWholeFile(String filename) throws FileNotFoundException {
String fileContents;
File file = new File(filename);
Scanner scanner = new Scanner(new FileInputStream(file));
Map<String, String> map = new HashMap<>();

while (scanner.hasNextLine()) {
try {
fileContents = scanner.nextLine();
String[] as = fileContents.split(" +");
map.put(as[0], as[1]);
System.out.println(as[0] + " " + as[1]);
} catch (ArrayIndexOutOfBoundsException e) {
//If some problam with File formate e.g. number without word
}
}
}

您可以通过多种方式做到这一点,其中之一就是聆听。Hera 我没有实现 getNumberOnly()getWordsOnly() 方法,并且我没有 DLL 实现,因此将数据放入 map(HashMap) 中。

关于java - 如何仅选择性地从 .txt 文件中读取数字和/或单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43153502/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com