How can I "distinguish" an integer from a given string?

I am doing an exercise where I need to enter a line from the keyboard. The string will be simple arithmetic, such as "2 + 4 + 6 - 8 + 3 - 7". Yes, the format should be like that. Single spaces between them.

The idea is to take this line and eventually print the answer to it. So far this is my code:

public class AddemUp { public static void main(String[] args) { Scanner kb = new Scanner(System.in); System.out.print("Enter something like 8 + 33 + 1345 + 137: "); String s = kb.nextLine(); Scanner sc = new Scanner(s); sc.useDelimiter("\\s*\\+\\s*|\\s*\\-\\s*"); int sum = 0; int theInt; Scanner sc1 = new Scanner(s); sc1.useDelimiter("\\s*\\s*"); String plusOrMinus = sc1.next(); int count = 0; if(s.startsWith("-")) { sum -= sc.nextInt(); } while(sc.hasNextInt()) { theInt = sc.nextInt(); if(count == 0) { sum += theInt; } else if(plusOrMinus.equals("+")) { sum += theInt; } else { sum -= theInt; } sc1.next(); count++; } System.out.println("Sum is: " + sum); } } } 

On line 25, where "sc1.delimiter" is located, I don’t know how to make the code skip all integers (with spaces) and select ONLY "+" or "-". Once this is achieved, I can simply inject it into the while loop.

+9
source share
8 answers

If you want to exclude numbers by leaving an array of operands, separate the characters other than plus or minus:

 String[] ops = str.split("[^+-]+"); 

fyi, when the minus sign is the first or last in the character class, this is the literal minus (otherwise it is a range)

+4
source

Try using split() ( JavaDoc ) instead . It is much simpler.

 "8 + 33 + 1345 + 137".split("\\+|\\-") 

should return an array with numbers.

+2
source

You can use the code below

  "8 + 33 + 1345 + 137".split("(\\s\\d*\\s)|(\\s\\d*)|(\\d*\\s)") 

here the regular expression checks the digit in the string and the space before / after / around it.

This split returns an array of [, +, +, +]

The first place will always be empty, if the line does not start with + / -, you can access the array from position [1]

+1
source

I would not use the Scanner for this, I would use pattern matching. They are opposite in that the scanner wants a separator between the characters you want, and pattern matching identifies the characters you want instead.

To find only operators, you could have this ...

  Pattern p = Pattern.compile("[+-]"); Matcher m = p.matcher("2 + 4 + 6 - 8 + 3 - 7"); while (m.find()) { String token = m.group(0); System.out.println(token); } 

Logic can be easy to handle when numbers and operators are together in a loop. That is why I turn it on.

  Pattern p = Pattern.compile("([^\\s]+)(?:\\s+|$)"); Matcher m = p.matcher("2 + 4 + 6 - 8 + 3 - 7"); while (m.find()) { String token = m.group(1); System.out.println(token); } 

regex101 is a good site for testing regular expressions.

0
source

Try this instead:

 String str = ... int total = 0; int operand; for(int i = 0; i < str.length(); i++){ if(Character.isWhiteSpace(str.charAt(i))) ; // empty else if(Character.isDigit(str.charAt(i))){ StringBuilder number = new StringBuilder(); while(Character.isDigit(str.charAt(i))){ number.append(str.charAt(i)); i++; } operand = Integer.parseInt(number.toString); } else if(str.charAt(i)) == '+') total += operand; else if(str.charAt(i)) == '-) total -= operand; else throw new IllegalArgumentException(); } 

Of course, you should do a more accurate check for illegal entries. I just gave you this idea.

-one
source

In the code below, you can only calculate the sequence of '+' and '-' operators. I wish this is useful

 public class test1 { public static void main(String[] args) { String s= "9-15"; s=s+"/"; /* add / to execute the last operation */ String split[]= new String[s.length()]; for (int i=0;i<split.length;i++){ /* split the string to array */ split[i]=s.substring(i,i+1); } String val1="",op="+"; /* val1 : container of the value before the operator to calculate it with total op : the operator between val1 and val2 at the begin is + */ int som=0; for (int i=0;i<split.length;i++){ try{ val1=val1+Integer.parseInt(split[i]); /* saving the number after the operation in a string to calculate it, a number format exception is throwing when the case don't contain integer*/ }catch(NumberFormatException e){ if(op.equals("+")) { som=som+Integer.parseInt(val1); /*calculate the total */ val1=""; /*initialize val1 to save the second number */ op=split[i]; /* save the operator of the next operation */ }else{ if(op.equals("-")) { som=som-Integer.parseInt(val1); val1=""; op=split[i]; } } } } System.out.println(som); } } 
-one
source
 int total = 0; final String s = "9 - 15"; final String[] arr = s.split(" "); int i = 0; while (i != arr.length) { switch (arr[i]) { case ("+"): total += Integer.parseInt(arr[++i]); break; case ("-"): total -= Integer.parseInt(arr[++i]); break; case ("*"): total *= Integer.parseInt(arr[++i]); break; case ("/"): total /= Integer.parseInt(arr[++i]); break; default: total = Integer.parseInt(arr[i++]); } if (i == arr.length - 1) { break; } } System.out.println(total); 

hope this can help you .... thnx

-2
source

Here you go, hope this helps ...

The code that you are about to see can solve all the basic equations, which means that it can solve the equations in which it only contains . , + , - , * and / or / in the equation. This equation can also add, subtract, multiply and / or divide decimal numbers. This one cannot solve equations containing x^y , (x) , [x] , etc.

 public static boolean isNum(String e) { String[] num=new String[] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"}; boolean ret=false; for (String n : num) { if (e.contains(n)) { ret=true; break; } } return ret; } public static boolean ifMax(String[] e, int i) { boolean ret=false; if (i == (e.length - 1)) { ret=true; } return ret; } public static String getResult(String equation) { String[] e=equation.split(" "); String[] sign=new String[] {"+", "-", "*", "/"}; double answer=Double.parseDouble(e[0]); for (int i=1; i<e.length; i++) { if (isNum(e[i]) != true) { if (e[i].equals(sign[0])) { double cc=0; if (ifMax(e, i) == false) { cc=Double.parseDouble(e[i+1]); } answer=answer+(cc); } else if (e[i].equals(sign[1])) { double cc=0; if (ifMax(e, i) == false) { cc=Double.parseDouble(e[i+1]); } answer=answer-(cc); } else if (e[i].equals(sign[2])) { if (ifMax(e, i) == false) { answer=answer*(Double.parseDouble(e[i+1])); } } else if (e[i].equals(sign[3])) { if (ifMax(e, i) == false) { answer=answer/(Double.parseDouble(e[i+1])); } } } } return equation+" = "+answer; } 

And here is an example of this:

Input:

 System.out.println(getResult("1 + 2 + 3 + 4 / 2 - 3 * 6")); 

Output:

 1 + 2 + 3 + 4 / 2 - 3 * 6 = 12 
-2
source

All Articles