I have figured out how to do this. All that is needed is the .useDelimeter error. help?

import java.io.*;
import java.util.*;
public class AddEmUp{public static void main(String args[])
{
`Scanner sc = new Scanner(System.in);

System.out.print("Enter something like 8 + 33 + 1,345 - 137 : ");String s = sc.nextLine();

`if((s.charAt(0)!='+')&&(s.charAt(0)!='-'))

 `s = "+" + s;

Scanner sc1=new Scanner(s);sc1.useDelimeter("\s\+\s|\s-\s");

`int sum = 0;

while(sc1.hasNextInt()){`

 `if(sc1.findInLine("\\s*\\+\\s*")!=null)

   `sum = sum + sc1/nextInt();
 `else
   `sc1.nextInt();

}

Scanner sc2 = new Scanner(s);sc2.useDelimeter("\s\+\s|\s-\s");

while(sc2.hasNextInt()){`

 `if(sc2.findInLine("\\s*-\\s*")!=null)

   `sum=sum - sc2.nextInt();
 `else
   `sc2.nextInt();

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

Recommended Answers

All 12 Replies

Literal \ characters in Java Strings need to be "escaped" - ie replaced with a double \
You did that in the findInLine, but not in your useDelimiter

It must not have posted correctly. In my code that i have on my computer i have a double \ in the useDelimeter

OK, in that case, after another look I can see the problem. Check the API documentation for Scanner, you have mis-spelled the name of the method.
Next time please post (copy/paste) the complete text of your error message(s) - that would have enabled me to identify the fault immediately.

My appologies. How do I correctly spell the method?

It's in the API documentation, which should be open on your desktop all the time you are writing anything in Java. It's your absolutly essential reference doc.
http://docs.oracle.com/javase/7/docs/api/

Thank You this helps a lot.

Please mark as Solved.
Glad your issue was fixed.

I have tried to mark it solved. I believe that my computer will not let me mark it.

Its the pale blue button "Mark Question Solved" just below the entry field for submitting a reply, which is just below this message.

i clicked it multiple times. it still doesnt mark it.

That's odd, but never mind - I'll mark it for you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.