题目:
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();