-3

I am trying to use Split method of String in java I have example like this.

String number  = Math.random() * 100 + "";
System.out.println("Number is : " + number);
String[] seprate = number.split(".");
System.out.println(seprate.length);

it should give me 2 Stack of array i mean 2 array element if value is like e.g. 67.90512897385857

but its not giving value like that

String number  = Math.random() * 100 + "";
System.out.println("Number is : " + number);
String[] seprate = number.split(".");
System.out.println(seprate.length);
System.out.println(seprate[1]);

its giving arrayindexoutbound exception.

Someone give idea why its giving like that?

Roman C
  • 49,761
  • 33
  • 66
  • 176
Kishan Bheemajiyani
  • 3,429
  • 5
  • 34
  • 68

5 Answers5

1

The String#split method takes a regular expression.

The "." in there means any character.

Escape your "." as such to signal a literal dot: number.split("\\.").

As Pieter De Bie points out, using java.util.regex.Pattern to safely escape your literals when passing literals to an argument that is going to be interpreted as a regular expression will help you a good deal.

In this case, you could use: number.split(Pattern.quote("."))

Community
  • 1
  • 1
Mena
  • 47,782
  • 11
  • 87
  • 106
1

You need to escape the dot. The split method takes a regular expression. From the docs:

Parameters:regex the delimiting regular expression

String[] seprate = number.split("\\.");
kai
  • 6,702
  • 22
  • 38
1

Split works with regex and you should use like this

number.split("\\.")
halil
  • 1,789
  • 15
  • 18
0

Pay attention to the documentation:

public String[] split(String regex)

Splits this string around matches of the given regular expression.

In a regular expression, . is any character (except newlines, usually).

So you are splitting at every character.

If you want to match only a dot, "\\." will work.

Has QUIT--Anony-Mousse
  • 76,138
  • 12
  • 138
  • 194
0
Double f = Math.random() * 100;
        String number  = String.valueOf(f);
        System.out.println("Number is : " + number);
        String[] seprate = number.split("\\.");
        System.out.println(seprate.length);

Please use this link for ur question.

The split() method in Java does not work on a dot (.)

Community
  • 1
  • 1
Pradeep
  • 1
  • 1