簡體   English   中英

從方法java返回值

[英]Return value from method java

我在Java中編寫了一個程序來返回值表。 后來,隨着該程序功能的發展,我發現我想在方法中訪問未返回的變量,但我不確定執行此操作的最佳方法。 我知道您不能返回多個值,但是如何在不進行大修的情況下訪問此變量? 這是我的代碼的簡化版本:

public class Reader {
    public String[][] fluidigmReader(String cllmp) throws IOException {
        //read in a file
        while ((inpt = br.readLine()) != null) {
            if (!inpt.equals("Calls")) {
                continue;
            }
            break;
        }
        br.readLine();
        inpt = br.readLine();
        //set up parse parse parameters and parse
        prse = inpt.split(dlmcma, -1);
        while ((inpt = br.readLine()) != null) {
            buffed.add(inpt);
        }
        int lncnt = 0;
        String tbl[][] = new String[buffed.size()][rssnps.size()];
        for (int s = 0; s < buffed.size(); s++) {
            prse = buffed.get(s).split(dlmcma);
            //turns out I want this smpls ArrayList elsewhere
            smpls.add(prse[1]);
//making the table to search through
            for (int m = 0; m < prse.length; m++) {
                tbl[lncnt][m] = prse[m];
            }
            lncnt++;
        }
        //but I return just the tbl here
        return tbl;
    }

誰能推薦一種在另一個類中使用smpls而不返回它的方法? 使用獲取/設置排序設置時可能是這樣嗎? 抱歉,如果這是一個顯而易見的問題,我還是模塊化編程世界的新手

現在,您有了這個tbl變量。 將其包裝在一個類中,然后將列表添加到該類中。

class TableWrapper {
    // default accessing for illustrative purposes - 
    // setters and getters are a good idea
    String[][] table;
    List<String> samples;

    TableWrapper(String[][] table, List<String> samples) {
        this.table = table;
        this.samples = samples;
    }
}

然后重構您的方法以返回包裝對象。

public TableWrapper fluidigmReader(String cllmp) throws IOException {
    // your code here
    String tbl[][] = new String[buffed.size()][rssnps.size()];
    TableWrapper tw = new TableWrapper(tbl,smpls);
    // more of your code
    return tw;
}  

然后在您要去的代碼中

String[][] tbl = fluidigmReader(cllmp);

你反而去

TableWrapper tw = fluidigmReader(cllmp);
String[][] tbl = tw.table;
List<String> smpls = tw.samples;

如果您對返回值使用了專用的類(例如另一個答案中提到的TableWrapper ),則可以在其中添加其他字段。

這是關於類的好處-它們可以擴展。 但是您不能在Java中擴展String[][]

您可以設置一個字段,而不是一個局部變量,以后可以用一個吸氣劑來檢索它。 除非需要它,否則要避免它,但是在這種情況下是可以避免的。

您可以為此使用class(Inside Reader class)變量。 但是請確保它的讀/寫是同步的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM