ACM_1001_Java读取控制台等

题目:

Calculate a + b

Input

The input will consist of a series of pairs of integers a and b,separated by a space, one pair of integers per line.

Output

For each pair of input integers a and b you should output the sum of a and b in one line,and with one line of output for each line in input.


Mine Code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class ACM_1001_2 {
	
	public static void main(String[] args){
		
		//System.out.println("Please input two integers:");
		
		try{
			
			//use buffer to read stream
			InputStreamReader is_reader = new InputStreamReader(System.in);
			BufferedReader bf_reader = new BufferedReader(is_reader);
			
			//read line
			String str = bf_reader.readLine();
			
			//read line one by one
			while(str!=null){
			String[] arrs=null;
			
			//use split to split strings into array
			arrs=str.split(" ");
			//convert char into int
			int sum = Integer.parseInt(arrs[0])+Integer.parseInt(arrs[1]);
			
			//System.out.println("The sum of your input is:"+sum);
			System.out.println(sum);
			
			//read next line
			str = bf_reader.readLine();
			}
			
		}catch(IOException e){
			e.printStackTrace();
		}
		
		
	}

}


Summary:

1. 使用buffer读控制台

InputStreamReader is_reader = new InputStreamReader(System.in);
BufferedReader bf_reader = new BufferedReader(is_reader);

2.使用split将string split到数组中

arrs=str.split(" ");

3. 字符串转化为整数

Integer.parseInt(arrs[0])




Sample Code:

import java.util.Scanner;


public class ACM_1001 {
	
	public static void main(String[] args){
		
		//use Scanner to read from console
		Scanner in = new Scanner(System.in);
		
		//use while to read next
		while(in.hasNextInt()){
			//convert into int
			int a = in.nextInt();
			int b = in.nextInt();
			System.out.println(a+b);
		}
		
	}

}


Summary:

1. use scanner to read from console

Scanner in = new Scanner(System.in);

2. use in.nextInt to get int result

int a = in.nextInt();


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值