黑马程序员技术交流社区
标题:
键盘录入无法停止,这是为什么,
[打印本页]
作者:
徐升2013
时间:
2013-4-11 18:32
标题:
键盘录入无法停止,这是为什么,
public static String fun() {
BufferedReader bfis = new BufferedReader(new InputStreamReader(
System.in));
String s = null;
String temp = null;
try {
while (true) {
temp = bfis.readLine();
if (temp.contains("null"))
break;
s = s.concat(temp);
}
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
}
复制代码
代码如上,明明设置只要含有null这个字符串就停止,为什么还是不停?原因在哪里,求教
作者:
熊永标
时间:
2013-4-11 18:40
本帖最后由 熊永标 于 2013-4-11 18:53 编辑
<P>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;</P>
<P>public class sadfssd {
public static void main(String[] args) {</P>
<P> BufferedReader bfis = new BufferedReader(new InputStreamReader(
System.in));
String s = "";</P>
<P> String temp = null;</P>
<P> try {
while (true) {
temp = bfis.readLine();</P>
<P> if (temp.contains("null"))
break;
s = s.concat(temp);</P>
<P> }</P>
<P> } catch (IOException e) {</P>
<P> e.printStackTrace();
}</P>
<P> }</P>
<P>}
</P>
复制代码
我测试了一下,是可以停下来的,只是有一个错误,那就是空指针错误,是因为你在申明s是没有初始化就把键盘输入的值给连接在后面,在调用concat()方法时,出现空指针异常.把在申明变量时,为其赋空字符串,就没错误了.如上提供的代码.
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2