jov
jov

Reputation: 63

Using Scanner for separating a string

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

Upvotes: 0

Views: 66

Answers (4)

sujit amin
sujit amin

Reputation: 131

public static void main(String[] args) {

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

s.useDelimiter("\\+");

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

}

Upvotes: 0

XtremeBaumer
XtremeBaumer

Reputation: 6435

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

Upvotes: 1

John Mitchell
John Mitchell

Reputation: 472

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.

Upvotes: 0

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());

}

Upvotes: 1

Related Questions