複製程式
import java.io.*;
public class Guess {
public static void main(String[] args) {
byte[] b = new byte[10];
int g = 0;
int index = 0;
int x = 0;
String sbuf = null;
System.out.println("Pick a number between 1 and 100 :");
while(true) {
try {
g = System.in.read();
}catch(IOException ex) {ex.printStackTrace();}
switch(g) {
case '\n':
break;
case '\r':
sbuf = new String(b, 0, index);
x = Integer.parseInt(sbuf);
if(x < 79) {
System.out.println("Your Guess " + x + '\n' + "HIGHER" );
index = 0;
break;
}else if(x > 79) {
System.out.println("Your Guess " + x + '\n' + "LOWER");
index = 0;
break;
}else {
System.out.println("Your Guess " + x + '\n' + "CORRECT");
index = 0;
return;
}
default:
b[index++] = (byte)g;
}
}
}
}
很简单的,关键是把输入转换成int 的过程,还有就是理解in.read是行缓冲的.