如何"分隔"给定字符串中的整数?

9 java regex loops pattern-matching delimiter

我正在做练习,我必须从键盘输入一个字符串.该字符串将是简单的算术,例如"2 + 4 + 6 - 8 + 3 - 7".是的,格式必须是这样的.中间有单个空格.

这个想法是采取这个字符串,并最终打印出答案.到目前为止,这是我的代码:

public class AddemUp {
  public static void main(String[] args) {
    Scanner kb = new Scanner(System.in);
    System.out.print("Enter something like 8 + 33 + 1345 + 137: ");
    String s = kb.nextLine();
    Scanner sc = new Scanner(s);
    sc.useDelimiter("\\s*\\+\\s*|\\s*\\-\\s*");
    int sum = 0;
    int theInt;
    Scanner sc1 = new Scanner(s);
    sc1.useDelimiter("\\s*\\s*");
    String plusOrMinus = sc1.next();
    int count = 0;
    if(s.startsWith("-"))
    {
        sum -= sc.nextInt();
    }
    while(sc.hasNextInt())
    {
        theInt = sc.nextInt();
        if(count == 0)
        {
            sum += theInt;
        }
        else if(plusOrMinus.equals("+"))
        {
            sum += theInt;
        }
        else
        {
            sum -= theInt;
        }
        sc1.next();
        count++;
    }
    System.out.println("Sum is: " + sum);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

在第25行,"sc1.delimiter"所在的位置,我不知道如何让代码跳过所有整数(以及空格)并仅隔离"+"或" - ".一旦实现,我可以简单地将其实现到while循环中.

Jir*_*ser 2

尝试使用split()( JavaDoc ) 方法代替。这要容易得多。

"8 + 33 + 1345 + 137".split("\\+|\\-")
Run Code Online (Sandbox Code Playgroud)

应该返回一个带有数字的数组。