如何用Java编写一维和二维数组到文本文件中

时间:2013-02-23 01:14:27

标签: java arrays printf

我想将数组的每个元素写入文本文件。以下将更清楚地展示

String[] Name = {"Eric","Matt","Dave"}

Int[] Scores = {[45,56,59,74],[43,67,77,97],[56,78,98,87]}

double[] average = {45.7,77.3,67.4}

我希望文本文件中有以下内容

Student Eric scored 45,56,59,74 with average of 45.7
Student Matt scored 43,67,77,97 with average of 77.3
Student Dave scored 56,78,98,87 with average of 67.4

我创建了输出文件

PrintStream output = new PrintStream(new File("output.txt"));

我使用了for循环

for(int i =0;i<=Name.length;i++){

    output.println("Student  " + Name[i] + " scored " + Scores[i] + " with average of " + average[i]);
}

但是这没用。请帮忙。

4 个答案:

答案 0 :(得分:2)

我的猜测是编译器不喜欢这一行:

Int[] Scores = {[45,56,59,74],[43,67,77,97],[56,78,98,87]}

Java中没有Int类型。假设你的意思是int,编译器仍会抱怨因为[45,56,59,74]不是int!

您需要的是int[][]和声明,例如:{{45,56,59,74}}

不过,我不确定你会对输出感到满意......

答案 1 :(得分:0)

  1. 二维数组需要两个括号而不是一个,
  2. Int应该是小写的,
  3. 变量应为小写(分数而不是分数)。
  4. 所以看起来应该是这样的:

    int[][] scores = {{45,56,59,74},{43,67,77,97},{56,78,98,87}};
    

    另外,for循环应该从0到1小于长度,否则你将超出界限。

    names.length = 3
    names[0] = "Eric"
    names[1] = "Matt"
    names[2] = "Dave"
    

    所以,当你尝试访问名称[3]时,你会得到一个越界异常,因为该数组只包含3个元素。

答案 2 :(得分:0)

也许你忘了刷新或关闭PrintStream(我还修复了上面提到的错误)

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;

public class Main {
    public static void main(String[] args) {
        String[] Name = {"Eric","Matt","Dave"};

        int[][] Scores = {{45,56,59,74},{43,67,77,97},{56,78,98,87}};

        double[] average = {45.7,77.3,67.4};



        try (
                PrintStream output = new PrintStream(new File("output.txt"));
            ){

            for(int i =0;i<Name.length;i++){
                String sc ="";
                for (int j=0;j<Scores[i].length;j++){
                        sc+=Scores[i][j]+" ";
                }
                output.println("Student  " + Name[i] + " scored " + sc + " with average of " + average[i]);
            }
            output.close();

        } catch (FileNotFoundException e) {

            e.printStackTrace();
        }

    }



}

请注意,这是java7语法(带有()的try..catch块)

请参阅:http://blog.sanaulla.info/2011/07/10/java-7-project-coin-try-with-resources-explained-with-examples/

答案 3 :(得分:-1)

您必须使用FileWriter而不是PrintStream。

BufferedWriter bw = new BufferedWriter(new FileWriter(new File(
                                        "C:/new.txt"), true));

StringBuffer sb = new StringBuffer();

for(int i =0;i<=Name.length;i++){
    sb.append("Student " + Name[i] + " scored " + Scores[i]
    + " with average of " + average[i] + "\n"); 
}

bw.write(sb.toString());
bw.close();