9

I came across code where i had encountered with Double.valueOf(line.split(",")[1]) I am familiar with Double.valueOf() and my problem is to understand what does [1] mean in the sentence. Searched docs didn't find anything.

while ((line = reader.readLine()) != null)
                double crtValue = Double.valueOf(line.split(",")[1]);
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
SmashCode
  • 741
  • 1
  • 8
  • 14

4 Answers4

14

It means that your line is a String of numbers separated by commas.
eg: "12.34,45.0,67.1"

The line.split(",") returns an array of Strings.
eg: {"12.34","45.0","67.1"}

line.split(",")[1] returns the 2nd(because indexes begin at 0) item of the array.
eg: 45.0

dryairship
  • 6,022
  • 4
  • 28
  • 54
3

It means line is a string beginning with a,b where b is in fact a number.

crtValue is the double value of b.

dejvuth
  • 6,986
  • 3
  • 33
  • 36
3

Java public String[] split(String regex)

Splits this string around matches of the given regular expression.

It

Returns: the array of strings computed by splitting this string around matches of the given regular expression

So the [1] gets the 2nd item of the array found in String[].

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
2

Your code tries to get the second double value from reader.readLine().


  1. String numbers = "1.21,2.13,3.56,4.0,5";
  2. String[] array = numbers.split(","); split the input line by commma
  3. String second = array[1]; get the second element from the array. Java array numeration starts from 0 index.
  4. double crtValue = Double.valueOf(second); convert String to double

Don't forget about NumberFormatException that may be thrown if the string does not contain a parsable double.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142