杰瑞科技汇

a b problem java

Of course! The "A + B problem" is the classic "Hello, World!" of competitive programming and algorithmic interviews. It's designed to test the most fundamental skills of a programmer: reading input, performing a calculation, and producing output.

a b problem java-图1
(图片来源网络,侵删)

Here’s a complete guide to solving the A + B problem in Java, from the most basic approach to more advanced scenarios.

The Problem Statement

Given two integers, A and B, calculate and print their sum, A + B.


Scenario 1: The Basic Version (Standard Input/Output)

This is the most common version, where you read two numbers from standard input (like the console) and print the result to standard output.

Solution 1: Using Scanner (Recommended for Beginners)

The java.util.Scanner class is the easiest and most straightforward way to get input from the user in a simple Java program.

a b problem java-图2
(图片来源网络,侵删)

Code:

import java.util.Scanner; // Import the Scanner class
public class Main {
    public static void main(String[] args) {
        // Create a Scanner object to read input
        Scanner scanner = new Scanner(System.in);
        // Read the first integer
        int a = scanner.nextInt();
        // Read the second integer
        int b = scanner.nextInt();
        // Calculate the sum
        int sum = a + b;
        // Print the result
        System.out.println(sum);
        // Close the scanner to prevent resource leaks (good practice)
        scanner.close();
    }
}

How to Run It:

  1. Save the code in a file named Main.java.
  2. Compile it from your terminal: javac Main.java
  3. Run it: java Main
  4. The program will wait. You need to type the two numbers separated by a space and press Enter.
    • Example Input: 5 10
    • Example Output: 15

Solution 2: Using BufferedReader (More Performant)

For reading a large amount of data (millions of lines), BufferedReader is significantly faster than Scanner because it uses a buffer. This is a common requirement in competitive programming.

Code:

a b problem java-图3
(图片来源网络,侵删)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
    public static void main(String[] args) throws IOException {
        // Create a BufferedReader to read from standard input
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        // Read a line of input as a String
        String line = reader.readLine();
        // Split the string by spaces to get the numbers as an array of strings
        String[] numbers = line.split(" ");
        // Parse the string numbers into integers
        int a = Integer.parseInt(numbers[0]);
        int b = Integer.parseInt(numbers[1]);
        // Calculate the sum
        int sum = a + b;
        // Print the result
        System.out.println(sum);
        // Close the reader (good practice)
        reader.close();
    }
}

How it Works:

  1. BufferedReader.readLine() reads an entire line of input as a single String.
  2. line.split(" ") splits this string into an array of smaller strings. For input "5 10", it becomes ["5", "10"].
  3. Integer.parseInt() converts these string representations of numbers into actual integer types that can be used for calculation.

Scenario 2: Handling Multiple Test Cases

A common variation of the problem is that you are given T test cases. For each test case, you are given two integers A and B, and you must print their sum.

Input Example:

3
5 10
100 200
-5 5

Output Example:

15
300
0

Solution: Using Scanner in a Loop

This is a simple extension of the first solution. We just need to read the number of test cases first and then loop that many times.

Code:

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // Read the number of test cases
        int t = scanner.nextInt();
        // Loop 't' times
        for (int i = 0; i < t; i++) {
            // Read A and B for the current test case
            int a = scanner.nextInt();
            int b = scanner.nextInt();
            // Calculate and print the sum
            System.out.println(a + b);
        }
        scanner.close();
    }
}

Scenario 3: The Online Judge Version (Fast I/O)

In competitive programming platforms (like Codeforces, LeetCode, etc.), programs are judged automatically. They often require very fast input/output to handle large datasets within a strict time limit. Using Scanner can be too slow.

The standard approach for this is to use BufferedReader for reading and PrintWriter for writing.

Code (Template for Fast I/O in Java):

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main {
    public static void main(String[] args) {
        // Use try-with-resources to automatically close readers/writers
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
             PrintWriter writer = new PrintWriter(System.out)) {
            // Read the first line (number of test cases)
            int t = Integer.parseInt(reader.readLine());
            // Loop for each test case
            while (t-- > 0) {
                // Use StringTokenizer to efficiently split the line
                StringTokenizer tokenizer = new StringTokenizer(reader.readLine());
                int a = Integer.parseInt(tokenizer.nextToken());
                int b = Integer.parseInt(tokenizer.nextToken());
                // Write the result to the output
                writer.println(a + b);
            }
        } catch (IOException e) {
            // Handle potential I/O errors
            e.printStackTrace();
        }
    }
}

Why this is better for Online Judges:

  • BufferedReader: Much faster than Scanner for bulk reading.
  • PrintWriter: Faster than System.out.println() for bulk writing.
  • StringTokenizer: A very efficient way to split a string into tokens (numbers) when you know the delimiter (a space).
  • try-with-resources: A modern Java feature that ensures your BufferedReader and PrintWriter are closed automatically, preventing resource leaks.

Summary and Recommendation

Scenario Recommended Tool Why?
Learning / Simple Scripts Scanner Extremely easy to use and understand. Perfect for beginners.
Multiple Test Cases Scanner or BufferedReader Simple to implement with a loop. Scanner is fine for small inputs.
Competitive Programming BufferedReader + PrintWriter Mandatory for speed. This is the industry standard template for Java in coding contests.

For any serious programming challenge or interview preparation, memorize the "Fast I/O" template. It will serve you well.

分享:
扫描分享到社交APP
上一篇
下一篇