【问题标题】:Processing numbers from a string and adding to find average score处理字符串中的数字并添加以查找平均分数
【发布时间】:2013-02-03 00:04:16
【问题描述】:

这是我当前的code,这是我当前的输出:

This program will calculate an overall score for a diver, based on individual dives.
The diver's score for dive 1 is 79.80. 
The diver's score for dive 2 is 49.80. 

The average score for these dives is 64.80. 

这是带有specifications 的页面。

基本上,这个程序从一个看起来像这样的文件中获取一个字符串:

1 2.5 8.5 8.0 8.5 9.5 9.0 7.5 6.5

其中1 是潜水编号,2.5 是难度,其余的是分数。我将除最高和最低之外的所有分数相加,乘以难度,再乘以 0.6 得到我的潜水分数。

我遇到的问题是:我的潜水 2 分数是正确的,但我的潜水 1 分数不正确。我真的不太清楚为什么。

非常感谢您的帮助;我绞尽脑汁想知道为什么会这样,但我似乎无法弄清楚。感谢您的关注,我很感激。

编辑:这是给你们的代码:

import java.util.*;
import java.io.*;

public class Dive {

    public static void main(String[] args) throws FileNotFoundException {
        printIntro();

        Scanner fileScanner = new Scanner(new File("DiveData.txt"));

        processDives(fileScanner);
    }

    public static void printIntro() {
        System.out
                .println("Welcome to the Diver Scoring program."
                        + "\nThis program will calculate an overall score for a diver, based on individual dives.");
    }

    public static void processDives(Scanner fileScanner) {
        double avg = 0;
        int count = 0;

        while (fileScanner.hasNext()) {
            int diveNumber = fileScanner.nextInt();
            String diveLine = fileScanner.nextLine();
            double score = calculateDiveScore(diveLine);
            avg += score;

            System.out.printf("The diver's score for dive " + diveNumber
                    + " is " + "%.2f. \n", score);

            count++;
            diveNumber = 0;
        }
        System.out.printf("\nThe average score for these dives is "
                + "%.2f. \n", avg / (double) count);
    }

    public static double calculateDiveScore(String diveLine) {
        double score = 0.0;
        String subNumbers = "";
        double difficulty = Double.parseDouble(diveLine.substring(1, 4));
        diveLine = diveLine.substring(5);
        double max = -500, min = 500;

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

            // if we're getting something other than a space, add it to the
            // string. We'll do the calculations while we have spaces.
            if (diveLine.charAt(i) != ' ') {
                subNumbers += diveLine.charAt(i);
            } else {
                double val = Double.parseDouble(subNumbers);
                // if the score is neither largest nor smallest, add it to total
                // score.
                if (Math.max(val, max) == max && Math.min(val, min) == min) {
                    score += val;
                }

                // if it is either largest or smallest, add previous largest or
                // smallest and set current to largest or smallest.
                if (Math.max(val, max) == val) {
                    if (max != -500)
                        score += max;
                    max = val;
                } else if (Math.min(val, min) == val) {
                    if (min != 500)
                        score += min;
                    min = val;
                }
                subNumbers = "";
            }
        }

        //check the last number to see if it's a max or a min
        if (Math.max(Double.parseDouble(subNumbers), max) == Double
                .parseDouble(subNumbers)) {
            score += max;
        } else if (Math.min(Double.parseDouble(subNumbers), min) == Double
                .parseDouble(subNumbers)) {
            score += min;
        }

        return score * difficulty * 0.6;
    }
}

答案可以在这里找到:

import java.util.*;
import java.io.*;

public class Dive {

    public static void main(String[] args) throws FileNotFoundException {
        printIntro();

        Scanner fileScanner = new Scanner(new File("DiveData.txt"));

        processDives(fileScanner);
    }

    public static void printIntro() {
        System.out
                .println("Welcome to the Diver Scoring program."
                        + "\nThis program will calculate an overall score for a diver, based on individual dives.");
    }

    public static void processDives(Scanner fileScanner) {
        double avg = 0;
        int count = 0;

        while (fileScanner.hasNext()) {
            int diveNumber = fileScanner.nextInt();
            String diveLine = fileScanner.nextLine();
            double score = calculateDiveScore(diveLine);
            avg += score;

            System.out.printf("The diver's score for dive " + diveNumber
                    + " is " + "%.2f. \n", score);

            count++;
            diveNumber = 0;
        }
        System.out.printf("\nThe average score for these dives is " + "%.2f.",
                avg / (double) count);
    }

