You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

计算平均值:字符串分词练习——分数格式成绩的平均值计算求助

Solution for Calculating Grade Average with Fractions

Hey there! I see you've already made solid progress parsing the input—great job stripping out whitespace and semicolons. Let's work through the fraction conversion and average calculation part together, step by step.

Step 1: Fix the Parentheses Issue First

First, we need to normalize all fractions by removing those surrounding parentheses. You had commented out the bracket replacement code, but we need to adjust it to handle both ( and ) properly (they're special characters in regex, so we'll wrap them in brackets to target both at once).

Step 2: Process Each Grade Entry

For every entry in your split dataset, we'll check if it's a fraction (contains /) or a plain integer:

  • Fractions: Split the string at / to get the numerator and denominator, convert them to integers, then calculate the percentage as (numerator / denominator) * 100. Important: cast one of the integers to double first to avoid integer division truncation!
  • Integers: Just convert the string to an integer and add it directly to the total sum.

Step 3: Calculate and Format the Average

Once we have the total sum of all converted grades, divide by the number of entries to get the average. We'll use printf to format the output to two decimal places, matching your expected result.

Modified Full Code

import java.util.Scanner;

public class GradeCalculator {
    public static void main(String[] args) {
        System.out.println("Enter a Set of Grades:");
        Scanner messageIn = new Scanner(System.in);
        String store = messageIn.nextLine();
        
        // Clean up input: remove whitespace, parentheses, and keep semicolons for splitting
        store = store.trim()
                     .replaceAll("\\s+", "")  // Remove any kind of whitespace
                     .replaceAll("[()]", ""); // Strip both opening and closing parentheses
        
        String[] dataSet = store.split(";");
        messageIn.close();
        
        double totalSum = 0.0;
        int gradeCount = dataSet.length;
        
        for (String gradeEntry : dataSet) {
            // Skip empty entries caused by trailing semicolons
            if (gradeEntry.isEmpty()) continue;
            
            if (gradeEntry.contains("/")) {
                // Handle fraction conversion
                String[] fractionParts = gradeEntry.split("/");
                int numerator = Integer.parseInt(fractionParts[0]);
                int denominator = Integer.parseInt(fractionParts[1]);
                
                // Calculate percentage with floating-point division
                double percentage = (double) numerator / denominator * 100;
                totalSum += percentage;
            } else {
                // Handle integer grade
                int integerGrade = Integer.parseInt(gradeEntry);
                totalSum += integerGrade;
            }
        }
        
        double average = totalSum / gradeCount;
        // Format output to two decimal places
        System.out.printf("The Average is: %.2f%n", average);
    }
}

Testing with Your Example Input

Let's verify with your sample input: 98;37; 12/33; (33/90); 88; 120/150;

  • After cleaning, the entries become: 98, 37, 12/33, 33/90, 88, 120/150
  • Breakdown of calculations:
    • 98 → 98
    • 37 → 37
    • 12/33 ≈ 36.3636
    • 33/90 ≈ 36.6667
    • 88 → 88
    • 120/150 = 80
  • Total sum: 98 + 37 + 36.3636 + 36.6667 + 88 + 80 = 376.0303
  • Average: 376.0303 ÷ 6 ≈ 62.67, which matches your expected output perfectly!

Quick Bonus Tip

If you want to handle invalid inputs (like non-numeric values or zero denominators), you can wrap the parsing steps in try-catch blocks to avoid crashes and show user-friendly error messages.

内容的提问来源于stack exchange,提问作者user3371137

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:39:15