[英]Java - Store last characters in array
Is it possible to store the last characters from a string in an array as a double? 是否可以将数组中字符串的最后一个字符存储为double?
I have following string: 我有以下字符串:
String s="random number 230";
That means I would like to have the array to look like this: 这意味着我希望数组看起来像这样:
double array[] = {230}
I'm not sure what you are looking for, but based entirely on the example you gave, you could use this: 我不确定您在寻找什么,但是完全基于您给出的示例,您可以使用以下代码:
String[] words = s.split(" ");
String numberString = words[words.length-1];
try{
double[] array = new double[]{Double.parseDouble(numberString)};
}
catch(NumberFormatException e){
e.printStackTrace();
}
Explanation: 说明:
.split
turns a string into an array of strings based on some delimiter. .split
根据某个定界符将字符串转换为字符串数组。
I used a blank space (ie " "
). 我使用了一个空格(即
" "
)。
Then, I reference the last string in the array as numberString
. 然后,我将数组中的最后一个字符串引用为
numberString
。 The array size will only be 0
if s
is an empty string (which would be a different problem). 如果
s
是一个空字符串,则数组大小将仅为0
(这将是一个不同的问题)。
And then I use Double.parseDouble()
which tries to return a double
value represented in a string. 然后,我使用
Double.parseDouble()
尝试返回以字符串表示的double
Double.parseDouble()
值。 The try\\catch
block means that we are prepared that it might not work. try\\catch
块意味着我们已经准备好它可能无法工作。
More information on that last bit can be found here 关于最后一点的更多信息可以在这里找到
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.