我正在制作一个程序,将数据文件中的读取双数输出到数组中,向用户询问搜索号和替换值,输出原始数组(如果找到该值)和新数组。我已经多次编写代码并尝试解决
中发生的这个恼人的错误list = addData.toArray( new Double[0] );
但它无法正常工作:(我几乎完成了程序,它应该这样做:
例如:
你正在寻找什么? ==> 6.17 用它替换? ==> 3.21原始数据:[4.67,2.98,1.10,9.73,5.73]
搜索结果:数组中未找到6.17。
新阵列:[4.67,2.98,1.10,9.73,5.73]
有没有办法解决这个问题所以我的程序可以工作?
package solution;
import static java.lang.System.*;
import java.util.*;
import java.io.*;
public class Java6002 {
public static void main(String[] args) {
new Environment().run();
}
}
class Environment {
private int[] list;
public Environment() {
try {
Scanner fScan = new Scanner(new File("Java6002a.dat"));
ArrayList<Double> addData = new ArrayList<Double>();
while(fScan.hasNext()) {
addData.add(fScan.nextDouble());
list = addData.toArray(new Double[0]);
}
}catch(Exception e) { }
}
public void run() {
Scanner scan = new Scanner(in);
out.print("What are you searching for? => ");
double target = scan.nextDouble();
out.print("Replace it with? => ");
double update = scan.nextDouble();
out.println();
out.println("Original Data: " + this.toString());
out.print("Search Result: ");
if(replace(target,update))
out.println(target + " was found in the array.");
else
out.println(target + " was NOT found in the array.");
out.println();
out.println("New array: " + this);
}
public boolean replace(double t, double w)
{
for (int x=0; x<list.length; x++)
if (list[x] == t)
{
list[x] = w;
return true;
}
return false;
}
public String toString()
{
String temp="[";
for(int x=0;x<list.length;x++) temp+=list[x]+",";
temp+="]";
return temp;
}
}
答案 0 :(得分:0)
将列表数组的类型更改为Double
private Double[] list;
您正在尝试将列表转换为数组,但是将目标数组数据类型传递为double但是为int。
来自docs
Collection.toArray(T [] a)
返回包含此集合中所有元素的数组; 返回数组的运行时类型是指定数组的运行时类型。