我正在尝试编写一个程序来对复数进行算术运算。复数在输入中以String形式给出。我想将字符串转换为实部和虚部。这样做我需要帮助。
下面的代码是我一直在尝试的
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
从字符串的开头做部分匹配。