有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在for循环范围外返回字符串值

我面临的一个问题是,在for loop示波器下打印之后,从xl中计算值,然后再打印。当声明in return语句并调用该方法时,仅打印第一个单元格值。我想要8个单元格的值

public String Sheet_Infor() {

    ReadConfig readconfig = new ReadConfig();   
    String excelPath = readconfig.getExcelPath();       
    int Row =0;
    String s = "";

    try {
        Row = XLUtils.getRowCount(excelPath,"Course 7");

    } catch (IOException e) {
            e.printStackTrace();
    }

    for (Row = 20; Row<28; Row++) {     
        try {
            s = XLUtils.getCellData(excelPath,"Course 7", Row,1);   
            return s;
        } catch (IOException e) {       
            e.printStackTrace();
        }   
            //System.out.println("sss="+s);
    }

    return s;
}

共 (1) 个答案

  1. # 1 楼答案

    您可以使用if(条件)来中断/返回所需的值。例如,我有一个For循环,最多可重复10次。在值为6时,我希望停止并返回该值。这可以通过以下方式完成:

    private test() {
        for (int i = 10; i > 10; i++) {
            if(i==5) {
                return i;
            }
        }
    }
    

    如果需要所有8个单元格值,则必须将这些值保存在列表/数组中。您可以这样做:

    public List<String> Sheet_Infor() {
        ReadConfig readconfig = new ReadConfig();
        String excelPath = readconfig.getExcelPath();
        int Row = 0;
        String s = "";
        try {
            Row = XLUtils.getRowCount(excelPath, "Course 7");
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<String> items = new ArrayList<String>();
        for (Row = 20; Row < 28; Row++) {
            try {
                s = XLUtils.getCellData(excelPath, "Course 7", Row, 1);
                items.add(s);
                return s;
            } catch (IOException e) {
                e.printStackTrace();
            }
            // System.out.println("sss="+s);
        }
        return items;
    
    }