我的教授让我们做一个简单的加法和减法计算器,但是输入必须是像"5-5“、"60+70”或"-8+10“这样的整个表达式。
Scanner console = new Scanner(System.in);
int sum;
String expression = console.nextLine();
String[] split = expression.split("(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)");
int a = Integer.parseInt(split[0]);
int b = Integer.parseInt(split[2]);
String operator = split[1];
switch (operator) {
case "+":
sum = a + b;
System.out.println(sum);
break;
case "-":
sum = a - b;
System.out.println(sum);
break;
}这是我的代码,它适用于前两个示例,但不适用于最后一个示例,其中第一个整数是负数,例如"-8+10",不,我不能用任何其他方法。我必须在单个字符串中输入整个表达式。
发布于 2020-08-05 07:50:57
您可以用(?<=\\d)(?=\\D)替换正则表达式。这是寻找出现(非数字)(数字)对。
关于你的例子:
5-5 => "5“和"-5”
60+70 => "60“和"+70”
-8+10 => "-8“和"+10”
int sum;
Scanner console = new Scanner(System.in);
String expression = console.nextLine();
String[] split = expression.split("(?<=\\d)(?=\\D)"); //split by signed numers
int a = Integer.parseInt(split[0]); //First numer at index 0
int b = Integer.parseInt(split[1]); //Second numer at index 1
sum = a + b; //You don't need operator. Instead just add a and b
System.out.println(sum);你可以摆脱operator。注意,如果a或b为负值,则仍然可以添加它们以获得正确的结果。
发布于 2020-08-05 08:00:14
您可以通过始终以0开头并将每个“部件”作为数字或运算符来修复此问题。此解决方案还允许任意长度,因此您不仅限于两个数字。
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
System.out.println(new Expression("-8+12").evaluate());
}
}
class Expression {
public List<Part> parts;
public Expression(String expression) {
String[] split = expression.split("(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)");
this.parts = Stream.of(split).map(Part::new).collect(Collectors.toList());
}
public Double evaluate() {
double total = 0;
Operator currentOperator = new Operator("+");
for (Part currentPart : parts) {
if (currentPart.isNumber()) {
total = currentOperator.apply(total, currentPart.getNumberValue());
} else {
currentOperator = new Operator(currentPart.value);
}
}
return total;
}
}
class Part {
public String value;
public Part(String value) {
this.value = value;
}
public double getNumberValue() {
return Double.parseDouble(this.value);
}
public boolean isNumber() {
try {
double number = Double.parseDouble(this.value);
return true;
} catch (Exception e) {
return false;
}
}
}
class Operator {
public String value;
public Operator(String value) {
this.value = value;
}
public double apply(double first, double second) {
switch(this.value) {
case "+":
return first + second;
case "-":
return first - second;
default:
throw new RuntimeException("Not a valid operator");
}
}
}https://stackoverflow.com/questions/63260524
复制相似问题