📄 highscorerecordstore.java
字号:
package game;
import javax.microedition.rms.*;
public class HighScoreRecordStore
{
/**
* 保存最高分
* @param name 姓名
* @param score 分数
* */
public static void saveHighScore(String name, int score)
{
RecordStore nameRs = null;
RecordStore scoreRs = null;
int rsNum = 0;
byte b[];
try
{
//打开记录集
nameRs = RecordStore.openRecordStore("name", true);
scoreRs = RecordStore.openRecordStore("score", true);
try
{
rsNum = nameRs.getNumRecords();
}
catch(RecordStoreNotOpenException e)
{
rsNum = 0;
}
//记录数大于零
if ( rsNum > 0 )
{
//记录数小于5
if ( rsNum < 5 )
{
b = name.getBytes();
nameRs.addRecord( b, 0, b.length);
b = intToByte(score);
scoreRs.addRecord( b, 0, b.length);
for ( int i = rsNum; i > 0; i-- )
{
if ( i > 1 && byteToInt(scoreRs.getRecord(i)) < score )
{
b = nameRs.getRecord(i);
nameRs.setRecord( i+1, b, 0, b.length);
b = scoreRs.getRecord(i);
scoreRs.setRecord( i+1, b, 0, b.length);
}
else
{
if ( i == rsNum )
{
break;
}
b = name.getBytes();
nameRs.setRecord( i, b, 0, b.length);
b = intToByte(score);
scoreRs.setRecord( i, b, 0, b.length);
}
}
}
//记录集等于5
else
{
for ( int i = rsNum; i > 0; i-- )
{
if ( i > 1 && byteToInt(scoreRs.getRecord(i)) < score )
{
b = nameRs.getRecord(i+1);
nameRs.setRecord( i, b, 0, b.length);
b = scoreRs.getRecord(i+1);
scoreRs.setRecord( i, b, 0, b.length);
}
else
{
if ( i == rsNum )
{
break;
}
b = name.getBytes();
nameRs.setRecord( i, b, 0, b.length);
b = intToByte(score);
scoreRs.setRecord( i, b, 0, b.length);
}
}
}
}
else
{
b = name.getBytes();
nameRs.addRecord( b, 0, b.length);
b = intToByte(score);
scoreRs.addRecord( b, 0, b.length);
}
//关闭记录集
nameRs.closeRecordStore();
scoreRs.closeRecordStore();
nameRs = null;
scoreRs = null;
}
catch(Exception e)
{
}
}
/**
* 取高分记录
* */
public static int getHighScore(String name[], int score[])
{
RecordStore nameRs = null;
RecordStore scoreRs = null;
int rsNum = 0;
try
{
//打开记录集
nameRs = RecordStore.openRecordStore("name", false);
scoreRs = RecordStore.openRecordStore("score", false);
try
{
rsNum = nameRs.getNumRecords();
}
catch(RecordStoreNotOpenException e)
{
rsNum = 0;
}
for ( int i = 0; i < rsNum; i++ )
{
name[i] = new String(nameRs.getRecord(i+1));
score[i] = byteToInt(scoreRs.getRecord(i+1));
}
//关闭记录集
nameRs.closeRecordStore();
scoreRs.closeRecordStore();
nameRs = null;
scoreRs = null;
}
catch(Exception e)
{
System.out.println(e);
}
return rsNum;
}
/**
* 将整数转换为字节数组
* @param number 要转换的整数
* @return 字节数组
* */
public static byte[] intToByte(int number)
{
return String.valueOf(number).getBytes();
}
/**
* 将字节数组转换为整数
* @param number 要转换的字节数组
* @return 整数
* */
public static int byteToInt(byte[] bytes)
{
return Integer.parseInt(new String(bytes));
}
public boolean moveArrayElement(int data[], int from, int to)
{
if ( to > data.length )
{
return false;
}
else
{
data[to] = data[from];
}
return true;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -