A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 刘圣繁 中级黑马   /  2013-2-21 22:55  /  5662 人查看  /  8 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

import java.net.*;
import java.io.*;
class LoginClient
{
public static void main(String[]args)throws Exception
{
Socket  st=new Socket("192.168.0.2",10002);
try{
PrintWriter out=new PrintWriter(st.getOutputStream(),true);
BufferedReader bur=new BufferedReader(new InputStreamReader(System.in));
BufferedReader buw=new BufferedReader(new InputStreamReader(st.getInputStream()));
for(int i=0;i<3;i++)
{
String name=bur.readLine();
if(name==null)
{
System.out.println("请输入用户名");
continue;
}
out.println(name);
String line=buw.readLine();
System.out.println(line);
if(line.contains("欢迎"))
break;
}
}
catch(IOException e){e.printStackTrace();}
finally{
try{
bur.close();
st.close();
}
catch(IOException e){e.printStackTrace();}
}
}
}
上面代码编译时出现问题
说变量bur找不到
编译提示找不到bur!!!!!!!!!!!
是不是说明try中的变量在try外面不能用   

8 个回复

倒序浏览
变量都有作用域的
一般来说呢就是一对大括号内
出了大括号就离开了变量的作用域,变量被释放了,不存在了
回复 使用道具 举报
{} 内的东西,只能{}自家用,其他想用,只能让{},在内部声明为 static  
回复 使用道具 举报
try代码块中的变量是局部变量,外面是用不了的
该代码中,你可以设成引用型变量定义在成员位置上,下面代码块就可以用了
比如
PrintWriter out=null//引用型变量定义在成员位置上
BufferedReader bur=null//引用型变量定义在成员位置上
BufferedReader buw=null//引用型变量定义在成员位置上

try{
out=new PrintWriter(st.getOutputStream(),true);
bur=new BufferedReader(new InputStreamReader(System.in));
buw=new BufferedReader(new InputStreamReader(st.getInputStream()));
}
这样写就不会有问题了
回复 使用道具 举报
{} 内的东西,只能{}自家用,其他想用,只能让{},在内部声明为 static  
回复 使用道具 举报
胥文 发表于 2013-2-21 23:15
try代码块中的变量是局部变量,外面是用不了的
该代码中,你可以设成引用型变量定义在成员位置上,下面代码 ...

正解!归根起来还是局部变量的作用域问题。
回复 使用道具 举报
在try中声明的变量属于局部变量,局部变量的作用域只能在当前的方法中使用,当方法执行完后,局部变量的生命周期也就结束了。
回复 使用道具 举报
胥文 发表于 2013-2-21 23:15
try代码块中的变量是局部变量,外面是用不了的
该代码中,你可以设成引用型变量定义在成员位置上,下面代码 ...

正解 ,ooo
回复 使用道具 举报

  1. import java.net.*;
  2. import java.io.*;
  3. class LoginClient
  4. {
  5. public static void main(String[]args)throws Exception
  6. {
  7. Socket  st=new Socket("192.168.0.2",10002);
  8. PrintWriter out=null;
  9. BufferedReader bur=null;
  10. BufferedReader buw=null;      //在外面初始化,作用于整个main方法
  11. try{
  12. out=new PrintWriter(st.getOutputStream(),true);
  13. bur=new BufferedReader(new InputStreamReader(System.in));
  14. buw=new BufferedReader(new InputStreamReader(st.getInputStream()));
  15. for(int i=0;i<3;i++)
  16. {
  17. String name=bur.readLine();
  18. if(name==null)
  19. {
  20. System.out.println("请输入用户名");
  21. continue;
  22. }
  23. out.println(name);
  24. String line=buw.readLine();
  25. System.out.println(line);
  26. if(line.contains("欢迎"))
  27. break;
  28. }
  29. }
  30. catch(IOException e){e.printStackTrace();}
  31. finally{
  32. try{
  33. bur.close();
  34. st.close();
  35. }
  36. catch(IOException e){e.printStackTrace();}
  37. }
  38. }
  39. }
复制代码
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马