题目

确认思路
1.字符串输入,想找未知数的字母如a,v,b..
2.将字符串以等号为界限作为两部分处理
3.不要忘记打印未知数以及=号
代码书写
1.先用静态static固定未知数变量->单个未知数因此用字符的形式
2.通过api正则表达式找出所有未知数
3.将其转为字符进行赋值

4.书写方法,对等号两边的加减号进行处理
5.对于变成+号全省略不进行添加与空客添加保持一致,方便以后进行处理

6.处理含有未知数的项的系数,并将其添加到变量e中
7.发现没系数的话(及系数为一,进行了隐藏),确定符号后直接对未知数系数+1或-1

8.处理完未知数后,对常数进行添加到j中
注:这里对等式最后一项进行了处理,同时每次结束刷新StringBuilder
(其实这里直接用String也可以,但是我习惯用StringBuilder进行添加)

9.同时设置方法对式子进行处理,依次截取每一项

10.细节处理,浮点计算存在-0的情况,需要对其进行处理
(我也是不通过好多次,才慢慢发现的
)
总结 Java代码展示
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
static char x;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.next();
String b = "[a-zA-Z]{1}";
Pattern p = Pattern.compile(b);
Matcher m = p.matcher(a);
m.find();
x= m.group().toCharArray()[0];
y(a );
}
public static boolean flag (char c){
if (c =='+' || c=='-' || c=='=' ){
return true;
}
return false;
}
public static void y (String a){
double e=0;
double j =0;
int d=a.length();
StringBuilder c=new StringBuilder();
for (int i = 0; i < a.length(); i++) {
if (a.charAt(i) =='='){
d=i;
continue;
}
if (i<d) {
if (a.charAt(i) =='+'){
c=new StringBuilder();
continue;
}
} else {
if (a.charAt(i)=='-'){
continue;
}
if (i==d+1&& (a.charAt(i)!='-'|| a.charAt(i)!='+')){
c.append('-');
}
if (a.charAt(i)=='+'){
c.append('-');
continue;
}
}
if (a.charAt(i)==x){
String f = c.toString();
if (f.length()==0){
e+=1;
c=new StringBuilder();
continue;
}
if (f.charAt(0)=='-' && f.length()==1) {
e+=-1;
c=new StringBuilder();
continue;
}
e+= Integer.parseInt(f);
c=new StringBuilder();
continue;
}
c.append(a.charAt(i));
String b =c.toString();
if (i==a.length()-1 || flag(a.charAt(i+1)) ){
j+= Integer.parseInt(b);
c = new StringBuilder();
}
}
System.out.print(x+"=");
double u = j/e;
if (u==0 || u==-0){
System.out.println("0.000");
}else {
System.out.printf("%.3f", -j / e);
}
}
}
|
感谢各位的观看,这是我现在水平想的比较方便的方案,有不足的地方请见谅(●’◡’●)(~ ̄▽ ̄)~