Help with Delimiters/While loops
* This is project 17 and it asks to create a code that uses delimiters/while loops to add or subtract numbers, but I have no idea how to code that! I used the s.contains("-") and s.contains("+") in two if statements with while loops in them, but it wouldn't work. Please tell me the best way to code where an addition and subtraction sign will work! Please get me to the right direction! :(hi):
* I really, really apologizing for not specifying the title of what I needed help with! I'll make sure to do so in the future!!
Project… Add ‘em Up
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).
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
By, "wouldn't work" I meant to say that the program prints out a negative number(sorry). My code is here below:
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.
boolean sa = s.contains("-");
sc.useDelimiter("\\s*\\+\\s*");
int sum = 0;
while(sc.hasNextInt( ))
{
if(sa == true)
{
sc.useDelimiter("\\s*\\-\\s*");
sum = sum - sc.nextInt( );
}
else
{
sum = sum + sc.nextInt( );
}
}
System.out.println("Sum is: " + sum);
}
}
It prints -8 :/
Re: Help with Delimiters/While loops
Please edit the post and wrap the code in code tags. See: BB Code List - Java Programming Forum
Please explain what "wouldn't work" means. Did you get errors or did the program give wrong results.
Re: Help with Delimiters/While loops
I've re-edited it Norm, I hope I explicated a little further.
Re: Help with Delimiters/While loops
Why do all the statements start in the first column? Statements should be indented 3-4 spaces to show their nesting logic level within if statements and methods.
Can you copy the console's contents that shows the input and output from when the program is executed?
With windows: To copy the contents of the command prompt window:
Click on Icon in upper left corner
Select Edit
Select 'Select All' - The selection will show
Click in upper left again
Select Edit and click 'Copy'
Paste here.
Re: Help with Delimiters/While loops
I was only taught how to use the bluej complier so Norm can I paste the results from the console?
Re: Help with Delimiters/While loops
Sorry, I don't know anything about bluej. It's hard to understand the problem without seeing the console from when the program executes.
The posted code still needs formatting.
Re: Help with Delimiters/While loops
Ok I'll reedit code with indents and post bluej's console results.
Re: Help with Delimiters/While loops
You need to give us the output for a run, as we have no idea (at least from reading the OP) what values you put in to get -8 out.
Also you really need to indent your code...
Re: Help with Delimiters/While loops
You need to rethink your algorithm.
If the equation contains a '-' you set a flag to true. Then if that flag is true you subtract the next int from the sum. It will subtract ALL ints and not just the one preceded by a '-'. If input is 8-3 then the result will be -11 (0 - 8 - 3). Since you only get -8 I'm assuming the call to hasNextInt fails and only the 8 is subtracted.
1 Attachment(s)
Re: Help with Delimiters/While loops
Ok here is the code (reindented)
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.
boolean sa = s.contains("-");
sc.useDelimiter("\\s*\\+\\s*");
int sum = 0;
while(sc.hasNextInt( ))
{
if(sa == true)
{
sc.useDelimiter("\\s*\\-\\s*");
sum = sum - sc.nextInt( );
}
else
{
sum = sum + sc.nextInt( );
}
}
System.out.println("Sum is: " + sum)
}
}
Output is in the screenshot
Attachment 4090
Re: Help with Delimiters/While loops
Quote:
Originally Posted by
Junky
You need to rethink your algorithm.
If the equation contains a '-' you set a flag to true. Then if that flag is true you subtract the next int from the sum. It will subtract ALL ints and not just the one preceded by a '-'. If input is 8-3 then the result will be -11 (0 - 8 - 3). Since you only get -8 I'm assuming the call to hasNextInt fails and only the 8 is subtracted.
Ok that makes sense, but how would I set the program to switch between each easily? a nested if statement? Store the ones with positives in front in one variable, and store the ones with negatives in front with another variable and add them together? I don't understand how to get to the point where it can accept +'s and -'s.
3 Attachment(s)
Re: Help with Delimiters/While loops
Ok I have somewhat good news! I've been able to recode where it adds or subtracts...but it still can't do both! Is there anyway you could tweak this so that it could?
Code:
public class Modded
{
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);
int sum=0;
if (s.contains("+"))
{
sc.useDelimiter("\\s*\\+\\s*");
while(sc.hasNextInt())
{
sum=sum+sc.nextInt();
}
}
if (s.contains("-"))
{
sc.useDelimiter("\\s*\\-\\s*");
while(sc.hasNextInt())
{
sum=sc.nextInt()-sc.nextInt();
}
}
System.out.println("Sum is: "+sum);
}
}
This is what happens with just negatives (only 2 numbers work):
Attachment 4091
With Positives (Positives allow more than 2):
Attachment 4092
And both(doesn't work)
Attachment 4093
Any suggestions would be awesome! :)
Re: Help with Delimiters/While loops
The contents of the images is too small to read. Can you copy the console contents and paste it here?
Also add some comments to the console output explaining what the problem is and what you want the program to do differently.
Re: Help with Delimiters/While loops
1st Console:
Enter something like 8 + 33 + 1345 - 137: 33 - 2
Sum is: 31
(It does that correctly)
2nd
Enter something like 8 + 33 + 1345 -137: 8 + 3 + 3
Sum is: 14
(That also is done correctly)
3rd
Enter something like 8 + 33 + 1345 -137: 8 + 3 -1
Sum is: 8
(The program should be able to ADD and SUBTRACT
That's what I need it to do. It needs to allow for addition and subtraction to coexist in one problem, and it needs to let me regardless of the order(except for the leading number it is always positive)
Re: Help with Delimiters/While loops
Quote:
needs to allow for addition and subtraction to coexist
You need to redesign the logic for the problem.
The posted code only works for simple input like: 2 + 3 and 4 - 5
Before writing any more code, work on a design. Write the steps the code needs to do in pseudo code and post the steps here. We'll help you get a design that will work on longer strings of numbers with + and -
When you have a design that works, then code it.
Re: Help with Delimiters/While loops
1. Enter an arithmetic expression that adds and subtracts numbers on the same line(leading number positive)
2. An string.contains checks for a positive sign
3. It adds up all the numbers until it hits a negative sign
4. It switches to a "-" delimiter and subtracts from the sum
5. It pulls out the sum
6. The output of the sum is printed
Re: Help with Delimiters/While loops
For step 2, what if the first sign is a - and the last sign is a +. The String contains a + but there are -s before it. Step 2 does not work.
How do steps 3 & 4 work? If there is a + first, when does the code see that there is now a -???
Steps 2 & 3 need to be re-worked.
What if there were a class with methods that would return the next tokens from the String one after the other. First a number then an operator (+ or -) then another number then another operator etc to the end of the String.
Re: Help with Delimiters/While loops
I see what you mean, but I still don't understand..How would you make the program switch from addition to subtraction without doing only one? That's the only part I don't understand at all.
Re: Help with Delimiters/While loops
Pseudo code:
initialize total to value of first token (a number)
begin loop continue until no more tokens
get next token (an operator)
get next token (a number)
update total using operator and number
end loop
Re: Help with Delimiters/While loops
Norm, I still don't understand one thing: How do you switch between delimiters without it messing up?!