2017-10-19 52 views
2

我想從控制檯輸入座標,格式爲(x1,y1)輸入距離公式的Java代碼(1,2)(2,3)

如何從輸入中只選擇數字(並避免使用括號)? 我知道我將不得不使用正則表達式解析輸入,但不知道怎麼做,該代碼

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)); 
    } 
} 
+0

數據是否必須在(x,y)的格式? – Deadron

+0

是的,輸入是多對,格式爲(x,y) – user8534573

+0

您不必使用正則表達式。你可以簡單地去掉支架。 – logger

回答

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

+0

修復語法錯誤,爲什麼只有單個數字的整數? – laune

+1

修正了,謝謝 – i0xHeX

+0

我一定會經過TutorialsPoint給出的例子...謝謝! – user8534573