要与整数进行比较的字节



>我正在尝试比较我保存在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();
                }
            }

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

    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();
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,因此它没有保存高分。

相关内容

  • 没有找到相关文章

最新更新