問題7:アクセス指定子とプロパティ
| この問題を解くためには… |
| → 基本編第7日目参照 |
|---|
prob7-1.(難易度★)
以下のプログラムのクラスDataに、メンバ変数のプロパティを追加し、ビルドが通るようにし、期待される実行結果を得られるように書き換えなさい。
プロジェクトProblem7_1/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Problem7_1
{
class Program
{
static void Main(string[] args)
{
Data d = new Data();
d.Number = 100;
d.Comment = "Programming C#";
Console.WriteLine("number = " + d.Number);
Console.WriteLine("comment = " + d.Comment);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Problem7_1
{
class Data
{
// メンバ変数number
private int number = 0;
// メンバ変数comment
private string comment = "";
}
}
number = 100
comment = Programming C#
comment = Programming C#
prob7-2.(難易度★)
以下のプログラムは、二つの文字列を合成したり、その長さを求めるする機能を持つクラス、TwoStringsと、そのクラスを使ったサンプルプログラムである。このクラスの二つの文字列を結合させるメソッドである、GetConnectedStringを追加し、実行結果通りに動くようにしなさい。
プロジェクトProblem7_2/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Problem7_2
{
class Program
{
static void Main(string[] args)
{
TwoStrings s = new TwoStrings();
s.String1 = "Hello";
s.String2 = "World";
Console.WriteLine("一つ目の文字列は" + s.String1);
Console.WriteLine("二つ目の文字列は" + s.String2);
Console.WriteLine("二つの文字列を合成したものは" + s.GetConnectedString());
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Problem7_2
{
class TwoStrings
{
private string string1;
// 二つ目の文字列
private string string2;
// 一つ目の文字列を設定
public string String1
{
set { string1 = value; }
get { return string1; }
}
// 一つ目の文字列を設定
public string String2
{
set { string2 = value; }
get { return string2; }
}
}
}
一つ目の文字列はHello
二つ目の文字列はWorld
二つの文字列を合成したものはHelloWorld
二つ目の文字列はWorld
二つの文字列を合成したものはHelloWorld
prob7-3.(難易度★)
以下のプログラムは、二つの整数の足し算と引き算を行うクラス、Calculationを用いて、二つの数の足し算と引き算の結果を出力したものである。実行結果と、以下に示す仕様をもとに、クラスCalculationを構成するCalculation.csを完成させ、動作するプログラムを完成させなさい。
プロジェクトProblem7_3/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Problem7_3
{
class Program
{
static void Main(string[] args)
{
Calculation c = new Calculation();
c.Number1 = 8; // 一つ目の数をセット
c.Number2 = 9; // 二つ目の数をセット
// 二つの数の和を表示
Console.WriteLine("{0} + {1} = {2}",c.Number1,c.Number2,c.Add());
// 二つの数の差を表示
Console.WriteLine("{0} - {1} = {2}",c.Number1,c.Number2,c.Sub());
}
}
}
8 + 9 = 17
8 - 9 = -1
クラスCalculationの仕様①フィールド(privateで隠ぺいすること)
8 - 9 = -1
| フィールド | 型 | 概要 | 対応するプロパティ名 |
|---|---|---|---|
| number1 | int | 一つ目の数 | Number1 |
| number2 | int | 二つ目の数 | Number2 |
クラスCalculationの仕様②メソッド
| メソッド名 | 戻り値の型 | 引数 | 概要 |
|---|---|---|---|
| Add | int | なし | number1とnumber2の和を返す。 |
| Sub | int | なし | number1とnumber2の差を返す。 |









