黑马程序员技术交流社区

标题: 键盘录入无法停止,这是为什么, [打印本页]

作者: 徐升2013    时间: 2013-4-11 18:32
标题: 键盘录入无法停止,这是为什么,
  1. public static String fun() {
  2.                 BufferedReader bfis = new BufferedReader(new InputStreamReader(
  3.                                 System.in));
  4.                 String s = null;

  5.                 String temp = null;

  6.                 try {
  7.                         while (true) {
  8.                                 temp = bfis.readLine();

  9.                                 if (temp.contains("null"))
  10.                                         break;
  11.                                 s = s.concat(temp);
  12.                        
  13.                                
  14.                         }

  15.                 } catch (IOException e) {

  16.                         e.printStackTrace();
  17.                 }
  18.                 return s;

  19.         }
  20. }
复制代码
代码如上,明明设置只要含有null这个字符串就停止,为什么还是不停?原因在哪里,求教

作者: 熊永标    时间: 2013-4-11 18:40
本帖最后由 熊永标 于 2013-4-11 18:53 编辑

  1. <P>import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;</P>
  4. <P>public class sadfssd {
  5. public static void main(String[] args) {</P>
  6. <P>  BufferedReader bfis = new BufferedReader(new InputStreamReader(
  7.     System.in));
  8.   String s = "";</P>
  9. <P>  String temp = null;</P>
  10. <P>  try {
  11.    while (true) {
  12.     temp = bfis.readLine();</P>
  13. <P>    if (temp.contains("null"))
  14.      break;
  15.     s = s.concat(temp);</P>
  16. <P>   }</P>
  17. <P>  } catch (IOException e) {</P>
  18. <P>   e.printStackTrace();
  19.   }</P>
  20. <P> }</P>
  21. <P>}
  22. </P>
复制代码
我测试了一下,是可以停下来的,只是有一个错误,那就是空指针错误,是因为你在申明s是没有初始化就把键盘输入的值给连接在后面,在调用concat()方法时,出现空指针异常.把在申明变量时,为其赋空字符串,就没错误了.如上提供的代码.






欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2