0

我试图args[0]用作输入文件,但是当我运行程序时,我不断得到一个IndexOutOfBoundsException,尽管我很确定这args[0]是正确的参数。我在上一个程序中也遇到了这个问题,但我不知道我做错了什么。

代码:

import java.io.*;
import java.util.NoSuchElementException;
import java.util.Scanner;

public class SortTest {
public static void main(String args[]) throws FileNotFoundException {
    try {
        Scanner read = new Scanner(new File(args[0]));

        while (read.hasNextLine()) {
            String name = read.nextLine();
            read.nextLine();

            String line1 = read.nextLine();
            int sh = Integer.parseInt(line1.substring(0,2));
            int sm = Integer.parseInt(line1.substring(3));
            read.nextLine();
            String line2 = read.nextLine();
            int fh = Integer.parseInt(line2.substring(0,2));
            int fm = Integer.parseInt(line2.substring(3));

            if (fh<sh) {
                System.out.println("Times not in correct order.");
                return;
            } else if (fh==sh) {
                if (fm<sm) {
                    System.out.println("Times not in correct order.");
                    return;
                }
            } else {
                System.out.println(name + "\n" + sh + ":" + sm + "\n" + fh + ":" + fm);
            }

        }
        read.close();
    }
    catch (FileNotFoundException e) {
        System.out.println("Invalid file path.");
    }
    catch (NoSuchElementException n) {
        System.out.println("No readable text in file.");
    }
    catch (IndexOutOfBoundsException x) {
        System.out.println("Proper format is java LectureSortTest <input>");
    }
    catch (NumberFormatException num) {
        System.out.println("File contents not formatted correctly");
    }
}
}
4

0 回答 0