为什么在使用inputstreamreader类时必须初始化变量x? [英] Why the variable x has to be initialized when using inputstreamreader class ?

查看:240
本文介绍了为什么在使用inputstreamreader类时必须初始化变量x?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import java.io. *;

public class i2

{

public static void main(String [] args)

{

InputStreamReader e = new InputStreamReader(System.in);



int x = 12; //声明1



尝试{

x = e.read();

}

catch(IOException p)

{



System.out .println(抓住);

}



System.out.println(x); //声明2



}



}





当x未在语句1处初始化为任何值时,它在语句2处给出编译时错误并且表示x未初始化。



但我认为x应该在调用read时初始化,因为read()返回一个Integer。

如果没有,那么这背后的概念是什么?请帮忙。



我尝试过的事情:



我跑了这是关于netbeans。

import java.io.* ;
public class i2
{
public static void main(String[] args)
{
InputStreamReader e = new InputStreamReader ( System.in) ;

int x=12 ; // statement 1

try{
x = e.read() ;
}
catch (IOException p)
{

System.out.println(" caught ");
}

System.out.println(x); // statement 2

}

}


When x is not initialized at statement 1 to any value then it gives compile time error at statement 2 and says x is not initialized .

But I think x should be initialized when read is invoked since read () returns an Integer .
If not then what is the Concept behind this ? Please help .

What I have tried:

I have run this on netbeans .

推荐答案

因为有一条路径通过代码,其中 x 在您尝试时没有值打印它:如果在 e.read 中抛出异常,将立即从 catch 块和<$继续执行c $ c> x 未分配值。
Because there is a path through the code where x has no value when your try to print it: if an exception is thrown in e.read execution will immediately continue from the catch block and x is not assigned a value.


这篇关于为什么在使用inputstreamreader类时必须初始化变量x?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