在java中调用包含while循环

时间:2018-03-21 15:11:04

标签: java while-loop

public List<String> CsvReaderGeneral(String CSVPATH,String AddStatement) throws IOException{
    BufferedReader bufferedReader = new BufferedReader(new FileReader(CSVPATH));
    String input;
    int count = 0;
    while((input = bufferedReader.readLine()) != null)    {
        count++;
    }

    System.out.println("Count : "+count);
    BufferedReader br = new BufferedReader(new FileReader(CSVPATH));
    br.readLine();
    String line=null;
    List<String> l = new ArrayList<String>();
     // String line="";
    while ((line = br.readLine()) != null) {
        String[] cols = line.split(",");
        l.add(AddStatement);
    }
    System.out.println(l);
    return l;
}

我在这里调用上面的方法:

public List<String> CsvReaderIDStationSystemHealth() throws Exception{

        //return CsvReaderGeneral(STATIONSCSVPATH, STATIONSCOLOUMNVALUE);
        return CsvReaderGeneral(STATIONSCSVPATH, "cols[0]");
    }

我的输出如下所示:

数:101
[cols [0],cols [0],cols [0],cols [0],cols [0],cols [0],cols [0],cols [0],cols [0],cols [0] ,cols [0],cols [0],cols [0],cols [0],cols [0],cols [0],cols [0],cols [0],cols [0],cols [0] ,cols [0],cols [0],cols [0],cols [0],cols [0],cols [0],cols [0],cols [0],cols [0],cols [0] ,cols [0],cols [0],cols [0],cols [0],cols [0],cols [0],cols [0],cols [0],cols [0],cols [0] ,cols [0],cols [0],cols [0],cols [0],cols [0],cols [0],cols [0],cols [0],cols [0],cols [0] ,cols [0],cols [0],cols [0],cols [0],cols [0],cols [0],cols [0],cols [0],cols [0],cols [0] ,cols [0],cols [0],cols [0],cols [0] ........

正在打印cols[0]而不是该位置的值。

如何获得价值?有没有其他方法可以调用此方法?

1 个答案:

答案 0 :(得分:1)

AddStatement =“cols [0]”并且你只是在循环中打印它而不以任何方式使用变量。我假设您正在尝试将该行的第一个元素添加到'l'变量中。所以你的while循环应该是这样的。

while ((line = br.readLine()) != null) {
        String[] cols = line.split(",");
        l.add(cols[0]);
    }

您不能(轻松)使用输入字符串调用动态创建的变量。如果您正在调用方法以获得可调整的cols,则您的方法标题应为

public List<String> CsvReaderGeneral(String CSVPATH,int colNum)

你的循环就是

while ((line = br.readLine()) != null) {
        String[] cols = line.split(",");
        l.add(cols[colNum]);
    }