如何将文件中的数据值写入新的输出文件?

时间:2015-02-13 23:25:29

标签: java android eclipse

我几乎完全在Eclipse中制作这个应用程序。它是一个Android应用程序,从我的应用程序项目的资产目录中的文本文件中读取双数据值。它将数据值存储在数组中,我只需要将double数据值的平方根写入输出文件。我在命令提示符中使用了adb shell,它显示了数据值,但它们不是平方根。数据值仍为原始的双重形式。所以,我认为代码的写入部分或执行平方根的方法必定是错误的。我真的不了解Java,所以请以更简单的方式向我解释。这是代码:

public void srAndSave(View view)
{
    EditText edt1;
    EditText edt2;
    TextView tv;

    String infilename; 
    String outfilename;

    tv = (TextView) findViewById(R.id.text_status);

    //Get the name of the input file and output file
    edt1 = (EditText) findViewById(R.id.edit_infile);
    edt2 = (EditText) findViewById(R.id.edit_outfile);

    infilename = edt1.getText().toString();
    outfilename = edt2.getText().toString();

    //Create an array that stores double values (up to 20)
    double double_nums[] = new double[20];
    int n = 0;//For storing the number of data values in the array


    //Open the data file from the asset directory
    //and make sure the data file exists
    AssetManager assetManager = getAssets();

    try
    {
        Scanner fsc = new Scanner(assetManager.open(infilename));

        //Get the data values from the file
        //and store them in the array double_nums
        n = 0;
        while(fsc.hasNext()){
            double_nums[n] = fsc.nextDouble();
            n++;
        }

        //Calls on square_root_it method
        square_root_it(double_nums, n);

        //Display that the file has been opened
        tv.setText("Opening the input file and reading the file were "
                + " successful.");

        fsc.close();

    }
    catch(IOException e)
    {
        tv.setText("Error: File " + infilename + " does not exist");

    }

    //Write the data to the output file and
    //also make sure that the existence of the file
    File outfile = new File(getExternalFilesDir(null), outfilename);
    try
    {
        FileWriter fw = new FileWriter(outfile); 

        BufferedWriter bw = new BufferedWriter(fw);

        PrintWriter pw = new PrintWriter(bw); 

        int x;

        for(x=0;x < n;x++)
            pw.println(double_nums[x]);

        pw.close();
    }
    catch(IOException e)
    {
        System.out.println("Error! Output file does already exist! You will overwrite"
                + " this file!");
    }

} //end srAndSave

public static void square_root_it(double[] a, int num_items)
{
    int i;

    for(i=0; i < num_items; i++)
        Math.sqrt(a[i]);

} //end square_root_it

}

1 个答案:

答案 0 :(得分:1)

你的问题在这里:

for(i=0; i < num_items; i++)
    Math.sqrt(a[i]);

Math.sqrt(num)返回一个值,它不会设置该值。 我要做的是创建第二个数组来保存结果,然后执行:

for(i=0; i < num_items; i++)
    results[i] = Math.sqrt(a[i]);