0

I feel like I've tried everything, searched everything I know to search, and I've been working on this for about 6 classes now.

I'm trying to make a program that accepts a string input like "6 + 6 -3+ 2", and can add/subtract everything to output the correct answer. I got it to work with either addition or subtraction at one time (can't do anything like "6 + 6 - 3") and there also always have to be a space between any digit. It also can't add multi-digit numbers, but I'll worry about that once it can correctly add/subtract in the first place.

So I don't think I'm understand how Scanner and delimiters work, (since that's what the chapter is on) but I can't seem to find anything online that's helped me understand what I'm doing wrong.

This is what I have so far:

package addEmUp;

import java.util.*;

public class TesterShell {
    public static void main(String[] args){
        Scanner kbIn = new Scanner(System.in);

        System.out.print("Enter some addition/subtraction problem: ");
        String s = kbIn.nextLine();

        Scanner numChecker = new Scanner(s);
        Scanner valueChecker = new Scanner(s);

        numChecker.useDelimiter("\\s*\\+\\s*|\\s*\\-\\s*");
        int sum = 0;

        while(numChecker.hasNext()){
            if(valueChecker.next().equals("-")){
                sum = sum - numChecker.nextInt();
            }
            else{
                sum = sum + numChecker.nextInt();
            }
            System.out.println(sum); //Just for checking what's going on, will remove in the end
        }

        System.out.println("Sum = " + sum);
    }
}

Based on the other questions I've found on StackOverflow, a better way to do this would be to use index, but the Chapter I'm in set me up with a shell program using strings and scanner.

What am I missing here? What did I misunderstand/not understand at all?

ananaso
  • 167
  • 2
  • 15
  • See this post: http://stackoverflow.com/questions/4589951/parsing-an-arithmetic-expression-and-building-a-tree-from-it-in-java or this one: http://stackoverflow.com/questions/1432245/java-parse-a-mathematical-expression-given-as-a-string-and-return-a-number – Jorge Campos Dec 10 '13 at 19:02

1 Answers1

2

For plain addition/subtraction you can do something simple like

String[] nums = s.replaceAll(" ", "").replaceAll("\\+", " ")
        .replaceAll("-", " -").split(" ");
int res = 0;
for (String n : nums) {
    if (!n.isEmpty())
        res += Integer.parseInt(n);
}
Konstantin
  • 3,254
  • 15
  • 20
  • Well, I was looking for a way to use delimiter since that's what my tutorial/book was looking for, but w/e. I think I'll switch to the official Java Tutorials now, since they seem much more clear than my current tutorial (who would'a thunk?). Also, some stuff I didn't know in there (but now I do, since I looked it up to understand this answer), like arrays. Thanks! – ananaso Dec 10 '13 at 21:48