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

4

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]);
Szombathely answered 4/4, 2016 at 13:25 Comment(4)
docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.htmlLapel
line#split returns an array, [1] acceses the second element of the returned array.Arielariela
@KevinEsche uhm, no, the 2nd element; unless you mean element at index 0 to be the 0th elementRust
@Rust you´re right, fixed it.Arielariela
N
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

Nathannathanael answered 4/4, 2016 at 13:27 Comment(0)
C
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.

Curvature answered 4/4, 2016 at 13:28 Comment(0)
B
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[].

Bangup answered 4/4, 2016 at 13:29 Comment(0)
A
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.

Ard answered 4/4, 2016 at 13:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.