Thursday, November 28, 2013

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!






Java 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);
}
}







No comments:

Post a Comment