Created
October 13, 2016 07:54
-
-
Save milk19873/8dc3d62443882c30cbf5fac79c6f4ccf to your computer and use it in GitHub Desktop.
第7回プログラミング講座
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
using System; | |
using System.Collections.Generic; | |
using System.ComponentModel; | |
using System.Data; | |
using System.Drawing; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using System.Windows.Forms; | |
namespace SimpleCalc | |
{ | |
public partial class Form1 : Form | |
{ | |
//このクラス内で使用する変数を宣言する。 | |
Calc calc; | |
int suji_mae = 0; | |
int suji_ushiro = 0; | |
int keisankekka = 0; | |
//コンストラクター(クラス名と同じ名前のメソッドをコンストラクターと呼ぶ。) | |
public Form1() | |
{ | |
InitializeComponent(); | |
} | |
//"+"ボタンを押した場合の処理 | |
private void tashizan_button_Click(object sender, EventArgs e) | |
{ | |
//足し算の記号をラベルに表示する | |
this.enzan_label.Text = "+"; | |
//テキストボックスの前の数字を、文字列から数値に変換し代入する。-① | |
this.suji_mae = Convert.ToInt32(suji_mae_text.Text); | |
//テキストボックスの後ろの数字を、文字列から数値に変換し代入する。-② | |
this.suji_ushiro = Convert.ToInt32(suji_ushiro_text.Text); | |
//Calcクラスをインスタンス生成する。-③ | |
calc = new Calc(this.suji_mae, this.suji_ushiro); | |
//CalcクラスのExecuteメソッドを使って計算を行う(0:足し算)-④ | |
this.keisankekka = calc.Execute(0); | |
//計算結果を、数値から文字列に変換する。-⑤ | |
string text_keisankekka = Convert.ToString(this.keisankekka); | |
//変換した文字列を、テキストボックスの合計の欄に代入する。-⑥ | |
this.goukei_text.Text = text_keisankekka; | |
} | |
//"-"ボタンを押した場合の処理 | |
private void hikizan_button_Click(object sender, EventArgs e) | |
{ | |
//引き算の記号をラベルに表示する | |
this.enzan_label.Text = "-"; | |
//①②③の組み合わせ技。一旦、変数に代入を行うのではなく、インスタンス生成時に数値変換した値を直接渡す。 | |
calc = new Calc(Convert.ToInt32(suji_mae_text.Text), Convert.ToInt32(suji_ushiro_text.Text)); | |
//④⑤⑥の組み合わせ技。一旦、変数に代入を行うのではなく、インスタンス生成したcalcのExecuteメソッドを呼び出す。 | |
//また、呼び出した後の戻り値を、数値から文字列に変換し、テキストボックスの合計の欄に代入する。 | |
this.goukei_text.Text = Convert.ToString(calc.Execute(1)); | |
} | |
} | |
public class Calc | |
{ | |
//このクラスで使用する変数を宣言する。 | |
int suji1 = 0; | |
int suji2 = 0; | |
//コンストラクター | |
public Calc (int a, int b) | |
{ | |
//変数を初期化します | |
this.suji1 = a; | |
this.suji2 = b; | |
} | |
//Executeメソッド | |
public int Execute (int enzan) | |
{ | |
//変数を初期化します | |
int result = 0; | |
if (enzan == 0) | |
{ | |
//足し算の場合の処理 | |
result = this.suji1 + this.suji2; | |
} | |
else if (enzan == 1) | |
{ | |
//引き算の場合の処理 | |
result = this.suji1 - this.suji2; | |
} | |
else | |
{ | |
//処理なし | |
} | |
//計算結果を返します(戻り値) | |
return result; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment