Java的split无法处理负数。

huangapple go评论88阅读模式
英文:

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(&quot;(?&lt;=\\d)(?=\\D)|(?&lt;=\\D)(?=\\d)&quot;);

int a = Integer.parseInt(split[0]);
int b = Integer.parseInt(split[2]);

String operator = split[1];

switch (operator) {

    case &quot;+&quot;:
        sum = a + b;
        System.out.println(sum);
        break;

    case &quot;-&quot;:
        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

你可以用 (?&lt;=\\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("(?&lt;=\\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。请注意,如果 ab 为负数,仍然可以将它们相加以获得正确的结果。

英文:

You can replace your regex by (?&lt;=\\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(&quot;(?&lt;=\\d)(?=\\D)&quot;); //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&#39;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(&quot;-8+12&quot;).evaluate());
  }
}

class Expression {

  public List&lt;Part&gt; parts;

  public Expression(String expression) {
    String[] split = expression.split(&quot;(?&lt;=\\d)(?=\\D)|(?&lt;=\\D)(?=\\d)&quot;);
    this.parts = Stream.of(split).map(Part::new).collect(Collectors.toList());

  }

  public Double evaluate() {
    double total = 0;
    Operator currentOperator = new Operator(&quot;+&quot;);
    
    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 &quot;+&quot;:
        return first + second;
      case &quot;-&quot;:
        return first - second;
      default:
        throw new RuntimeException(&quot;Not a valid operator&quot;);
    }
  }
}

You can play around with this solution here.

huangapple
  • 本文由 发表于 2020年8月5日 15:41:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/63260524.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定