如何从静态方法调用数组?

时间:2016-02-23 07:33:13

标签: arrays static

在此代码中,如何全局调用数组以供其他方法使用?

关于我的代码的背景信息,我们被要求扫描包含DNA链的文件,然后将其翻译成RNA Strand。

我收到错误:“当我在翻译方法上调用dna数组时找不到符号 - 变量dna”(它找不到dna.length)for(int i=0; i < dna.length; i++){

public class FileScannerExample 
{

    public static void main(String[] args) throws IOException
    {
        //This is how to create a scanner to read a file

        Scanner inFile = new Scanner(new File("dnaFile.txt"));  
        String dnaSequence = inFile.next();
        int dnalength = dnaSequence.length();

        String[] dna = new String[dnalength];

        for(int i=0; i<=dna.length-2 ; i++)
        {
            dna[i]=dnaSequence.substring(i,i+1); //looking ahead and taking each character and placing it in the array 
        }

        dna[dna.length-1]=dnaSequence.substring(dna.length-1); //reading the last spot in order to put it in the array 

        //Testing that the array is identical to the string
        System.out.println(dnaSequence);
        for(int i = 0 ; i<=dna.length-1; i++)
        {
            System.out.print(dna[i]);
        }

    }



    public void  translation()
    {  
        for(int i=0; i < dna.length; i++){
            //store temporary 
            if (dna[i] = "A"){
                dna[i] = "U"; 
            }
            if(dna[i] = "T"){
                dna[i] = "A";
            }
            if(dna[i] = "G"){
                dna[i]= "C"; 
            }
            if(dna[i] = "C"){
                dna[i] = "G";
            }

        }
    }

}

1 个答案:

答案 0 :(得分:0)

您需要先将符号带入范围,然后才能引用它。您可以通过将其拉到更高的范围(作为类中的字段),或通过将其作为方法参数传递到本地范围来执行此操作。

作为班级成员:

public class Test
{
    private String myField;

    void A() {
        myField = "I can see you";
    }

    void B() {
        myField = "I can see you too";
    }
}

作为方法参数:

public class Test
{
    void A() {
        String myVar = "I can see you";
        System.out.println(myVar);
        B(myVar);
    }

    void B(String param) {
        param += " too";
        System.out.println(param);
    }
}

请注意,为了查看实例成员,您必须从非静态上下文引用它。您可以通过将该字段声明为静态来解决这个问题,尽管您希望在类中注意静态状态,但这通常会使代码更加混乱并且更难以使用。