    public static double calculateDiveScore(String diveLine) {

        diveLine = diveLine.substring(1);
        String[] fields = diveLine.split(" ");
        double difficulty = Double.parseDouble(fields[0]);
        double[] scores = new double[fields.length - 1];
        double max = -500.0, min = 500.0, score = 0;

        for (int i = 0; i < fields.length - 1; i++) {
            scores[i] = Double.parseDouble(fields[i + 1]);
        }

        for (int i = 0; i < scores.length; i++) {
            if (Math.max(scores[i], max) == scores[i])
                max = scores[i];
            if (Math.min(scores[i], min) == scores[i])
                min = scores[i];
            score += scores[i];
        }

        score -= max;
        score -= min;

        return score * difficulty * 0.6;
    }
}

(Also found here on pastebin)

【问题讨论】:

  • 这个问题引起了很多混乱,因为您只链接到您的代码。 SO-ers 习惯于查看内联代码。我看到同时你自己找到了答案,但还有另一个问题,因为这个事实不是很明显。您能否发布自己的答案并接受它,以便将来的访客清楚?
  • 希望看起来更好,Marko。感谢您的提示

标签: java file-io


【解决方案1】:

为此使用String.split()。您解析分数线的方式极其复杂且容易出错。

这里有一个提示这只是伪代码,用于展示方法

final String s = "1 2.5 8.5 8.0 8.5 9.5 9.0 7.5 6.5";
final String[] fields = s.split(" ");
// get the metadata
final int diveNumber = Integer.parseInt(fields[0]);
final double difficulty = Double.parseDouble(fields[1]);
// convert the scores 
final double[] scores = new double[fields.length - 2];
for (int i = 2; i < fields.length; i++ )
{
   scores[i] = Double.parseDouble(fields[i]);  
}

// the rest is left as an exercise to the reader

我个人会将所有原始数组转换为 List 实例,以便更轻松地使用它们,但这是另一个教训。

【讨论】:

  • 我的例子并不是要复制和粘贴,这是作业,它是一个提示,朝着正确的方向朝着最惯用的方式做到这一点Java。
  • fields[0] 是一个空字符串 "" 出于某种原因,使用一些调试技术来解决它。该行可能有一些杂散字符或其他东西。
  • java 处理 .split() 的方式应该至少可以将我的字符串拆分为 fields 数组,这意味着 fields[0] 应该 是与相关的 int潜水编号 - 相反它只是一个空字段?
  • 如果有人找到这个帖子并想要答案,这是我的最终(工作)代码:pastebin.com/evai8sdB
【解决方案2】:

由于这是家庭作业,您学习的最佳方式可能是读取整个字符串,然后在字符串上创建扫描仪,然后使用 getDouble() 对其进行迭代。

所以:

for(iterate over number of lines) {

    String yourString = "blah";

    ... create Scanner pointing to yourString...

    while(scanner has a double) {

        double nextNum = get next double from scanner;
        ... Do something with that double...
    }
}

如果您需要任何关于具体细节的帮助,请随时提出。

编辑:哎呀,错过了您的代码的链接。忽略“发布您的代码”位。

【讨论】:

  • 我认为我阅读它做得很好,这不是问题所在。由于该课程是comp sci 100级课程,因此对我应该如何做事有很大的限制。我很感激这个提示,以供将来参考
  • 好吧,您之前已经在使用扫描仪,所以我看不出您以后不能使用它的任何原因。编辑:您遇到问题的原因是您检查和存储最大值和最小值的方式。运行你的程序,看看如果数字不断增加会发生什么:即 1.0 2.0 3.0
  • 你是对的,但它实际上只有在它们持续减少时才有效
  • 无论哪种方式都有问题。难度为 2 的 1.0 2.0 3.0 应返回 2.4,但您的代码返回 3.6
  • 我的意思是,如果潜水分数总是下降,我会得到正确答案
猜你喜欢
  • 1970-01-01
  • 2018-01-20
  • 2023-03-22
  • 2017-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-18
  • 1970-01-01
相关资源
最近更新 更多