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

I came across code where I came across Double.valueOf(line.split(",")[1]) I am familiar with Double.valueOf() and my problem is to understand what [1] means offer. Searching for documents did not find anything.

 while ((line = reader.readLine()) != null) double crtValue = Double.valueOf(line.split(",")[1]); 
+5
source share
4 answers

This means that your line is a string of numbers separated by commas.
for example: "12.34,45.0,67.1"

line.split(",") returns an array of strings.
for example: {"12.34","45.0","67.1"}

line.split(",")[1] returns the 2nd value (since indexes start at 0) of an array element.
e.g. 45.0

+9
source

This means that line is a line starting with a,b , where b is actually a number.

crtValue - double b value.

+3
source

Java public String[] split(String regex)

Separates this line around matches for a given regular expression.

it

Returns: an array of strings calculated by breaking this string around matches of a given regular expression

So, [1] gets the second element of the array found in String[] .

+3
source

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


  • String numbers = "1.21,2.13,3.56,4.0,5";
  • String[] array = numbers.split(","); splits the input string into commma
  • String second = array[1]; get the second element from the array. Java array numbering starts at index 0 .
  • double crtValue = Double.valueOf(second); convert String to double

Do not forget about a NumberFormatException that can be thrown if the line does not contain parsing double .

+2
source

Source: https://habr.com/ru/post/1246412/


All Articles