What does line.split(",")[1] mean [Java]?
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()
.
String numbers = "1.21,2.13,3.56,4.0,5";
String[] array = numbers.split(",");
split the input line by commmaString second = array[1];
get the second element from the array. Java array numeration starts from0
index.double crtValue = Double.valueOf(second);
convertString
todouble
Don't forget about NumberFormatException
that may be thrown if the string does not contain a parsable double
.
SmashCode
Updated on July 09, 2022Comments
-
SmashCode almost 2 years
I came across code where i had encountered with
Double.valueOf(line.split(",")[1])
I am familiar withDouble.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 about 8 years
-
SomeJavaGuy about 8 years
line#split
returns an array,[1]
acceses the second element of the returned array. -
fge about 8 years@KevinEsche uhm, no, the 2nd element; unless you mean element at index 0 to be the 0th element
-
SomeJavaGuy about 8 years@fge you´re right, fixed it.
-