首页 文章

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

提问于
浏览
7

我正在做练习,我必须从键盘输入一个字符串 . 该字符串将是简单的算术,例如“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);
        }
    }
}

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

7 回答

  • -2

    如果你想消除数字,留下一个操作数数组,除了正或负之外的字符:

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

    fyi,当一个减号在字符类中是第一个或最后一个时它是一个字面减去(否则它是一个范围)

  • -2

    请尝试使用 split()JavaDoc)方法 . 这更容易 .

    "8 + 33 + 1345 + 137".split("\\+|\\-")
    

    应该返回一个带数字的数组 .

  • 2

    您可以使用以下代码

    "8 + 33 + 1345 + 137".split("(\\s\\d*\\s)|(\\s\\d*)|(\\d*\\s)")
    

    这里正则表达式检查字符串中的数字以及它之前/之后/周围的空格 .

    这个拆分返回数组 [, +, +, +]

    除非字符串以/ - 开头,否则第一个位置将始终为空,您可以从[1]位置访问数组

  • -1

    在这里,希望这有助于......

    您将要看到的代码可以解决所有基本方程式,这意味着它可以求解 only 在等式中包含 .+-* 和/或 / 符号的方程式 . 该等式还可以加,减,倍,和/或除小数 . 这 cannot 求解包含 x^y(x)[x] 等的方程式 .

    public static boolean isNum(String e) {
        String[] num=new String[] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"};
        boolean ret=false;
        for (String n : num) {
            if (e.contains(n)) {
                ret=true;
                break;
            }
        }
        return ret;
    }
    public static boolean ifMax(String[] e, int i) {
        boolean ret=false;
        if (i == (e.length - 1)) {
            ret=true;
        }
        return ret;
    }
    
    
    public static String getResult(String equation) {
        String[] e=equation.split(" ");
        String[] sign=new String[] {"+", "-", "*", "/"};
        double answer=Double.parseDouble(e[0]);
        for (int i=1; i<e.length; i++) {
            if (isNum(e[i]) != true) {
                if (e[i].equals(sign[0])) {
                    double cc=0;
                    if (ifMax(e, i) == false) {
                        cc=Double.parseDouble(e[i+1]);
                    }
                    answer=answer+(cc);
                } else if (e[i].equals(sign[1])) {
                    double cc=0;
                    if (ifMax(e, i) == false) {
                        cc=Double.parseDouble(e[i+1]);
                    }
                    answer=answer-(cc);
                } else if (e[i].equals(sign[2])) {
                    if (ifMax(e, i) == false) {
                       answer=answer*(Double.parseDouble(e[i+1]));
                    }
                } else if (e[i].equals(sign[3])) {
                    if (ifMax(e, i) == false) {
                       answer=answer/(Double.parseDouble(e[i+1]));
                    }
                }
            }
        }
        return equation+" = "+answer;
    }
    

    这是一个例子:

    Input:

    System.out.println(getResult("1 + 2 + 3 + 4 / 2 - 3 * 6"));
    

    Output:

    1 + 2 + 3 + 4 / 2 - 3 * 6 = 12
    
  • -1
    int total = 0;
        final String s = "9 - 15";
        final String[] arr = s.split(" ");
        int i = 0;
        while (i != arr.length)
        {
            switch (arr[i])
            {
                case ("+"):
                    total += Integer.parseInt(arr[++i]);
                    break;
                case ("-"):
                    total -= Integer.parseInt(arr[++i]);
                    break;
                case ("*"):
                    total *= Integer.parseInt(arr[++i]);
                    break;
                case ("/"):
                    total /= Integer.parseInt(arr[++i]);
                    break;
                default:
                    total = Integer.parseInt(arr[i++]);
            }
            if (i == arr.length - 1)
            {
                break;
            }
        }
        System.out.println(total);
    

    希望这可能会帮助你.... thnx

  • 4

    试试这个:

    String str = ...
    int total = 0;
    int operand;
    for(int  i = 0; i < str.length(); i++){
        if(Character.isWhiteSpace(str.charAt(i)))
        ; // empty
        else if(Character.isDigit(str.charAt(i))){
            StringBuilder number = new StringBuilder();
            while(Character.isDigit(str.charAt(i))){
                number.append(str.charAt(i));
                i++;
            }
            operand = Integer.parseInt(number.toString);
        }
        else if(str.charAt(i)) == '+')
            total += operand;
        else if(str.charAt(i)) == '-)
            total -= operand;
        else
            throw new IllegalArgumentException();
    }
    

    对于非法入境,你当然应该做更好的检查 . 我刚刚给了你这个主意 .

  • 1

    下面的代码可以只计算运算符“和”的序列 - “我希望它有用

    public class test1 {
    
    public static void main(String[] args) {
        String s= "9-15";
        s=s+"/"; /* add / to execute the last operation */
        String split[]= new String[s.length()];
        for (int i=0;i<split.length;i++){   /* split the string to array */
            split[i]=s.substring(i,i+1);
        }
        String val1="",op="+"; /* val1 : container of the value before the operator to calculate it with total
                                  op : the operator between val1 and val2 at the begin is + */
        int som=0;
        for (int i=0;i<split.length;i++){
            try{
                val1=val1+Integer.parseInt(split[i]); /* saving the number after the operation in a string to calculate it,
                                                     a number format exception is throwing when the case don't contain integer*/ 
            }catch(NumberFormatException e){
                if(op.equals("+"))  {
                    som=som+Integer.parseInt(val1); /*calculate the total */
                    val1=""; /*initialize val1 to save the second number */
                    op=split[i]; /* save the operator of the next operation */
                }else{
                if(op.equals("-"))  {
                    som=som-Integer.parseInt(val1);
                    val1="";
                    op=split[i];
                }
            }
            }
        } 
        System.out.println(som);
    }
    }
    

相关问题