加算(標準入出力)
●addメソッド
与えられた2つの数字(変数xと変数yに格納された数字)を合計します。
int add(int x,int y){
returnx + y;
}
上記のようなメソッド定義を構成するには、3つの要素が必要になります。
・戻り値の型
・メソッド名
・引数
●標準入出力
キーボードから文字列を入力するには,
BufferedReader buf =new BufferedReader(new InputStreamReader(System.in)); と
import java.io.*; が必要となり、
readLine() で文字の入力を行います。
●サンプル
import java.io.*;
class sample {
public static void main(String args[])throws IOException{
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
int a = Integer.parseInt(buf.readLine());
int b = Integer.parseInt(buf.readLine());
int c = add(a,b);
System.out.println(c);
}
static int add(int x, int y){
return x + y;
}
}
●実行結果
1 //入力
2 //入力
3