构造函数和 Try Catch 语句的 困惑 ,高手 明示

lambertapple2 2011-11-12 12:29:13
一个简单类变量声明 ,必须在 在 try catch 外 先声明 为null, 然后用构造函数在 try catch里面生成 , 如果把这个 声明 全搬进 try catch,就变成无法解析 , 这是为什么 。看这个例子 : Printer outputStream, 必须要 先声明为 PrintWriter outputStream = null; 然后在 里面 创建实例 ,如果在 try catch 里面 直接写 : PrintWriter outputStream= new PrintWriter(new FileOutputStream("out.txt"));后面的 对 output的 调用 就不能执行了 ,是不是因为 try catch里面 包含的只能算局部变量了 外面的 看不到也无法调用了呢 ?


import java.io.*;
import java.util.*;

public class TextFileOutputDemo
{
public static void main(String[] args)
{

PrintWriter outputStream=null;
try
{
outputStream= new PrintWriter(new FileOutputStream("out.txt"));

}
catch (FileNotFoundException e)
{
System.out.println("Error opening the file out.txt.");
System.exit(0);
}
System.out.println("Enter three lines of text: ");
String line= null;
Scanner keyboard = new Scanner(System.in);
int count;
for(count=1; count<=3; count++)
{
line=keyboard.nextLine();
outputStream.println(count + " " + line);
}
outputStream.close();
System.out.println("Those lines were written to out.txt.");
}
}

...全文
119 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
风尘中国 2011-11-12
  • 打赏
  • 举报
回复
对的,try后面跟着的是一个{}所以里面声明的对象和变量的作用域都在这个{}当中,因此java在这里的语法方面确实不太好,有点费事
追风筝的孩子 2011-11-12
  • 打赏
  • 举报
回复
你的理解是对的,其实也不必可以这样写,当你发现try块后面的用不了,你就会把它提取出来了

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