Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在循环内部处理异常后,读入停止_Java_Oop_Indexoutofboundsexception - Fatal编程技术网

Java 在循环内部处理异常后,读入停止

Java 在循环内部处理异常后,读入停止,java,oop,indexoutofboundsexception,Java,Oop,Indexoutofboundsexception,我有一个很奇怪的问题。在抛出并处理我的ReaderException异常后,在第一次出现异常时,我的读入仍然停止。有人能解释一下为什么会这样吗 输入: Hotel Paradis;Strada Ciocarliei, Cluj-Napoca 400124;46.779862;23.611739;7;200;8;250;1;400 Hotel Sunny Hill;Strada Fagetului 31A, Cluj-Napoca 400497;46.716030;23.573740;4;150;

我有一个很奇怪的问题。在抛出并处理我的ReaderException异常后,在第一次出现异常时,我的读入仍然停止。有人能解释一下为什么会这样吗

输入:

Hotel Paradis;Strada Ciocarliei, Cluj-Napoca 400124;46.779862;23.611739;7;200;8;250;1;400
Hotel Sunny Hill;Strada Fagetului 31A, Cluj-Napoca 400497;46.716030;23.573740;4;150;6;190
Golden Tulip Ana Dome;Strada Observatorului 129, Cluj-Napoca 400352;46.751989;23.576580;0;330;0;350;0;600
代码:

