如何扫描文本文件的第一行是否有两个整数,省略任何字符串?

时间:2010-11-13 14:26:51

标签: integer java.util.scanner text-files

我必须在文本文件的第一行搜索两个Int值,这两个值将是2D数组的维度。以下是我到目前为止...谢谢!

 try {
        Scanner scan = new Scanner(f);
            int rows = scan.nextInt();
            int columns = scan.nextInt();
        String [][] maze = new String[rows][columns];
     }

1 个答案:

答案 0 :(得分:0)

另一种方式:

// read your file
File f = new File("file.txt"); 

// make sure your file really exists
if(f.exists()) {  

    // a buffered reader is standard for reading files in Java
    BufferedReader bfr = new BufferedReader(new FileReader(f));

    // read the first line, that's what you need
    String line = bfr.readLine();

    // assuming your integers are separated with a whitespace, use this splitter
    // if they're separated with a comma, the use line.split(",");
    String[] integers = line.split(" ");

    // get the first integer
    int i1 = Integer.valueOf(integers[0]);

    // get the second integer
    int i2 = Integer.valueOf(integers[1]);

    System.out.println(i1);
    System.out.println(i2);

    // finally, close buffered reader to avoid any leaks
    bfr.close();
}

我会将异常处理留给您。如果您的文件不存在,无法读取,或者第一行的第一和第二部分不是整数,您将有例外。如果它们是否定的,那就没关系。

注意:您没有指定第一行的外观。我在这段代码中假设它们位于开头,用空格分隔。

如果不是,那么您也可以使用字符串拆分,但是您必须检查每个拆分的部分是否可以转换为整数。如果第一行中有3个或更多整数,则会有歧义。因此,我的假设。