如何打破if条件?

时间:2014-12-16 13:01:41

标签: java

package com.selenium.utitlity;

import java.io.File;
import java.io.IOException;
import java.util.Hashtable;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ReadRows {
    public static Hashtable<String, String> getRowValues(int row)
            throws IOException {
        File file = new File("./prop.xlsx");
        if (file.exists()) {
            Hashtable<String, String> table = new Hashtable<String, String>();
            XSSFWorkbook workbook = new XSSFWorkbook("./prop.xlsx");
            XSSFSheet sourceSheet = workbook.getSheet("Sheet1");
            int LastRow = sourceSheet.getLastRowNum();
            // GetHeading of the Row
            XSSFRow headerRow = sourceSheet.getRow(0);
            // Get Test Data
            XSSFRow sourceRow = sourceSheet.getRow(row);
            if (row > LastRow) {
                System.out.println("The row is out of range");
            } else {
                int lastColumn = headerRow.getLastCellNum();
                for (int i = 0; i < lastColumn; i++) {
                    table.put(headerRow.getCell(i).toString(), sourceRow
                            .getCell(i).toString());
                }
            }
            return table;
        } else {
            System.out.println("No such file is there in the directory");
            return null;
        }

    }
}

我试图在下面的代码中使用break或exit:

if (row > LastRow) {
                    System.out.println("The row is out of range");
                }

退出代码不返回表为NULL。但如果不使用休息,我会得到以下结果

The row is out of range
null

我不想打印null我想在行&gt;时使用break LASTROW

1 个答案:

答案 0 :(得分:1)

首先,我想指出if语句不是循环。它们可以递归使用,但这不属于它们的自然用途。为了打破或继续循环,您可以简单地使用breakcontinue关键字。

这些用于标记和未标记的上下文中。查看oracle docs以获得更深入的解释。

break用于终止forwhile&amp; do-while但不适用于您的上下文。你应该throw一个例外。然后,您可以捕获异常并做任何您想要做的事情。

然而,当您在循环中时,您可以在break语句中同时使用continueif

希望这有帮助。