public HotelDescriptor readLine(最后一行字符串)抛出ReaderException{
系统输出打印项次(行);
字符串信息[]=行。拆分(“;”);
用于(字符串i:info)
系统输出打印LN(i);
字符串tempname=info[0];
字符串tempaddress=info[1];
float templatitudeh=float.parseFloat(信息[2]);
float-templanginiteh=float.parseFloat(信息[3]);
int singleroom=Integer.parseInt(信息[4]);
int singleprice=Integer.parseInt(信息[5]);
int doubleroom=Integer.parseInt(信息[6]);
int doubleprice=Integer.parseInt(信息[7]);
int suiteeRoom=Integer.parseInt(信息[8]);
int suiteprice=Integer.parseInt(信息[9]);
Hotel tempHotel=新酒店(tempname、tempaddress、templatitudeh、TemplongIdeh、单人房、单人房、双人房、双人房、套房间、套房价格);
System.out.println(tempHotel.getName());
返回坦普尔酒店;
}
公共列表读取文件(最终字符串){
try(BufferedReader buff=new BufferedReader(new FileReader(hotels))){
字符串行=”;
而((line=buff.readLine())!=null){try{
添加(readLine(line));
}捕获(ReaderException e){
e、 printStackTrace();
}捕获(阵列索引边界外异常){
例如printStackTrace();
}
//line=buff.readLine();
}
}catch(filenotfounde异常){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
返回hotelData;
}

我认为hotelData被声明为类字段(类全局)

在读取文本文件时,您应该考虑可能发生(或不发生)的一些异常情况。可以采取简单的步骤来确保该文本文件的读取相对成功。如果您的应用程序正在创建文本文件,那么您的成功率将显著提高,因为您可以控制文本文件的编写方式。但是,如果您的应用程序没有创建文本文件,或者文本文件是从远程源编译的,那么成功率可能会降低,除非采取措施确保预期结果

在我看来:

  • 文本文件应可识别,以确保 实际上正在读取文本文件以进行处理。如果文本数据来自 一个CSV文件,然后一个CSV标题行应该是第一行 在文件中,应读取并比较此行 以验证访问的文件是否正确。这是 如果文件可由任意数量的用户选择,则尤其如此 用户(可能通过文件选择器)。如果文件标识符 (或描述符)行在文本文件中不作为 文件,也许你应该考虑使用一个,即使它是 考虑一个注释行,该行可能以 作为行的第一个字符的分号()。任何东西 可以将文件标识为要处理的正确文件
  • 空白行和任何被视为注释行的行应 忽略。这包括已知为实际数据的任何文件行 线条无论它们是什么。通常,需要几行代码 由if语句和一些条件组成的 处理好这种情况
  • 永远不要指望实际的数据行(您将需要的数据行 处理)保存所有预期需要的数据。这是 尤其是在使用 方法,例如Integer.parseInt()Float.parseFloat(),作为 仅仅是例子。这实际上是你所在地区最大的问题 情况。记下您提供的示例数据行 在你的岗位上。第一行由10个分隔的字符组成 数据,第二个数据行由8个分隔的数据段组成 数据,第三行同样由10个分隔符组成 数据。这里的问题是第二条数据线。什么时候 此行被拆分,结果将是一个数组(info[]),该数组 将包含8个元素(索引0到7),但是readLine()方法是 希望始终处理由10个元素组成的数组 (索引0至9)。在处理第二行数据时,猜猜看是什么 当代码行
    int suiteeRoom=Integer.parseInt(信息[8])时发生被点击。没错,你会得到一个
    arrayindexoutofbounds异常,因为在info[]数组中根本没有索引8。您需要在代码中处理类似的情况,并准备好处理它们。不要依赖
    异常处理为您处理业务。整个想法
    就是尽量避免例外,如果有必要的话。我不相信这是其中之一
如果没有对代码类的访问,我将自然地假设您的方法返回是有效的,并且按计划运行。考虑到这一点,我将如何格式化Hotels文本文件:

My App Name - Hotels Data File

;Hotel Name; Hotel Address; Latitude; Longtitude; Single Room; Single Price; Double Room; Double Price; Suite Room; Suite Price

Hotel Paradis;Strada Ciocarliei, Cluj-Napoca 400124;46.779862;23.611739;7;200;8;250;1;400
Hotel Sunny Hill;Strada Fagetului 31A, Cluj-Napoca 400497;46.716030;23.573740;4;150;6;190
Golden Tulip Ana Dome;Strada Observatorului 129, Cluj-Napoca 400352;46.751989;23.576580;0;330;0;350;0;600
文件的第一行是文件描述符行。第二行是一个空行,只是为了更方便地查看文件。第三行被视为注释行,因为在本例中,它以分号()开头。实际上,由您决定创建文件的位置
My App Name - Hotels Data File

;Hotel Name; Hotel Address; Latitude; Longtitude; Single Room; Single Price; Double Room; Double Price; Suite Room; Suite Price

Hotel Paradis;Strada Ciocarliei, Cluj-Napoca 400124;46.779862;23.611739;7;200;8;250;1;400
Hotel Sunny Hill;Strada Fagetului 31A, Cluj-Napoca 400497;46.716030;23.573740;4;150;6;190
Golden Tulip Ana Dome;Strada Observatorului 129, Cluj-Napoca 400352;46.751989;23.576580;0;330;0;350;0;600
public HotelDescriptor readLine(final String line) {
    // Split on various possible combinations of how the
    // delimiter might be formated within a file line.
    String info[] = line.split(" ; |; |;"); 
    // Variables declaration and default initialization values
    String tempname = "";
    String tempaddress = "";
    float templatitudeh = 0.0f;
    float templongitudeh = 0.0f;
    int singleroom = 0;
    int singleprice = 0;
    int doubleroom = 0;
    int doubleprice = 0;
    int suiteroom = 0;
    int suiteprice = 0;

    String strg; // Used to hold the current Array Element in the for/loop
    String regExF = "-?\\d+(\\.\\d+)?"; // RegEx to validate a string float or double value.
    String regExI = "\\d+";             // RegEx to validate a string Integer value.
    for (int i = 0; i < info.length; i++) {
        strg = info[i].trim(); // remove leading/trailing spaces if any
        switch (i) {
            case 0:
                tempname = info[i];
                break;
            case 1:
                tempaddress = info[i];
                break;
            case 2:
                // Is it a float or double numerical value
                if (strg.matches(regExF)) {
                    templatitudeh = Float.parseFloat(info[i]);
                }
                break;
            case 3:
                // Is it a float or double numerical value
                if (strg.matches(regExF)) {
                    templongitudeh = Float.parseFloat(info[i]);
                }
                break;
            case 4:
                // Is it a Integer numerical value
                if (strg.matches(regExI)) {
                    singleroom = Integer.parseInt(info[i]);
                }
                break;
            case 5:
                // Is it a Integer numerical value
                if (strg.matches(regExI)) {
                    singleprice = Integer.parseInt(info[i]);
                }
                break;
            case 6:
                // Is it a Integer numerical value
                if (strg.matches(regExI)) {
                    doubleroom = Integer.parseInt(info[i]);
                }
                break;
            case 7:
                // Is it a Integer numerical value
                if (strg.matches(regExI)) {
                    doubleprice = Integer.parseInt(info[i]);
                }
                break;
            case 8:
                // Is it a Integer numerical value
                if (strg.matches(regExI)) {
                    suiteroom = Integer.parseInt(info[i]);
                }
                break;
            case 9:
                // Is it a Integer numerical value
                if (strg.matches(regExI)) {
                    suiteprice = Integer.parseInt(info[i]);
                }
                break;
        }
    }

    Hotel tempHotel = new Hotel(tempname, tempaddress, templatitudeh, templongitudeh, 
            singleroom, singleprice, doubleroom, doubleprice, suiteroom, suiteprice);
    System.out.println(tempHotel.getName());
    return tempHotel;
}

public List<HotelDescriptor> readFile(final String hotels) {
    try (BufferedReader buff = new BufferedReader(new FileReader(hotels))) {
        String line;
        int lineCounter = 0;
        while ((line = buff.readLine()) != null) {
            // Trim any leading or trailing spaces (spaces, tabs, etc)
            line = line.trim();
            lineCounter++; 
            // Is this the right file to read?
            if (lineCounter == 1) {
                if (!line.equalsIgnoreCase("My App Name - Hotels Data File")) {
                    //No it isn't...
                    JOptionPane.showMessageDialog(this, "Invalid Hotels Data File!",
                            "Invalid Data File", JOptionPane.WARNING_MESSAGE);
                    break; // Get out of while loop
                }
                // Otherwise skip the File Descriptor line.
                else { continue; }
            }
            // Is this a blank or Comment line...
            // Lines that start with ; are comment lines
            if (line.equals("") || line.startsWith(";")) {
                // Yes it is...skip this line.
                continue;
            }
            // Process the data line...
            hotelData.add(readLine(line));
        }
    }
    catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    catch (IOException e) {
        e.printStackTrace();
    }

    return hotelData;
}