[英]Java splitting separating imaginary and real part of a Complex number
我正在嘗試編寫一個程序來對復數執行算術運算。 復數在輸入中以字符串形式給出。 我想將字符串轉換為實部和虛部。 為此我需要幫助。
下面的代碼是我一直在嘗試的
public float getreal(String c){
//String s[] = c.split("[\\Q+-\\Ei]");
//System.out.println(s[0]+" "+s[1]);
int postion_plus=c.indexOf('+');
int position_i=c.indexOf('i');
System.out.println(c.substring(0, postion_plus));
return Float.parseFloat(c.substring(0,postion_plus));
}
該代碼似乎適用於正數,但是對於負復數(如-5.5 + 4i)會引發錯誤
這段代碼只是為了獲得真正的一部分
String[] okSamples = {"3", "-1.0", "7i", "i", "+i", "-i", "4-7i", "-3.4i", ".5", "3."};
String[] badSamples = {"", "1.0.5i", "+", "-"};
String doubleRegex = "[-+]?(\\d+(\\.\\d*)?|\\.\\d+)";
Pattern doublePattern = Pattern.compile(doubleRegex);
總體而言,這些案例過於繁瑣,無法正確處理並涵蓋大多數案例:
// Not okay:
Pattern complexPattern = Pattern.compile("(?<re>" + doubleRegex + "?)"
+ "(?<im>((" + doubleRegex + "i|[-+]?i))?)";
因此,用代碼處理案例。 例如:
double re = 0.0;
double im = 0.0;
Matcher m = doublePattern.matcher(c);
if (m.lookingAt()) {
re = Double.parseDouble(m.group());
c = c.substring(m.end());
m = doublePattern.matcher(c);
if (c.matches("[-+].*") && m.lookingAt()) {
im = Double.parseDouble(m.group());
c = c.substring(m.end());
if (!c.equals("i")) {
throw new NumberFormatException();
}
} else if (c.matches("[-+]i")) {
im = c.startsWith("-") ? -1.0 : 1.0;
} else {
throw new NumberFormatException();
}
} else if (c.matches("[-+]i")) {
im = c.startsWith("-") ? -1.0 : 1.0;
} else {
throw new NumberFormatException();
}
這樣可以更牢固地處理檢索。 lookingAt
從字符串開頭開始部分匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.