0

我正在尝试将我保存在 A 文件中的高分与整数进行比较。所以我总是会从我的文件中得到三个字符,但是如果我控制它,它不会把我的新分数放进去。

try{
                String FILENAME = "HanoiScore1File";
                FileInputStream fos = openFileInput(FILENAME);
                byte[] b = new byte[2];
                fos.read(b);
                fos.close();
                Data = new String(b);
                Score2 = Integer.parseInt(Data);
            }catch (java.io.FileNotFoundException e) {
              } catch (IOException e) {
                e.printStackTrace();
            }
            if(Score2>Score){
                try{
                    String FILENAME="HanoiScore1File";
                    Data=Integer.toString(Score);
                    FileOutputStream fostemp = openFileOutput(FILENAME, Context.MODE_PRIVATE);
                    fostemp.write(Data.getBytes());
                    fostemp.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
4

2 回答 2

0
String FILENAME = "HanoiScore1File";

//Read the score
Scanner scanner = new Scanner(new File(FILENAME));
int Score = scanner.nextInt();
scanner.close();

//Write the score
PrintWriter printWriter = new PrintWriter(new File(FILENAME));
printWriter.println(Score);
printWriter.close();

这有效,但我犯的错误是

if (Score2>Score)

score2 始终为 0,永远不会大于 score,所以它没有保存高分。

于 2012-05-09T15:00:18.593 回答
0

如果您真的关心将分数存储为两个字节以节省空间,则需要结合使用位移和按位运算符,例如:

    int score = 2839;
    byte a = (byte)(score & 255);
    byte b = (byte)(score >> 2);

但是,如果您对空间比较宽容,您可以执行以下简单操作:

    String FILENAME = "HanoiScore1File";

    //Read the score
    Scanner scanner = new Scanner(new File(FILENAME));
    int Score = scanner.nextInt();
    scanner.close();

    //Write the score
    PrintWriter printWriter = new PrintWriter(new File(FILENAME));
    printWriter.println(Score);
    printWriter.close();
于 2012-05-08T15:16:26.337 回答