字节与整数进行比较

时间:2012-05-08 14:38:54

标签: android integer compare byte

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

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分: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)

得分2总是0,永远不会大于得分,所以它没有保存高分。