chostwales
chostwales

Reputation: 89

Get 2 doubles from a string

I am passing some data from another class. This string I pass is:

"23 n 5"

Now I have 2 instance Double variables called a and b.

My aim is to take this and place 23 in a and 5 in b. The n is a splitter. Any number can be either side.

i'm sure the code must be really simple here. But, i'm not sure what to put in. Any help would be greatly appreciated.

  public Double x(String x){
        if (x.contains(" n ")){
 <code need help on> }

Upvotes: 0

Views: 74

Answers (3)

user2513392
user2513392

Reputation:

public void x(String x)
{
    if (x.contains(" n "))
    {
        String[] s = x.split(" n ");
        a = Double.parseDouble(s[0]);
        b = Double.parseDouble(s[1]);
    }
}

Upvotes: 4

AsSiDe
AsSiDe

Reputation: 1846

Try This:

String[]arr=x.trim().split("n");
double a=Double.parseDouble(arr[0]);
double b=Double.parseDouble(arr[1]);

Upvotes: 1

M A
M A

Reputation: 72854

Use String#split:

String[] split = input.split(" n ");  // the argument can be a regular expression

Upvotes: 5

Related Questions