输入的距离公式的Java代码(1,2)(2,3)

时间:2017-10-19 19:51:55

标签: java

我正在尝试从控制台获取输入坐标,其形式为(x1,y1)

如何从输入中仅选择数字(并避免括号)? 我知道我将不得不使用正则表达式并解析输入,但不知道如何为此代码执行此操作

import java.io.*;

public class main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] input1 = br.readLine().split(",");
        String[] input2 = br.readLine().split(",");
        double x1 = Double.valueOf(input1[0]);
        double y1 = Double.valueOf(input1[1]);


        double x2 = Double.valueOf(input2[0]);
        double y2 = Double.valueOf(input2[1]);

        double result = Math.sqrt(((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)));
        System.out.println(String.valueOf(result));
    }
}

1 个答案:

答案 0 :(得分:0)

是的,您应该使用正则表达式从文本中获取数字。 像这样:

String input = br.readLine();
// Compile you pattern with two groups to capture each num
Pattern pattern = Pattern.compile("\\((\\d+(\\.\\d+)?),(\\d+(\\.\\d+)?)\\)");
// Match your input
Matcher matcher = pattern.matcher(input);
// If your input matches to pattern you want, then you take numbers
if (matcher.find()) {
    double x = Double.parseDouble(matcher.group(1);
    double y = Double.parseDouble(matcher.group(3);
    //... Other code you need
}

最后,我建议您阅读有关正则表达式的更多信息,例如:Regular Expressions TutorialsPoint