Addition and Subtraction Program

I am making a program that adds and subtracts numbers. I need to be able to get the leading sign to be recognized, but this is causing problems. When I have a space between the leading sign and the leading number (- 2 - 3) it is not working, but when I have no space (-2 - 3) it is working. How do I solve this problem. Here is the code, and thanks for the help!

Code:

`import java.io.*;`

import java.util.*;

public class Tester

{

public static void main(String args[])

{

Scanner kb = new Scanner(System.in);

System.out.print("Enter something like 8 + 33 + 1,345 + 137 : ");

String s = kb.nextLine();

Scanner sc = new Scanner(s);

sc.useDelimiter("\\s+");

String operation;

int num;

int sum = 0;

int count = 0;

operation = "";

char ch = s.charAt(0);

while(sc.hasNextInt( ))

{

if(!(Character.isDigit(ch)))

{

operation = sc.next();

}

num = sc.nextInt();

if (count == 0)

{

sum = sum + num;

}

else if (operation.contains( "+" ))

{

sum = sum + num;

}

else if (operation.contains("-"))

{

sum = sum - num;

}

if(sc.hasNext())

{

operation = sc.next();

}

count++;

}

System.out.println("Sum is: " + sum);

}

}

Re: Addition and Subtraction Program

Quote:

How do I solve this problem

Re do the logic to handle the floating -

Re: Addition and Subtraction Program

I'm sorry, but I'm a beginner. Can you please tell me what it means to redo the logic to handle the floating?

Thanks for the help!

Re: Addition and Subtraction Program

What are the steps the program needs to do to parse its input?

Make a list describing what it should do.

Something like:

begin loop to scan through tokens on the expression

get next token

if token is number do this

if token is sign do that

end loop

evaluate what was found

The logic will need to consider what "state" it is in.

Did it just get a binary operator? What tokens are valid after an operator?

Did it just get a number? What tokens are valid after an operator? What are not valid?

Re: Addition and Subtraction Program

You need to distinguish between unary operators and binary operators; your expression has the following syntax: <unary>? <number <binary> {<unary> <number>*; your <number>s can be unsigned.

kind regards,

Jos

Re: Addition and Subtraction Program

Are you allowed to use regular expressions? If so, you can use reformat the string to allow proper parsing by the scanner. If you are not allowed to use that then here is a hint. Don't think of the string as a mathematical expression. Just think of it as a list of positive or negative numbers that need to be added together. This assumes of course that you are not checking for input errors such as "5 + 10 10 -4". Here, the second 10 has an implied + in front of it.

Regards,

Jim