分享免费的编程资源和教程

网站首页 > 技术教程 正文

「POJ 1000」 A+B Problem 经典水题 JAVA 解题报告

goqiw 2024-09-09 06:29:07 技术教程 39 ℃ 0 评论

A+B Problem

?

Time Limit: 1000MSMemory Limit: 10000K

?

Description

Calculate a+b

Input

Two integer a,b (0<=a,b<=10)

Output

Output a+b

Sample Input


1 2

Sample Output


3

解决思路

这是一道经典水题了,基本上每个OJ都有的。

题目很简单,就是对输入的两个整数a和b,输出它们的和。

写这份解题报告主要是跟一些没在OJ上刷过题的朋友介绍下,在OJ上输入输出的一个流程。以及用Java语言刷题需要注意的一些问题。

先贴代码:


package com.igeekspace;

import java.io.*;

public class Main {
    static BufferedReader bufferedReader;
    static PrintWriter printWriter;

    private static void solve() throws IOException {
        while (true) {
            String input = bufferedReader.readLine();

            if (input == null) {
                break;
            }
            String[] nums = input.split(" ");

            if(nums.length != 2){
                break;
            }
            int a = Integer.parseInt(nums[0]);
            int b = Integer.parseInt(nums[1]);

            printWriter.println(a + b);
        }
    }

    public static void main(String[] args) {
        bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        printWriter = new PrintWriter(new OutputStreamWriter(System.out));

        try {
            solve();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        printWriter.flush();
    }
}

上面是我IDE上的代码,记得提交到OJ上的时候,需要把包信息去掉,例如第一行的“package com.igeekspace;”,因为OJ上不会按照这个目录结构去做编译,加上这行包信息OJ会报编译错误。

输入用StreamTokenizer类,是因为OJ的很多题目输入的数据量特别大,有些题目测试用例数可能是十万级,但是执行时间,给java语言一般只给2秒,所以我测试发现StreamTokenizer类比Scanner类IO处理效率更高。输出类用PrintWriter也是基于同样的原因。

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表