Thursday, November 28, 2013

Help With Project "Add 'em Up"?




Hello! I'm looking for someone who is very experience in Java and very familiar with the Scanner class to please help me with this project. I would really appreciate it! Anyway, here is the exact project, word for word:




-------------------------------------------------------------------------------------------------------------------------------------------------




Consider the following program that allows something like 8 + 33 + 1,345 +137 to be entered as



String input from the keyboard. A Scanner object then uses the plus signs (and any adjoining



whitespace) as delimiters and produces the sum of these numbers(1523).






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( ); //Best to store in a String and then create a new Scanner
//object; otherwise, it can get stuck waiting for input.
Scanner sc = new Scanner(s);
//Set delimiters to a plus sign surrounded by any amount of white space...or...
// a minus sign surrounded by any amount of white space.
sc.useDelimiter("\\s*\\+\\s*");
int sum = 0;
while(sc.hasNextInt( ))
{
sum = sum + sc.nextInt( );
}
System.out.println("Sum is: " + sum);
}
}




The output will typically look like this:

Enter something like 8 + 33 + 1,345 +137 : 8 + 33 + 1,345 + 137



Sum is: 1523




Now modify this program so as to allow either plus or minus signs. Don’t forget to allow for a



leading plus or minus sign on the first number in the sequence. If the leading number has no sign,



assume the number is positive. Your output should typically appear as follows:




Enter something like 8 + 33 + 1,345 -137 : 8 + 33+ 1,345 -137



Sum is: 1249




-------------------------------------------------------------------------------------------------------------------------------------------------




I've been trying for hours to get my code to work, and I've tried numerous different ways of attempting to do this, and they have all failed. I'm really getting frustrated and I would really appreciate it if you could post the correct answer in code and then explain why and how it works. If necessary, I will post my current code, but I don't think it's even close to correct at this point. Could anyone please help? Thanks!







No comments:

Post a Comment