您好,我有一個函式可以讀取由空格分隔的 int (0 1 0 2 0 1 0 2 0 1 0 1) 并在向量中逐個位置插入。這作業正常。
public void readTemplate() throws NumberFormatException, IOException {
File templateFile = new File ("C:\\Temp\\templateFile.txt");
FileReader fr = new FileReader(templateFile);
BufferedReader br = new BufferedReader(fr);
String row;
int j=0;
while((row = br.readLine()) != null) {
String[] strings = row.split(" ");
for (String str : strings) {
Integer foo = Integer.parseInt(str);
vectorTemplate[j] = foo;
j ;
}
}
br.close();
fr.close();
System.out.println("TEMPLATE FILE SUCCESFULY OPENED");
}
現在我有一個新的需求,那就是在同一行讀取一個字串。
認為這是投注者的名字和他們的賭注:
約翰 0 1 2 1 0 1 2 2 1 0 1 0
我有一個 Bet 型別類,我需要將名稱保存為 String 并將其他元素保存在該用戶的下注向量中。
我不知道如何將第一個資訊作為字串讀取以保存在我的變數名中,而該行的其余部分通常作為向量保存。
我嘗試了一些替代方法,但我總是遇到 java.lang.NumberFormatException
我相信錯誤在我留下粗體的那一行( totalBets[j].setName(str); )
public void betsReads() throws IllegalArgumentException, IOException {
File betsFile = new File ("C:\\Temp\\bets.txt");
FileReader fr = new FileReader(betsFile);
BufferedReader br = new BufferedReader(fr);
for(int j = 0; j < size; j ) {
String row;
while((row= br.readLine()) != null) {
totalBets[j] = new Bet();
String[] strings = row.split(" ");
for (String str : strings) {
**totalBets[j].setName(str);**
for(int i = 0; i < bets.vectorBets.length; i ) {
Integer foo = Integer.parseInt(str);
totalBets[j].vectorBers[i] = foo;
}
j ;
}
}
}
br.close();
fr.close();
uj5u.com熱心網友回復:
String令牌陣列中的第一個是名稱。之后的每個值都是一個賭注。此外,使用try-with-Resources而不是顯式關閉。喜歡,
public void betsReads() throws IllegalArgumentException, IOException {
File betsFile = new File("C:\\Temp\\bets.txt");
try (FileReader fr = new FileReader(betsFile);
BufferedReader br = new BufferedReader(fr)) {
String row;
int j = 0;
while ((row = br.readLine()) != null) {
totalBets[j] = new Bet();
String[] strings = row.split("\\s ");
totalBets[j].setName(strings[0]);
for (int i = 1; i < strings.length; i ) {
int foo = Integer.parseInt(strings[i]);
totalBets[j].vectorBers[i - 1] = foo;
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/354279.html
