既然是写程序,就自然不可避免需要人机交互。也就是需要获取用户的输入,然后出来得到用户的输出。
我看了书中的内容,书中给出的方法可以实现输入文字显示,但是存在问题,比如我输入一段长的中文,再输入一段短的中文,显示出来的内容中,还有那段长的中文内容的后边一部分。这里就是因为书中的参考程序没有进行数组的初始化,清空。我对代码进行了整理。并写下来与大家分享:
static void BookCase() {
InputStream is=System.in;
try {
byte[] bs=new byte[20];
while(is.read(bs)!=-1){
String string=new String(bs).trim();
bs=new byte[20]; //这里就是解决书中问题的地方。书中的代码,没有对数组进行重置,我这里进行了。
if(string.isEmpty()){
break;
}
System.out.print("大家好,输入的是:"+string+"\n\r");
}
} catch (Exception e) {
// TODO: handle exception
System.out.println("opps,sorry,出了点错误!");
}
}
上面是使用System.in类、InputStream类来完成的。
还有一种方法,是我研究出的,利用System.in类的部分静态方法完成:
static String GetString() {
int a = 0;
Collection<Byte> intList = new ArrayList<Byte>();
while (true) {
try {
a = System.in.read();
intList.add((byte) a);
if (a == 10) {
intList.add((byte) 10);
byte[] nByte = new byte[intList.size()];
Iterator<Byte> newInteger = intList.iterator();
a = 0;
for (; newInteger.hasNext();) {
nByte[a] = (byte) (newInteger.next());
a++;
}
String outStr = new String(nByte, Charset.defaultCharset());
return outStr;
}
} catch (IOException e) {
// TODO Auto-generated catch block
return "";
}
}
}
另外一种,是使用Scanner类来完成的。
这段代码实现了读取中文字符后,处理应该输入数字,但是输入的不是数字的情况,可以反复处理,直达输入的为数字。如下代码:
static void BBSCreat() {
Scanner kScanner = new Scanner(System.in);
System.out.print("输入一段文字:");
String nInput = kScanner.nextLine();
System.out.println("您输入的是:" + nInput);
kScanner.reset();
while (true) {
try {
System.out.print("输入一个数字:");
int d = kScanner.nextInt();
System.out.println("您输入的数字是:" + d);
break;
} catch (Exception e) {
kScanner.nextLine();
System.out.println("输入格式不对,请重新输入");
}
}
}
后期会给代码加上注释,现在太晚了,睡觉吧!