0

I'm trying to separate the numbers (including Double) from a string such as "4+5*(4.5+6)". I thought about using a scanner to separate the numbers from my string. I would like to hear if there is a better way to do it, and to know how can i do it with a Scanner? This is my code, just wanted to check if it works and it threw an Exception...

package testzehavit;

import java.util.Scanner;

public class main {

    public static void main(String[] args) {
        Scanner s= new Scanner("443+54+24");
        s.useDelimiter("+");
        System.out.println(s.next());

    }

}

Thank you

XtremeBaumer
  • 5,158
  • 1
  • 15
  • 44
jov
  • 53
  • 1
  • 2
  • 8

4 Answers4

1

The scanner delimiters are regex. The symbol '+' is used in regexes for saying "one or more times".

What you want to do is:

public static void main(String[] args) {
    Scanner s= new Scanner("443+54+24");
    s.useDelimiter("\\+");
    System.out.println(s.next());

}
  • thank you! what if i want to use more than one delimeter? (for example for the string "4+5*(4.5+6)" ). is it possible? – jov Dec 11 '17 at 08:11
  • Then use `\\+|\\*` – Tim Biegeleisen Dec 11 '17 at 08:12
  • You can @Jovani use `"[+*\\(\\)\\.\"]"` – YCF_L Dec 11 '17 at 08:14
  • 1
    @TimBiegeleisen's answer is good, but if I would be you I'll take a look at how regexes are built: https://en.wikipedia.org/wiki/Regular_expression and then you can use an online tool for trying your regexes (like https://regex101.com/ ) Also, you can focus on math, here's an example of questions about the topic: https://stackoverflow.com/questions/1631820/regular-expression-to-match-digits-and-basic-math-operators – Federico José Sorenson Dec 11 '17 at 08:15
1

Coming from this question/answer you have to escape the + since the method takes regular expressions and not literal strings. In Java you escape with double backslash \\. This code:

public static void main(String[] args) {
    Scanner s = new Scanner("443+54+24");
    s.useDelimiter("\\+");
    System.out.println(s.next());
}

prints 443

XtremeBaumer
  • 5,158
  • 1
  • 15
  • 44
0

Use String.contains(); method. You could put a regular expression that represents the range of numbers and operands inside that, or do a simple for-loop and parse each iteration to String to pass it as an argurment to contains method.

Sorry for not demonstrating any code but I'm on my phone. Google String.contains() and Regular Expression. You should be able to combine the two.

John Mitchell
  • 402
  • 2
  • 5
0

public static void main(String[] args) {

Scanner s = new Scanner("443+54+24");

s.useDelimiter("\\+");

System.out.println(s.next());

}

sujit amin
  • 73
  • 2
  • 5