英文:
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;
}
这是我的代码,对于前两个示例可以工作,但对于第三个示例,其中第一个整数是负数,例如"-8+10",不能正常工作,我不能以其他方式进行操作,必须在单个字符串中输入整个表达式。
英文:
My professor asked us to make a simple calculator for addition and subtraction but the input has to be the whole expression like "5-5", "60+70" or "-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;
}
This is my code, and it works for the first two examples but not the last one where the first integer is a negative, e.g. "-8+10", and no I cannot do it any other way. I have to input the whole expression in the single string.
答案1
得分: 2
你可以用 (?<=\\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)"); //按有符号数字分割
int a = Integer.parseInt(split[0]); //第一个数字在索引0
int b = Integer.parseInt(split[1]); //第二个数字在索引1
sum = a + b; //你不需要操作符。只需将a和b相加即可获得正确结果
System.out.println(sum);
你可以去掉 operator
。请注意,如果 a
或 b
为负数,仍然可以将它们相加以获得正确的结果。
英文:
You can replace your regex by (?<=\\d)(?=\\D)
. This is looking for occurences of (non digit)(digit) pairs.<br><br>For yours examples:<br>
5-5 => "5" and "-5"<br>
60+70 => "60" and "+70"<br>
-8+10 => "-8" and "+10"<br>
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);
You can get rid of operator
. Notice, if a
or b
will be negative, you still can just add them to get the correct result.
答案2
得分: 0
你可以通过始终从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");
}
}
}
英文:
You can fix this by always starting with 0 and applying each 'part' as a number or an operator. This solution also allows an arbitrary length, so you are not limited to only 2 numbers.
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");
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论