Возникли трудности с работой моих обработчиков PrintWriter и BufferedReader

Итак, я смог запустить свой код, однако у меня возникли проблемы с кодом рекордов. Я не могу использовать функции буферизованного чтения и печати, потому что по какой-то причине, которую я не понимаю, они не работают. Я хочу, чтобы программа сравнила счет с рекордом, и если счет больше, чем рекорд, рекорд будет обновлен в текстовом файле. причина, по которой файл txt необходим, связана с тем, что после закрытия программы мне нужен метод проверки предыдущего рекорда. Я действительно новичок в использовании обработки, записи и чтения файлов txt с помощью программ, и ни один из других сайтов и форумов, на которые я смотрел, не помог, потому что они не записывают переменную highscore в файл txt. Пожалуйста, помогите, я готов сломать свой компьютер. EM1.score = балл, набранный в ходе программы.

class High_Score {
int highscore = 0;   
PrintWriter output; //imports the writer
BufferedReader reader; //imports the reader
int state = 0; //sets the varoable for the keyboard

void scoring() {
int score = EM1.score; 
if (score > highscore) {
  highscore = score;
}
textSize(30);  
text("Your score is "+ score, 150, height/4); 
text("The current highscore is "+highscore+".", 75, height/2);
text("Try to beat it.", 200, 450);
textSize(12); 
text("Press esc to exit this page.", 225, 550);
}

void reader() {
importHS();
updateHS();
}

void updateHS() {
int score = EM1.score; 
output = createWriter("highscore.txt");  //creates the file that will be
if (highscore < score) {
highscore = score;
output.print(highscore);
output.close();
}
}

void importHS() {
reader = createReader("highscore.txt"); //reads the current highscore
if (reader == null) {
  highscore = 0;
  return;
}
String line;
try {
  line = reader.readLine();
} 
catch (IOException e) {
  e.printStackTrace();
  line = null;
}
if (line != null) {
  highscore = int(line);
  println(highscore);
}
try {
  reader.close();
} 
catch (IOException e) {
  e.printStackTrace();
}
}

void type() { //allows the screen to close is esc is pressed on the keyboard
state = key;
if (key == ESC) {
  exit();
}
}
}

person Nicole Ilyin    schedule 13.01.2017    source источник


Ответы (1)


Ты почти там. Есть только пара вещей, которые я вижу немного не так:

  1. вы не вызываете flush() на модуле записи оставшиеся данные записываются в файл
  2. проверка if (highscore < score) в updateHS() предотвращает запись: вам все равно это не нужно, так как scoring() уже проверяет, является ли текущий счет рекордом, и обновляет его соответствующим образом.

Вот большая часть вашего кода, настроенного для записи/чтения с диска:

EM1Class EM1 = new EM1Class();
High_Score hs = new High_Score();

void setup(){
   size(800,600);

   EM1.score = 500;

   hs.reader();
}

void draw(){
  background(0);
  hs.scoring();
  hs.updateHS();
}

void keyPressed(){
  if(keyCode == UP)   EM1.score += 10;
  if(keyCode == DOWN) EM1.score -= 10;
}

class EM1Class{
  int score;
}
class High_Score {
  int highscore = 0;   
  PrintWriter output; //imports the writer
  BufferedReader reader; //imports the reader
  int state = 0; //sets the varoable for the keyboard

  void scoring() {
    int score = EM1.score; 
    if (score > highscore) {
      highscore = score;
    }
    textSize(30);  
    text("Your score is "+ score, 150, height/4); 
    text("The current highscore is "+highscore+".", 75, height/2);
    text("Try to beat it.", 200, 450);
    textSize(12); 
    text("Press esc to exit this page.", 225, 550);
  }

  void reader() {
    importHS();
    updateHS();
  }

  void updateHS() {
    int score = EM1.score; 
    output = createWriter("highscore.txt");  //creates the file that will be
    output.print(highscore);
    output.flush();
    output.close();
  }

  void importHS() {
    reader = createReader("highscore.txt"); //reads the current highscore
    if (reader == null) {
      highscore = 0;
      return;
    }
    String line;
    try {
      line = reader.readLine();
    } 
    catch (IOException e) {
      e.printStackTrace();
      line = null;
    }
    if (line != null) {
      highscore = int(line);
      println(highscore);
    }
    try {
      reader.close();
    } 
    catch (IOException e) {
      e.printStackTrace();
    }
  }

  void type() { //allows the screen to close is esc is pressed on the keyboard
    state = key;
    if (key == ESC) {
      exit();
    }
  }
}

Там есть заполнитель EM1Class, чтобы скетч мог скомпилироваться.

Я не уверен, что класс High_Score должен знать о EM1 напрямую. Возможно, вы захотите немного реорганизовать код и убедиться, что он не так сильно связан, как сейчас, поскольку вы все равно используете классы.

Также ознакомьтесь с руководством по стилю Java: это поможет написать последовательный и аккуратно организованный код. Это, безусловно, окупится созданием дисциплины для этого в долгосрочной перспективе, но также сразу же, когда ваш код будет легче сканировать/быстро читать и делать выводы о его потоке.

Другой вариант — использовать встроенный XML и JSON, которые облегчат анализ (а также имеют удобные функции загрузки/сохранения).

int score = 0;
int highScore;

void setup(){
  loadHighScore();
}
void draw(){
  background(0);
  text("score:"+score+"\nhighScore:"+highScore+"\n\nuse UP/DOWN\narrows",10,15);
}
void keyPressed(){
  if(keyCode == UP)   score += 10;
  if(keyCode == DOWN) score -= 10;
  if(score > highScore) highScore = score;
}

void loadHighScore(){
  try{
    JSONObject jsonScore = loadJSONObject("highScore.json");
    highScore = jsonScore.getInt("highScore");
  }catch(Exception e){
    println("error loading/parsing highScore.json");
    e.printStackTrace();
  }
}
void saveHighScore(){
  JSONObject jsonScore = new JSONObject();
  jsonScore.setInt("highScore",highScore);
  saveJSONObject(jsonScore,"highScore.json");
}

//save on close
void exit(){
  saveHighScore();
  super.exit();
}
person George Profenza    schedule 13.01.2017