javaのFileReadersとFileWriterに問題があります。私は自分のプログラムで人の名前を取得してから、2つの質問でスコアを評価するように求めます。これはかなり簡単ですが、今私がやりたいことは、このようなログファイルにそれを文書化することです:Javaのファイルで操作する
Jacob : 10
Mark : 15
Steve : 7
そして、これらの人々のいずれかのプログラムを開くたびに、それは彼らの現在のスコアを取得するか、それがある場合します誰かが新しい名前とスコアを付け加えるだろう。 ファイルを検索して最後に整数を取得する方法が見つかりません。
EDIT:
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