繁体   English   中英

如何在循环之外使用此变量?

[英]how can i use this variable outside it's loop?

当我尝试在循环或if声明之外使用变量“ encryptionKey”时,会引发编译错误“找不到符号”。

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中存在哪些类型的变量

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

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

并且您将可以在此类的任何位置使用此变量,或在方法内部声明, else-ifelse-if范围之外:

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

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

因此它对于此特定方法内的所有实体都是可见的。

这是因为该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);
}

在方法外创建变量

char[] encryptionKey;

在方法里面,那么你可以

encryptionKey = ...

唯一的问题是,如果您在初始化变量之前尝试调用它,请当心,或采取诸如if(encryptionKey==null) return;预防措施if(encryptionKey==null) return;

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

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

             encryptionKey = inputPlainResultArray;
             ....
}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM