📄 messagestore.java
字号:
/* ***************************************************
Fixed Data Structure Example
Message Store
***************************************************
*/
import java.io.*;
class MessageStore
{
public static void main( String args[] )
{
String a = "one string";
String b = "twostring";
String c = "threestring";
String c1 = "threestrin";
String [] test1input = { a, b, c };
String [] test1output = { b, c1 };
test(test1input,test1output,2,10);
test(test1input,test1input, 10, 20);
test(new String[0], new String[0], 10, 20);
System.out.println("done!");
}
protected static void test(String[] input, String[] output, int storeSize, int chunkSize) {
MessageStore self=new MessageStore(storeSize, chunkSize);
for ( int i=0; i< input.length; i++ ){
self.acceptMessage(input[i].toCharArray(), input[i].length());
};
assert( output.length == self.length(), "length wrong" );
char[] destination = new char[chunkSize];
for ( int i=0; i< output.length; i++ ){
String s = new String(destination, 0, self.getMessage(i, destination ));
assert ( s.equals(output[i]),
"message " + i + " wrong! " +
s + " != " + output[i]);
};
}
protected static void assert (boolean assertion, String excuse) {
if (!assertion) { throw new RuntimeException(excuse);}
}
protected char[][] messages;
protected int[] messageLengths;
protected int oldestMessage;
protected int length;
public MessageStore(int capacity, int messageSize) {
messages = new char[capacity][messageSize];
messageLengths = new int[capacity];
oldestMessage = length = 0;
assert( length() == 0, "buffer calcuations wrong" );
}
public void acceptMessage(char[] msg, int msgLength) {
int nextMessage = (oldestMessage + length) % capacity();
messageLengths[nextMessage] = Math.min(msgLength,chunkSize());
System.arraycopy(msg, 0, messages[nextMessage], 0, messageLengths[nextMessage]);
if (length() == capacity()) {
oldestMessage = (oldestMessage + 1) % capacity();
} else {
length++;
}
}
// getMessage: Answers a message into the character array passed. Returns the number
// of characters in the message. The character array must be larger than the chunk size.
public int getMessage(int i, char[] destination) {
int msgIndex = (oldestMessage + i) % capacity();
System.arraycopy( messages[msgIndex], 0, destination, 0, messageLengths[msgIndex]);
return messageLengths[msgIndex];
}
public int length() {return length;}
public int capacity() {return messages.length;}
public int chunkSize() {return messages[0].length;}
};
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -