我有一个要求输入学生姓名和分数的程序。名称和分数用“ |”分隔。我将它们拆分并放置在一个数组中,以便可以根据得分显示统计数据。

当我尝试显示得分低于平均水平的学生的姓名时,我遇到了一个问题。每当我运行程序时,<belowAvg>标记都不会输出。我不认为这些名称已保存到studentNames[i]文件中。

如果有人能指出我正确的方向,我将不胜感激。

 // Get the data from the text area and dump it in the file in XML format
    String text = textArea.getText();
    // Print the text to the file  - for testing purposes only
    outfile.println(text);

    Double[] studentScores = new Double[10];
    String [] studentNames = new String[10];
    double sumScores = 0;
    String []lines = text.split("\n");
    int i;
    outfile.println("<students>");
    for(i=0;i<lines.length;i++)
    {
        outfile.println("<student>");
        String[]tokens =lines[i].split("\\|");
        outfile.println("<name>" + tokens[0] + "</name>");
        studentNames[i] = tokens[0];

        outfile.println("<score>" + tokens[1] + "</score>");
        Double score = Double.parseDouble(tokens[1]);
        studentScores[i] = score;
        outfile.println("</student>");
    }
    double arraySize = i;
    double average = 0;
    double maximum = studentScores[1];
    double minimum = studentScores[1];

    for(i=0;i<arraySize;i++)
    {
     sumScores = sumScores + studentScores[i];
     if(studentScores[i] > maximum)
     {
         maximum = studentScores[i];
     }
     if(studentScores[i] < minimum)
     {
        minimum = studentScores[i];
     }
    }

     average = sumScores / arraySize;

     outfile.printf("\nThe sum is: %.1f" , sumScores);
     outfile.printf("\n<average> %.1f", average);
     outfile.println("</average>");
     outfile.printf("\n<maximum> %.1f" , maximum);
     outfile.println("</maximum>");
     outfile.printf("\n<minimum> %.1f", minimum);
     outfile.println("</minimum");

     for(i=0;i<arraySize;i++)
     {
         if(studentScores[i] < average)
         {
             outfile.printf("\n<belowAvg>" , studentNames[i]);
             outfile.println("</belowAvg>");
         }
     }

    outfile.println("\n</students>");
    outfile.close();


这就是XML文件正在打印的内容。

jill|87
phil|23
michael|99
leny|67

<students>
<student>
<name>jill</name>
<score>87</score>
</student>
<student>
<name>phil</name>
<score>23</score>
</student>
<student>
<name>michael</name>
<score>99</score>
</student>
<student>
<name>leny</name>
<score>67</score>
</student>

The sum is: 276.0
<average> 69.0</average>

<maximum> 99.0</maximum>

<minimum> 23.0</minimum

<belowAvg></belowAvg>

<belowAvg></belowAvg>

</students>

最佳答案

if(studentScores[i] < average)
{
 outfile.printf("\n<belowAvg>" , studentNames[i]);
 outfile.println("</belowAvg>");
}


在您要打印出studentNames数组中的值的行中,实际上并没有使用该值。您需要在%s标记后添加<belowAvg>

09-11 19:59