我正在研究线性系统求解器,我希望用户能够一次性输入整个等式,而不是分别输入每个数字。
我试图将字符串拆分为“+”和“=”(等式格式为(ax + by = c))但它将加号之后的第二部分拆分为“by = c”而不是只是“通过”。
这是我的代码:
System.out.print("Enter Your First Equation (ax + by = c): " );
String eq1 = sc.nextLine();
String[] part = eq1.split("\\+");
String[] part2 = eq1.split("\\=");
String result = part[0];
String result2 = part[1];
String result3 = part2[1];
double a1 = Double.parseDouble(result);
double b1 = Double.parseDouble(result2);
double c1 = Double.parseDouble(result3);
System.out.print("Enter Your Second Equation (ax + by = c): " );
String eq2 = sc.nextLine();
String[] part3 = eq1.split("\\+");
String[] part4 = eq1.split("\\=");
String result4 = part3[0];
String result5 = part3[1];
String result6 = part4[1];
double a2 = Double.parseDouble(result4);
double b2 = Double.parseDouble(result5);
double c2 = Double.parseDouble(result6);
System.out.println("Your Equations Are (1) " + a1 + "x + " + b1 + "y = " + c1);
System.out.println(" (2) " + a2 + "x + " + b2 + "y = " + c2);
答案 0 :(得分:1)
String.split不会给你想要的结果,我猜这将是“ax”,“by”,因为它必须寻找一个分裂的标记并将剥离该标记。
尝试模式和匹配,使用此正则表达式:(\ d *)([a-zA-Z] +)|(\ d +)。
e.g:
public static void main(String[] args) {
String exp = "53x+6y=30";
String pattern = "(\\d*)([a-zA-Z]+)|(\\d+)";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(exp);
while (m.find( )) {
System.out.println("Found value: " + m.group(0) );
}
}
输出
Found value: 53x
Found value: 6y
Found value: 30
答案 1 :(得分:0)
如果你坚持使用String.split()方法,那么我想你可以这样做(就像一个例子):
String eq = "ax+by=c";
String[] splitStrg1 = eq.split("=");
String[] splitStrg2 = splitStrg1[0].split("\\+");
String part1 = splitStrg2[0];
String part2 = splitStrg2[1];
String part3 = splitStrg1[1];
System.out.println("Part 1 is: " + part1);
System.out.println("Part 2 is: " + part2);
System.out.println("Part 3 is: " + part3);