[英]cannot be resolved to a variable,where to declare it
我cant cannot be resolved to a variable
,我知道它的用途,但是我不知道如何解决它。我是否必须在其他地方声明它? 在哪
我有这个 :
public void calculeaza() {
totaltest = 0;
String[] cant = new String[allcant.size()];
for (int j = 0; j < allcant.size(); j++) {
cant[j] = allcant.get(j).getText().toString();
if (cant[j].matches("")) {
Toast.makeText(this,
"Ati omis cantitatea de pe pozitia " + (j + 1),
Toast.LENGTH_SHORT).show();
cant[j] = Float.toString(0);
}
和这个 :
public void salveaza(){
try {
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(cant[1]);
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
既然你宣告cant
在calculeaza()
你不能用它salveaza()
如果要在方法之间共享它,则应在外部将其声明为实例变量 。
您可以在此处了解有关Java范围的更多信息: Java编程:5变量范围 。
使用ArrayList代替String []并将其声明为类字段。
public class MyClass{
private ArrayList<String> cant; // <---- accessible by all methods in the class.
public void calculeaza() {
cant = new ArrayList<String>();
for (int j = 0; j < allcant.size(); j++) {
cant.add(allcant.get(j).getText().toString());
if (cant.get(j).matches("")) {
Toast.makeText(this,
"Ati omis cantitatea de pe pozitia " + (j + 1),
Toast.LENGTH_SHORT).show();
cant.get(j) = Float.toString(0);
}
....
public void salveaza(){
try {
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(cant[1]);
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
}
有很多更好的方法可以做到这一点,但这可以解决您的问题。 使用ArrayList是因为它比尝试在类级别初始化数组要容易得多。
如果要使用字符串数组,则可以调用cant String[] cant = new String[allcant.size()];
在不同的方法中,您不能在方法内部声明它。
在方法内部声明变量使其成为局部方法,这意味着它仅存在于该方法内,而无法从外部看到或使用。 您最好的选择是将其声明为实例变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.