【发布时间】:2013-12-03 04:53:46
【问题描述】:
我为TestScores 和ScoreException 创建了一个程序,现在我想弄清楚如何计算分数的平均值。这是我编写平均代码时的代码,它产生了一个找不到适合字符串的方法
TestScores
import javax.swing.*;
public class TestScore
{
public static void main(String args[]) throws Exception
{
int[] id = {1234, 2345, 3456, 4567, 5678};
int[] score = {0, 0, 0, 0, 0};
String scoreString = new String();
final int HIGHLIMIT = 100;
String inString, outString = "";
for(int x = 0; x < id.length; ++x)
{
inString = JOptionPane.showInputDialog(null,
"Enter score for student id number: " + id[x]);
score[x] = Integer.parseInt(inString);
try
{
if(score[x] > HIGHLIMIT)
{
scoreString = "Score over " + HIGHLIMIT;
throw (new ScoreException(scoreString));
}
}
catch(ScoreException e)
{
JOptionPane.showMessageDialog(null, e.getMessage());
score[x] = 0;
}
}
for(int x = 0; x < id.length; ++x)
outString = outString + "ID #" + id[x] + " Score " +
score[x] + "\n";
JOptionPane.showMessageDialog(null, outString);
}
}
还有我的ScoreException 代码
public class ScoreException extends Exception
{
public ScoreException(String s)
{
super(s);
}
}
这是我的平均代码,但它没有正确输出
int score[] = new score[] { 45, 98 ,80, 74, 93};
double result = 0;
{
for(int x=0; x < int.length; x++){
result += score[x];
}
System.out.println(result/count)
【问题讨论】:
-
"but I can't seem to understand how to write code for averages..."-- 你将如何在纸上做到这一点?找出算法的步骤,因为您的程序的步骤是相同的。另外,请发布您解决此问题的最佳尝试,以便此问题看起来不仅仅是家庭作业转储。 -
在第二个 for 循环中,求和
score[x],然后除以score.length。 -
stackoverflow.com/questions/7008189/… 和其他几个这样的人已经有了答案