简体   繁体   English

line.split(“,”)[1]是什么意思[Java]?

[英]What does line.split(“,”)[1] mean [Java]?

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. 我遇到过我遇到Double.valueOf(line.split(",")[1])代码Double.valueOf(line.split(",")[1])我熟悉Double.valueOf() ,我的问题是要理解[1]在句子中的含义。 Searched docs didn't find anything. 搜索过的文档没有找到任何内容。

while ((line = reader.readLine()) != null)
                double crtValue = Double.valueOf(line.split(",")[1]);

It means that your line is a String of numbers separated by commas. 这意味着您的line是由逗号分隔的数字字符串。
eg: "12.34,45.0,67.1" 例如: "12.34,45.0,67.1"

The line.split(",") returns an array of Strings. line.split(",")返回一个字符串数组。
eg: {"12.34","45.0","67.1"} 例如: {"12.34","45.0","67.1"}

line.split(",")[1] returns the 2nd (because indexes begin at 0) item of the array. line.split(",")[1]返回数组的第2个 (因为索引从0开始)项。
eg: 45.0 例如: 45.0

It means line is a string beginning with a,b where b is in fact a number. 这意味着line是一个以a,b开头的字符串a,b其中b实际上是一个数字。

crtValue is the double value of b . crtValuebdouble值。

Java public String[] split(String regex) 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[] . 所以[1]得到String[]找到的数组的第二项。

Your code tries to get the second double value from reader.readLine() . 您的代码尝试从reader.readLine()获取第二个double值。


  1. String numbers = "1.21,2.13,3.56,4.0,5";
  2. String[] array = numbers.split(","); split the input line by commma 通过commma分割输入行
  3. String second = array[1]; get the second element from the array. 从数组中获取第二个元素。 Java array numeration starts from 0 index. Java数组计数从0索引开始。
  4. double crtValue = Double.valueOf(second); convert String to double String转换为double

Don't forget about NumberFormatException that may be thrown if the string does not contain a parsable double . 如果字符串不包含可解析的double ,请不要忘记可能抛出的NumberFormatException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM