java - Adding and Subtracting numbers from a String -
this program takes in string , adds integers in it, have set delimiter "+" surrounded amount of white space. works fine want work negative integers well, instance if input "8 + 33 + 1,345 - 37"; output 41.it doesn't 1,345 or subtracts -37 total. delimiters "skipped" ? instance, correct if compiler goes 8 , '+' skipped goes 33? , if set delimiter "\s*\+|-\s*" (an attempt of + or -), output still 41, why?
import java.util.*; import java.io.*; public class add_em_up { public static void main (string args []) { scanner x = new scanner (system.in); system.out.print("enter 8 + 33 + 1,345 + 137 :"); string s = x.nextline(); scanner sc1 = new scanner (s); sc1.usedelimiter("\\s*\\+\\s*"); int sum = 0; while (sc1.hasnextint()) { sc1.skip(",*"); if (sc1.hasnextint()) { sum = sum + sc1.nextint(); } } system.out.println("sum is: " + sum); } }
just put +, - inside character class.
sc1.usedelimiter("\\s*[-+]\\s*");
Comments
Post a Comment