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

Java新手求助:大整数分数化简代码的运行时错误修复方法

Fixing Runtime Errors in Your Java Fraction Simplification Program

Hey there! Let's break down why your program is hitting runtime errors and get it working correctly for those huge 10^30-sized numbers.

The Core Problem

Your input values (numerators and denominators up to 10^30) are way larger than what Java's basic numeric types can handle. For example:

  • int maxes out at ~2 billion
  • long only goes up to ~9e18
    Trying to store 10^30 in either will cause integer overflow, which leads to unexpected behavior or runtime crashes.

The Solution: Use BigInteger

Java's java.math.BigInteger class is designed exactly for this scenario—it supports arbitrarily large integers, so even 10^30 is no problem. Here's a complete, working implementation that uses BigInteger to simplify your fractions:

import java.math.BigInteger;
import java.util.Scanner;

public class FractionReducer {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Read number of test cases
        int testCases = scanner.nextInt();
        scanner.nextLine(); // Consume the leftover newline after nextInt()
        
        for (int i = 0; i < testCases; i++) {
            // Read and split the fraction line (handles spaces around "/")
            String fractionLine = scanner.nextLine().trim();
            String[] fractionParts = fractionLine.split("\\s+/\\s+");
            
            // Parse numerator and denominator into BigIntegers
            BigInteger numerator = new BigInteger(fractionParts[0]);
            BigInteger denominator = new BigInteger(fractionParts[1]);
            
            // Calculate Greatest Common Divisor (GCD)
            BigInteger gcd = numerator.gcd(denominator);
            
            // Simplify the fraction
            BigInteger simplifiedNum = numerator.divide(gcd);
            BigInteger simplifiedDen = denominator.divide(gcd);
            
            // Print the result in the required format
            System.out.println(simplifiedNum + " / " + simplifiedDen);
        }
        
        scanner.close();
    }
}

Key Details Explained

Let's walk through the important parts so you understand what's happening:

  • Handling Input: After using scanner.nextInt() to get the number of test cases, we call scanner.nextLine() to clear the newline character left in the input buffer—this prevents the next nextLine() from reading an empty string.
  • Splitting the Fraction: The regex \\s+/\\s+ splits the line on " / " (with any number of spaces around the slash), so it works even if the input has extra spaces.
  • GCD Calculation: BigInteger has a built-in gcd() method that efficiently computes the greatest common divisor of two large integers—no need to implement the Euclidean algorithm yourself!
  • Simplification: Dividing both the numerator and denominator by their GCD gives us the reduced fraction, and since GCD divides both numbers evenly, we don't have to worry about remainder issues.

Testing with Your Example Input

If you run this code with your sample input:

4
1 / 2
2 / 4
3 / 3
4 / 2

You'll get the exact output you expect:

1 / 2
1 / 2
1 / 1
2 / 1

Quick Tips for Future

  • Always use BigInteger when dealing with numbers larger than 9e18 (the max of long).
  • Double-check input parsing logic—small issues like leftover newlines or unexpected spaces can cause hard-to-debug errors.
  • Remember to close your Scanner to free up resources (though in small programs like this, it's less critical, it's good practice!).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:05:22