What does line.split(",")[1] mean [Java]?

25,909

Solution 1

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

Solution 2

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[].

Solution 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.

Solution 4

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.

Share:
25,909
SmashCode
Author by

SmashCode

Updated on July 09, 2022

Comments

  • SmashCode
    SmashCode almost 2 years

    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]);
    
    • Reimeus
      Reimeus about 8 years
    • SomeJavaGuy
      SomeJavaGuy about 8 years
      line#split returns an array, [1] acceses the second element of the returned array.
    • fge
      fge about 8 years
      @KevinEsche uhm, no, the 2nd element; unless you mean element at index 0 to be the 0th element
    • SomeJavaGuy
      SomeJavaGuy about 8 years
      @fge you´re right, fixed it.