0

我想将数组的每个元素写入一个文本文件。例如下面将更清楚地演示

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

4 回答 4

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}}

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

于 2013-02-23T01:21:29.593 回答
0
  1. 二维数组需要两个括号而不是一个,
  2. Int 应该是小写的,
  3. 变量应该是小写的(分数而不是分数)。

所以它应该是这样的:

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"

因此,当您尝试访问 names[3] 时,您将得到一个越界异常,因为该数组仅包含 3 个元素。

于 2013-02-23T01:25:59.693 回答
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/

于 2013-02-23T01:26:40.197 回答
-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();
于 2013-02-23T01:22:25.053 回答