ฉันจะสแกนบรรทัดแรกของไฟล์ข้อความเพื่อหาจำนวนเต็มสองตัวโดยไม่ใส่สตริงใด ๆ ได้อย่างไร

ฉันต้องค้นหาบรรทัดแรกของไฟล์ข้อความเพื่อหาค่า Int สองค่าที่จะเป็นขนาดของอาร์เรย์ 2 มิติ นี่คือสิ่งที่ฉันมีจนถึงตอนนี้...ขอบคุณ!

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

person Trevor Arjeski    schedule 13.11.2010    source แหล่งที่มา
comment
คุณจำเป็นต้องใช้ Scanner หรือไม่?   -  person Ignacio Vazquez-Abrams    schedule 13.11.2010
comment
ใช้ นิพจน์ทั่วไป   -  person khachik    schedule 13.11.2010
comment
ไม่ นั่นเป็นความชอบส่วนตัวของฉันเอง   -  person Trevor Arjeski    schedule 13.11.2010


คำตอบ (1)


อีกวิธีหนึ่ง:

// 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 ตัวขึ้นไปในบรรทัดแรก จะเกิดความคลุมเครือ ดังนั้นสมมติฐานของฉัน

person darioo    schedule 13.11.2010