java - 我怎样才能 "delimit"来自给定字符串的整数?

标签 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);
    }
  }
}

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

最佳答案

如果你想消除数字,留下一个操作数数组,拆分字符 other 而不是加号或减号:

String[] ops = str.split("[^+-]+");

仅供引用,当减号是字符类中的第一个或最后一个时,它是一个文字减号(否则它是一个范围)

关于java - 我怎样才能 "delimit"来自给定字符串的整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13851588/

相关文章:

javascript - 从函数内访问循环变量

javascript - 在Javascript中映射数组数组的每个数组的第一个元素

java.lang.NoSuchMethodError 在 Cloudbees 追我

java - 有没有办法将 Java 注释作为参数传递?

java - 多模块maven VS 微服务架构

python - 我误解了 Python 正则表达式吗?

正则表达式:如何删除每行冒号之前的所有内容

python - 我怎样才能更具体地使用这个正则表达式?

java - TextView中的Android文本单词之间的距离很长

php - 如果在循环中使用 MySQLi 准备好的语句,我什么时候调用bind_param?