所以我试图读取一个包含int和字符串的文件。因此,主要目标是让用户输入参考编号和程序以吐出下面的行。我正在尝试使用线性搜索算法,这是文件:
1<---Reference #
The Adventures of Tom Sawyer<---Line to Spit out
2
Huckleberry Finn
4
The Sword in the Stone
6
Stuart Little
10
Treasure Island
12
The Secret Garden
14
Alice's Adventures in Wonderland
20
Twenty Thousand Leagues Under the Sea
24
Peter Pan
26
Charlotte's Web
31
A Little Princess
32
Little Women
33
Black Beauty
35
The Merry Adventures of Robin Hood
40
Robinson Crusoe
46
Anne of Green Gables
50
Little House in the Big Woods
52
Swiss Family Robinson
54
The Lion, the Witch and the Wardrobe
56
Heidi
66
A Winkle in Time
100
Mary Poppins
以下是我目前的代码:
public class NewJFrame extends javax.swing.JFrame {
ArrayList<Integer> colours = new ArrayList<Integer>();
BufferedReader br = null;
/**
* Creates new form NewJFrame
*/
public NewJFrame() {
int word=0;
try {
br = new BufferedReader(new FileReader("Booklist.txt"));
while ((word == br.read())){
colours.add(word);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
initComponents();
}
static public Boolean linearSearch(ArrayList colours, String B) {
for (int k = 0; k < A.length; k++) {
if (A[k].equals(B)) {
return true;
}
}
return false;
}
对于初学者来说,如果你可以帮助我至少正确阅读文件那就太棒了。
答案 0 :(得分:0)
最简单的方法是使用地图。
Map<Integer,String> readFileasMap(String file) throws IOException{
Map<Integer,String> map = new HashMap<>();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while((line = br.readLine()) != null){
int number = Integer.parseInt(line);
String text = br.readLine();
map.put(number, text);
}
br.close();
return map;
}
然后您可以使用map.get(index)
返回相应的行
如果你想把它与列表保持一致,那么函数非常相似。
List<Integer> indexes;
List<String> titles;
void readFileasLists(String file) throws IOException{
indexes = new ArrayList<>();
titles = new ArrayList<>();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while((line = br.readLine()) != null){
int number = Integer.parseInt(line);
String text = br.readLine();
indexes.add(number);
titles.add(text);
}
br.close();
return;
}