System.in.read转换为整数不起作用

时间:2014-07-27 10:31:48

标签: java performance input

我正在尝试创建一个输入类,以便它可以比BufferedReader类更快地读取。我刚刚得到它,但不知何故,这段代码并没有按预期工作。我基本上使用这个类的readInt()方法,它应该一次读取一个整数,但它的作用是它读取第一个整数就好了,但它会跳过第二个整数的第一个字符。

INPUT:
1 
234

OUTPUT:
34

Case 2:
INPUT: 
2
3
4
5
6

OUTPUT:
4
6

我猜测下次调用readInt()方法时,它仍在读取前一个输入的换行符,但我无法弄清楚为什么会发生这种情况。

有人可以帮帮我吗?

import java.io.IOException;

public class Main{

/**
 * @param args
 * @throws IOException 
 */

public static void main(String[] args) throws IOException {
    FastInput fi = new FastInput();

    int T = fi.readInt();
    int[] arr = new int[100];
    //System.out.println("We are here. Value of T is: " + T);

    for(int i = 0; i < T; i++) {

        arr[i] = fi.readInt();
    }
    System.out.println("Printing the array:");
    for(int i = 0; i < T; i++) {
        System.out.println(arr[i]);
    }


}

}

class FastInput {
int bufferLength = 8192;
byte[] buffer;
byte b;
int currPos = 0;
int bytesRead = 0;

FastInput() {
    buffer = new byte[bufferLength];
}

FastInput(int l) {
    bufferLength = l;
    buffer = new byte[bufferLength];
}

public byte[] read() throws IOException {
    bytesRead = System.in.read(buffer, 0, bufferLength);
    currPos = 0;

    if(bytesRead == -1) {
        buffer[0] = -1;
    }
    return buffer;
}

public byte readByte() throws IOException {
    if(currPos == bytesRead) {
        read();
    }
    return buffer[currPos++];
}

public char readChar() throws IOException {
    while((b = readByte()) <= ' ') {
        b = readByte();
    }
    return (char)b;
}

public int readInt() throws IOException {
    int integer = 0;
    while((b = readByte()) <= ' ') {

        //System.out.println("Here b is: " + (char)b + " or " + b);
        b = readByte();
        //System.out.println("reading < space: " + (char)b + " or " + b);
    }
    boolean negative = false;
    if(b == '-') {
         negative = true;
         //System.out.println("reading negative: " + (char)b);
         b = readByte();
    }

    do{
        integer = (integer * 10) + (b - '0');
        //System.out.println("reading the number: " + (char)b);
        b = readByte();
    } while( b > ' ');

    if(negative) {
        return -integer;
    } else {
        return integer;
    }
}

public String readString() throws Exception {
    StringBuffer sb = new StringBuffer("");
    b = readByte();
    while (b <= ' ')
        b = readByte();
    do {
        sb.append((char) b);
        b = readByte();
    } while (b > ' ');
    return sb.toString();
}
}

0 个答案:

没有答案