简体   繁体   English

从文件中协调Java

[英]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. 我正在尝试从文件中读取一些坐标,并将它们的xy值作为整数,以便我可以计算出两点之间的距离。 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. 我已经设法使用Scanner从每一行中获取一些数字,但现在这个方法似乎是将每个数字作为一个单独的数字读取。 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. 正则表达式\\D*匹配任何非数字序列,包括空数字。 Because it matches the empty string, your scanner is going to read one character at a time. 因为它匹配空字符串,所以您的扫描仪将一次读取一个字符。

Write

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

instead. 代替。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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