您好我有一串数字,并希望将它们放入浮点数组中,以便我可以访问这些值。
// this bit works fine, data is split into string array.
String fdata[] = data.split(",");
Float array_f[] = new Float(fdata.length);
// this is the bit which throws an error and causes my app to crash.
for (int i = 0; i < fdata.length; i++){
float y = Float.parseFloat(fdata[i]);
array_f[i] = y;
}
错误是
java nullpointerexception:尝试调用虚方法 java对象上的java.lang.string java.lang.split(java.lang.string) 参考
感谢
除此之外,我想我需要解释一下,所以我提供了更多的代码来展示我想要做的事情。
String data; //does this need to define the number of bytes needed then?
start_Acq.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
channel_a = String.valueOf(channel_Acq.getSelectedItem());
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
connection.start_acquisition(channel_a);
data = connection.start_acquisition(channel_a);
connection.stop_acquisition();
}catch (Exception e ){
e.printStackTrace();
}
}
});thread.start();
data_recived.setText(data);
String fdata[] = data.split(",");
Float array_f[] = new Float[fdata.length];
for(int i = 0; i<fdata.length; i++){
float y = Float.parseFloat(fdata[i]);
array_f[i] = y;
}
}
});
答案 0 :(得分:2)
您的代码的问题是初始化,您所要做的就是使用原始float而不是Float:
String data = "123,5468,1,25,36";
String fdata[] = data.split(",");
float array_f[] = new float[fdata.length];
for (int i = 0; i < fdata.length; i++){
array_f[i] = Float.parseFloat(fdata[i]);
System.out.println(array_f[i]);
}
答案 1 :(得分:1)
首先,data
为空;修复它并尝试这个
float y = java.lang.Float.parseFloat(fdata[i]);
答案 2 :(得分:1)
您的数组初始化错误,应该像
Float array_f[] = new Float[fdata.length];
经过长度你应该有一个分号而不是','
for (int i=0; i<fdata.length;i++){
修改强> 试试这个它会起作用
String fdata[] = new String[]{"6.5", "8.5"}; //this bit works fine, data is split into string array.
Float array_f[] = new Float[fdata.length];
for (int i = 0; i < fdata.length; i++) { //this is the bit which throws an error and causes my app to crash.
float y = Float.parseFloat(fdata[i]);
array_f[i] = y;
}
System.out.println(Arrays.asList(array_f));
答案 3 :(得分:0)
使用此 将字符串数组转换为字符串,然后转换float
for(int i=0;stringarray.length>i;i++){float_var = Float.valueOf(string_array.get(i)); float_array.add(float_var);}
然后添加浮点数组