美文网首页
Compilation error String cannot

Compilation error String cannot

作者: 泡泡爱上巧克力_7122 | 来源:发表于2018-07-24 09:16 被阅读0次

    public class StrTest {

     public static void main(String[] args) {

         int i = 10; Object obj =i; 

         if(obj instanceof String) String s=(String) obj; 

     }}

    出现String cannot be resolved to a variable错误,但是如果改成这样

    public class StrTest2 { 

     public static void main(String[] args) {

         int i = 10; Object obj =i; 

         String s=null;

         if(obj instanceof String) s=(String) obj; 

     }}

    没有错误。

    出现这个编译错误的原因在于StrTest 1中if语句中的变量s作用域仅在{}内,编译器阻止你这么做,认为你出了作用域外我们都不能使用这个变量,并以此认为这是不必要的代码。而StrTest2中作用域在main中。但是在Str1中我们这么写

     if(obj instanceof String) {String s=(String) obj;} 由于有{}的作用,编译器认为你申明的变量的作用域范围,因此没有报错 

    相关文章

      网友评论

          本文标题:Compilation error String cannot

          本文链接:https://www.haomeiwen.com/subject/utfemftx.html