我在使用java中的所有FileReader和FileWriters時遇到了一些問題。我希望我的程序能夠得到這個人的名字,然後在詢問他們幾個問題後評估他們的分數。這是很容易的,但現在我想要做的就是記錄它在這樣的日誌文件:每次這些人打開程序會檢索其當前得分對java中的文件進行操作
Jacob : 10
Mark : 15
Steve : 7
然後,或者如果它是一個新的它會追加他們的名字和分數。 我無法找到搜索文件的方法,然後在最後檢索整數。
編輯:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Scanner;
public class Main {
static Scores scoreClass = new Scores();
private static void setupMap() {
try {
FileInputStream fin = new FileInputStream("scores.map");
@SuppressWarnings("resource")
ObjectInputStream ois = new ObjectInputStream(fin);
scoreClass = (Scores) ois.readObject();
} catch (Exception e) {
System.err.println("Could not load score data");
e.printStackTrace();
}
}
private static void saveMap() {
try {
FileOutputStream fout = new FileOutputStream("scores.map");
@SuppressWarnings("resource")
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(scoreClass);
} catch (Exception e) {
System.err.println("Could not save score data");
e.printStackTrace();
}
}
public static void main(String[] args) {
setupMap();
int score = 0;
String guess;
String[][] questions_with_answers = {{"I __________ to school.(go)", "She __________ tennis. (play)", "She _______ a bitch. (be)"}, {"am going", "was playing", "is being"}};
Scanner answer = new Scanner(System.in);
Scanner studentInput = new Scanner(System.in);
System.out.println("What is your name?");
String name = answer.nextLine();
if(Scores.getScore(name) == -1){
Scores.setScore(name, score);
} else {
Scores.getScore(name);
}
System.out.println("Hello " + name + ". Your score is: " + score);
for(int i = 0; i < (questions_with_answers[0].length); i++){
System.out.println(questions_with_answers[0][i]);
guess = studentInput.nextLine();
if(guess.equals(questions_with_answers[1][i])){
System.out.println("Correct! You get 1 point.");
score = score + 1;
System.out.println("Your score is " + score);
} else {
System.out.println("You made a mistake! No points...");
}
}
System.out.printf("Congrats! You finished the test with "+ score +" points out of " + questions_with_answers[0].length);
Scores.setScore(name, score);
saveMap();
answer.close();
studentInput.close();
}
}
這不會引發任何異常,但仍然沒有從文件中讀取輸入:/
那你試試這麼遠嗎?向我們展示一些代碼 – nachokk
您可以在每行中使用'String [] array = line.split(「:」);'這將返回一個數組,在您的情況下,如果它被正確保存,數組的大小應該是2 。然後,只需使用'int score = Integer.valueOf(array [1])' – nachokk