Java实现两数及之间整数求和(不区分输入大小)
Bounded Sum Calculation (Inclusive of Both Inputs)
Hey there! Let's tackle your problem of calculating the sum of two integers and all integers between them—regardless of which input is larger. First, let's break down the areas where your current code can be improved, then share cleaner, more efficient solutions.
Issues in Your Current Code
- Unnecessary Static Variables: Using static variables for
sum,first, andsecondintroduces state pollution (if you ever extend this code to run multiple times, values will carry over between executions). Local variables are safer and cleaner here. - Redundant Loop Logic: The three overlapping
ifchecks in yourwhileloop make the flow hard to follow and can lead to unexpected behavior. - Boundary Bug: When the two input integers are equal, your code doesn't add that number to the sum (e.g., inputting 5 and 5 would return
sum = 0instead of the correct value 5).
Solution 1: Clear Loop-Based Approach
This version uses Math.min() and Math.max() to define the range upfront, then loops through every integer in that range (inclusive) to calculate the sum. It's intuitive and easy to debug:
import java.util.Scanner; public class BoundedSum { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Input an integer (0,1,2,3...)."); int first = input.nextInt(); System.out.println("Input a second integer. The sum of your inputs plus any numbers between them will be given."); int second = input.nextInt(); int sum = 0; int min = Math.min(first, second); int max = Math.max(first, second); // Iterate from the smaller number to the larger one, including both endpoints for (int i = min; i <= max; i++) { sum += i; } System.out.println("The sum = " + sum); input.close(); // Clean up the scanner resource to avoid leaks } }
Solution 2: Efficient Mathematical Formula
For large ranges, a loop can be slow. Instead, use the arithmetic series sum formula—it calculates the result in constant time (O(1)), no matter how big the range is:
- Number of terms:
count = max - min + 1 - Sum:
sum = count * (min + max) / 2
Here's the code implementation:
import java.util.Scanner; public class BoundedSum { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Input an integer (0,1,2,3...)."); int first = input.nextInt(); System.out.println("Input a second integer. The sum of your inputs plus any numbers between them will be given."); int second = input.nextInt(); int min = Math.min(first, second); int max = Math.max(first, second); int count = max - min + 1; int sum = count * (min + max) / 2; System.out.println("The sum = " + sum); input.close(); } }
Key Improvements in Both Solutions
- No static variables, so the code is thread-safe and doesn't retain state between runs.
- Explicit range definition with
minandmaxmakes the logic straightforward to follow. - Fixes the boundary bug: when inputs are equal, the sum correctly includes that single number.
- Properly closes the
Scannerto avoid resource leaks.
内容的提问来源于stack exchange,提问作者SatchmoRu
相关产品推荐
相关产品推荐

