黑马程序员技术交流社区

标题: 关于判断语句中的变量 [打印本页]

作者: shdosh    时间: 2015-8-27 21:22
标题: 关于判断语句中的变量
  1.         public static Set<Student> getScore(Comparator<Student> cmp)throws IOException{

  2.                 Set<Student> stuSet = null;//盲点:如果写在if里面,下面会出现stuSet变量找不到的错误,因为判断语句可能执行不到。
  3.                 if(cmp == null)
  4.                         /*Set<Student>*/ stuSet = new TreeSet<Student>();
  5.                 else
  6.                         stuSet = new TreeSet<Student>(cmp);
  7.                 BufferedReader bufIn =  new BufferedReader(new InputStreamReader(System.in));
  8.                
  9.                 String str = null;

  10.                 while((str = bufIn.readLine())!=null){
  11.                         if(str.equals("over"))
  12.                                 break;
  13.                         String[] stuInfo = str.split(",");
  14.                        
  15.                         Student stu = new Student(stuInfo[0],Integer.parseInt(stuInfo[1]),Integer.parseInt(stuInfo[2]),Integer.parseInt(stuInfo[3]));
  16.                        
  17.                         stuSet.add(stu);
  18.                 }
  19.                 return stuSet;

  20.         }
复制代码


作者: shdosh    时间: 2015-8-27 21:23
如果把Set的定义放在if判断中会出现stuSet变量找不到符号的错误,难道是编译器认为判断语句可能会执行不到,所以认为找不到符号?
作者: chensheng06    时间: 2015-8-27 21:47
如果定义在if里面,你确定在if里面定义的局部变量,到下面的whlie循环能用?
作者: shdosh    时间: 2015-8-27 22:22
chensheng06 发表于 2015-8-27 21:47
如果定义在if里面,你确定在if里面定义的局部变量,到下面的whlie循环能用? ...

Set<Student> stuSet = null;写在if外面能用,写在if里面就不能用了





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