简体   繁体   中英

Coordinates in Java from file

I'm trying to read some coordinates in from a file and get their x and y values as integers so that I can work out the distance between two points. I've managed to use Scanner to grab some numbers from each line, but the method now seems to be reading each digit as a separate number. So when I get use sample data of:

(25, 4) (1, -6)

I end up getting:

(2, 5) (4, 1)

The code I'm using to get the numbers from file and to output the answer is:

import java.io.File;
import java.util.Scanner;

public class Main{
    public static void main(String[] args) throws Exception{
        File file = new File(args[0]);
        Scanner sc = new Scanner(file);
        sc.useDelimiter("\\D*");
        while(sc.hasNext()){
            double xOne = sc.nextInt();
            double yOne = sc.nextInt();
            double xTwo = sc.nextInt();
            double yTwo = sc.nextInt();
            sc.nextLine();
            System.out.println(xOne + "," + yOne + "," + xTwo + "," + yTwo);
            int d = (int)Math.sqrt(Math.pow((xTwo - xOne), 2) + Math.pow((yTwo - yOne), 2));
            System.out.println(d);
        }
        sc.close();
    }
}

The regular expression \\D* matches any sequence of non-digits, including an empty one. Because it matches the empty string, your scanner is going to read one character at a time.

Write

sc.useDelimiter("\\D+");

instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM