练习题:第一行为数值i,接着的i的行为需要输入的算式,每行可能有三个数据或两个数据
程序员文章站
2022-03-19 11:37:43
...
思路:
- 获取数据,
split
分割形成数组 - 将数组传递给一个指定的解析类
解析类需要根据符号来判断运算类型,进行运算,并且返回结果 - 输出计算式子以及式子长度
解析类
package calculator;
import java.util.Arrays;
/**
* @author 青韵
* @date 2020/3/8 - 18:45
*/
public class Calculator {
private static char sign;
public static String calculate(String[] arr) {
char tempSign;
int arrStart;
if (haveSign(arr.length)) {
sign = arr[0].charAt(0);
arrStart = 1;
} else {
arrStart = 0;
}
tempSign = sign;
int[] ints = Arrays.stream(arr, arrStart, arr.length)
.mapToInt(Integer::parseInt).toArray();
return Equation.create(ints[0], ints[1], tempSign).formatEquation();
}
private static boolean haveSign(int len) {
return len == 3;
}
private static class Equation {
private int num1;
private int num2;
private char sign;
private int result;
public Equation(int num1, int num2, char sign) {
this.num1 = num1;
this.num2 = num2;
this.sign = sign;
}
public static Equation create(int num1, int num2, char sign) {
return new Equation(num1, num2, sign);
}
private void calculate() {
switch (sign) {
case 'a': {
sign = '+';
result = num1 + num2;
} break;
case 'b': {
sign = '-';
result = num1 - num2;
} break;
case 'c': {
sign = '*';
result = num1 * num2;
} break;
default: result = 0;
}
}
public String formatEquation() {
calculate();
return stringFormat();
}
private String stringFormat() {
return "" + num1 + sign + num2 + "=" + result;
}
}
}
主方法测试类
package calculator;
import java.util.Scanner;
/**
* @author 青韵
* @date 2020/3/8 - 19:23
*/
public class Main {
public static void main(String[] args){
String[] arr;
Scanner input = new Scanner(System.in);
int totalRow = input.nextInt();
input.nextLine();
// System.out.println("total = " + totalRow);
for (int i = 0; i <= totalRow; i++) {
System.out.println();
arr = input.nextLine().split(" ");
// System.out.println(Arrays.toString(arr));
String result = Calculator.calculate(arr);
System.out.println(result);
System.out.print(result.length());
}
}
}
上一篇: 基于骨骼的行为识别笔记
下一篇: 表单学习及练习