计算平均值:字符串分词练习——分数格式成绩的平均值计算求助
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 todoublefirst 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

