[英]Java split cant make it work for negative numbers
我的教授要求我们制作一个简单的加减法计算器,但输入必须是整个表达式,如“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;
}
这是我的代码,它适用于前两个示例,但不适用于第一个 integer 为负数的最后一个示例,例如“-8+10”,不,我不能以任何其他方式做到这一点。 我必须在单个字符串中输入整个表达式。
您可以用(?<=\\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
为负数,您仍然可以将它们相加以获得正确的结果。
您可以通过始终从 0 开始并将每个“部分”应用为数字或运算符来解决此问题。 此解决方案还允许任意长度,因此您不仅限于 2 个数字。
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");
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.