Answer to Exercise 2

The solution to this one involves setting up an array hold the singers. You then loop round each position in the array. Use an IF Statement to test if the string contains (m) or (f). If it contains (m) then you can increment a singer_male variable; if it contains (f) then increment a singer_female variable.

 

C# NET Answer

private void btnSingers_Click(object sender, EventArgs e) {
	
	string[] singers = new string[6];

	singers[0] = "Beyonce (f)";
	singers[1] = "David Bowie (m)";
	singers[2] = "Elvis Costello (m)";
	singers[3] = "Madonna (f)";
	singers[4] = "Elton John (m)";
	singers[5] = "Charles Aznavour (m)";

	int singer_male = 0;
	int singer_female = 0;

	for (int i = 0; i < singers.Length; i++) {

		if (singers[i].Contains("(m)")) {
			singer_male++;
		}

		if (singers[i].Contains("(f)")) {
			singer_female++;
		}
	}

	listBox1.Items.Add("Number of male singers is " + singer_male.ToString());
	
	listBox1.Items.Add("Number of female singers is " +singer_female.ToString());

        }

 

VB NET Answer

Private Sub btnSingers_Click(sender As Object, e As EventArgs) Handles btnSingers.Click

	Dim singers(5) As String

	singers(0) = "Beyonce(f)"
	singers(1) = "David Bowie(m)"
	singers(2) = "Elvis Costello(m)"
	singers(3) = "Madonna(f)"
	singers(4) = "Elton John(m)"
	singers(5) = "Charles Aznavour(m)"

	Dim singer_male As Integer = 0
	Dim singer_female As Integer = 0

	For i = 0 To singers.Length - 1

		If InStr(singers(i), "(f)") > 0 Then
			singer_female = singer_female + 1
		End If

		If InStr(singers(i), "(m)") > 0 Then
			singer_male = singer_male + 1
		End If

	Next

	ListBox1.Items.Add("Number of male singers is " + singer_male.ToString())

	ListBox1.Items.Add("Number of female singers is " + singer_female.ToString())
	
End Sub

 

Java Answer

public static void main(String[] args) {
        
	String[] singers = new String[6];

	singers[0] = "Beyonce (f)";
	singers[1] = "David Bowie (m)";
	singers[2] = "Elvis Costello (m)";
	singers[3] = "Madonna (f)";
	singers[4] = "Elton John (m)";
	singers[5] = "Charles Aznavour (m)";
 
	int singer_male = 0;
	int singer_female = 0;

	for (int i = 0; i < singers.length; i++) {
    	
		if (singers[i].indexOf("(m)") != -1) {
			singer_male++;
		}

		if (singers[i].indexOf("(f)") != -1) {
    		singer_female++;
		}
	}

	System.out.println(singer_male);
	System.out.println(singer_female);
	
}