Created
March 6, 2015 10:21
-
-
Save SAMMY7th/87c9801885c9887c7674 to your computer and use it in GitHub Desktop.
TechInstitute大阪 2015/03/01 メソッド演習
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* このPractice7もクラスです。 | |
* が、このクラスはまだみなさんに教えていない「static」という | |
* キーワードにより、インスタンスを作らなくてもメソッドを呼び出せています。 | |
* 今は深く考えないようにしてください。staticを勉強してから、 | |
* 改めてこのクラスを眺めてみてね。 | |
* | |
* この演習では、メソッドにのみ着目してください。 | |
* {} でくくられている範囲を意識するように。 | |
* | |
* アクセス修飾子 static 戻り型 メソッド名(引数) { | |
* 処理 | |
* } | |
* この、{} でくくられている範囲が、そのメソッドの処理です。 | |
*/ | |
public class Practice7 { | |
/** | |
* 実は、この「main」もメソッド。 | |
* javaコマンド実行時に1番最初に呼ばれる、特殊メソッドです。 | |
* | |
* 引数:String型の配列 args | |
* 戻り値:なし(void) | |
*/ | |
public static void main(String[] args) { | |
// outputメソッドに文字列"2015/03/01"を引数として渡して実行 | |
output("2015/03/01"); | |
// 下の2行も同様です。自分で動きを追ってみてね。 | |
output("グランフロント"); | |
output("Tech Institute"); | |
// addメソッドに2つの整数(10と5)を引数として渡して実行 | |
// 戻り値を変数resultに代入 | |
int result = add(10, 5); | |
System.out.println(result); | |
// sumメソッドに整数10を引数として渡して実行。戻り値を画面に出力 | |
System.out.println("合計は" + sum(10)); | |
// では、下のメソッドは何をしているでしょうか?考えてみてね。 | |
System.out.println(sum2(10)); | |
} | |
/** | |
* 引数として受け取った文字列の頭に「Practice7:」とつけて、 | |
* 画面に出力するメソッド | |
* | |
* 引数:String型 str | |
* 戻り値:なし(void) | |
*/ | |
private static void output(String str) { | |
System.out.println("Practice7:" + str); | |
} | |
/** | |
* 引数として受け取った2つの整数を足した結果を戻すメソッド | |
* | |
* 引数:int型 x1, int型 x2 | |
* 戻り値:int型 | |
*/ | |
private static int add(int x1, int x2) { | |
int sum = x1 + x1; | |
return sum; | |
} | |
/** | |
* 引数として受け取った整数xについて、 | |
* 0〜xの合計値を返却するメソッド | |
* | |
* 引数:int型 x | |
* 戻り値:int型 | |
*/ | |
private static int sum(int x) { | |
int sum = 0; | |
for (int i = 0; i <= x; i++) { | |
sum += i; | |
} | |
return sum; | |
} | |
/** | |
* このメソッドの意味は自分で考えてみてね。 | |
* | |
* 【回答】 | |
* 例えば、xが5だとすると0〜5の合計は | |
* | |
* 0 + 5 = 5 | |
* 1 + 4 = 5 | |
* 2 + 3 = 5 | |
* 3 + 2 = 5 | |
* 4 + 1 = 5 | |
* 5 + 0 = 5 | |
* | |
* なので | |
* | |
* 5 * 6(個) / 2 | |
* | |
* で求めることができます。 | |
* | |
* つまりこの計算でも、0〜xの合計を出すことができます。 | |
*/ | |
private static int sum2(int x) { | |
return x * (x + 1) / 2; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment