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?