无法解析为变量,在哪里声明它

时间:2013-06-11 21:15:45

标签: java android

我得到了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();
    }
}

3 个答案:

答案 0 :(得分:3)

由于您在cant中声明了calculeaza(),因此无法在salveaza()中使用它。如果要在方法之间共享,则应将其声明为instance variable

您可以在此处了解有关Java Scope的更多信息:Java Programming: 5 - Variable Scope

答案 1 :(得分:1)

使用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,因为它比在类级别初始化数组容易得多。

答案 2 :(得分:1)

如果你想使用字符串数组,你可以用不同的方法调用cant String[] cant = new String[allcant.size()];,你不能在方法中声明它。

在方法中声明变量使其成为本地方法,这意味着它只存在于该方法中,无法从外部查看或使用。这里你最好的选择是将它声明为实例变量。