【问题标题】:how can i use this variable outside it's loop?我如何在它的循环之外使用这个变量?
【发布时间】:2015-08-25 10:25:56
【问题描述】:

当我尝试在循环之外使用变量“encryptionKey”或在其中声明它的 if 语句时,它会引发编译错误“找不到符号”.. 有什么想法吗?

else if (inputPlainResultArray.length == 4 || inputPlainResultArray.length == 9 || inputPlainResultArray.length == 16)
{
   char[] encryptionKey = inputPlainResultArray;
   System.out.print("Encryption Key: ");
   System.out.print(encryptionKey);
   System.out.println();
   System.out.println();
   System.out.println();
   System.exit(0);

}
}
}

【问题讨论】:

  • 那些变量超出范围。在 java 中,范围仅限于 {}。只需将该变量声明移到顶部,以便它们进一步可用。

标签: java declare


【解决方案1】:

因为它是局部变量,这意味着你不能在它声明的范围之外访问它。 你应该看看on which types of variables exists in Java

在您的特定情况下,您可以使用 实例变量,因此您可以在方法之外声明 char[] encryptionKey

 public class YourClass{
   char[] encryptionKey;
   // other methods, fields, etc.
}

你可以在这个类的任何地方使用这个变量,或者在方法内部声明,在else-if范围之外:

char[] encryptionKey = null;
if (...){}

else if (...){
char[] encryptionKey = inputPlainResultArray;
}

所以它对这个特定方法内的所有实体都是可见的。

【讨论】:

    【解决方案2】:

    这是因为variable 的范围在loop/if 语句的花括号中。你不能这样使用它。而是在外面声明并使用它。

    在你的情况下,它看起来像这样:

    char[] encryptionKey = null;
    if (...)
    ...
    else if (inputPlainResultArray.length == 4 || inputPlainResultArray.length == 9 || inputPlainResultArray.length == 16)
    {
        encryptionKey = inputPlainResultArray;
        System.out.print("Encryption Key: ");
        System.out.print(encryptionKey);
        System.out.println();
        System.out.println();
        System.out.println();
        System.exit(0);
    }
    

    【讨论】:

      【解决方案3】:

      在方法之外创建变量

      char[] encryptionKey;
      

      在方法里面你可以有

      encryptionKey = ...
      

      唯一的问题是如果你在初始化变量之前尝试调用它,所以要小心,或者采取预防措施,例如if(encryptionKey==null) return;

      【讨论】:

        【解决方案4】:

        您无法从循环外部访问变量“encryptionKey”,因为您已在循环内部声明了它。 将声明移到外面,它会起作用。

        char[] encryptionKey;    
        else if (inputPlainResultArray.length == 4 || inputPlainResultArray.length == 9 || inputPlainResultArray.length == 16)
        {
        
                     encryptionKey = inputPlainResultArray;
                     ....
        }
        

        【讨论】:

          【解决方案5】:

          使用 break 关键字,而不是 System.exit(0);

          if(condition){
                  //do something
                  break;
              }
          

          【讨论】:

          • 这是你的第二个问题
          猜你喜欢
          • 2016-05-30
          • 2015-06-05
          • 1970-01-01
          • 1970-01-01
          • 2021-03-10
          • 2013-12-03
          • 2022-07-18
          • 1970-01-01
          • 2020-11-05
          相关资源
          最近更新 更多