Answer to Exercise 3

This exercise may have given you a few problems, as it's a lot trickier than it seems. The key to it is a double for loop, one inside the other. First, you set up two arrays, one to hold the vowels and one to hold the instruments. The outer loop is used to grab an instrument from the array. The inner loop is used to cycle through the five vowels. If a vowel is found in the instrument then you can use the Replace string method to replace it with a blank character, which is done with two double quotes with no space between them "".

 

C# NET Answer

private void btnVowels_Click(object sender, EventArgs e) {

	string[] vowels = new string[5];

	vowels[0] = "a";
	vowels[1] = "e";
	vowels[2] = "i";
	vowels[3] = "o";
	vowels[4] = "u";

	string[] instruments = new string[4];

	instruments[0] = "cello";
	instruments[1] = "guitar";
	instruments[2] = "violin";
	instruments[3] = "double bass";

	for (int a = 0; a < instruments.Length; a++) {
                    
		string instrument = instruments[a];
                
		for (int i = 0; i < vowels.Length; i++)
 		{
			instrument = instrument.Replace(vowels[i], "");
		}
              
		listBox1.Items.Add(instrument);
	}
}

 

VB NET Answer

Private Sub btnVowels_Click(sender As Object, e As EventArgs) Handles btnVowels.Click

	Dim vowels(4) As String
	Dim instruments(3) As String

	vowels(0) = "a"
	vowels(1) = "e"
	vowels(2) = "i"
	vowels(3) = "o"
	vowels(4) = "u"

	instruments(0) = "cello"
	instruments(1) = "guitar"
	instruments(2) = "violin"
	instruments(3) = "double bass"

	Dim instrument As String

	For i = 0 To instruments.Length - 1
	    instrument = instruments(i)

	    For j = 0 To vowels.Length - 1
			instrument = instrument.Replace(vowels(j), "")
	    Next

	    ListBox1.Items.Add(instrument)
	Next

End Sub

 

Java Answer

public static void main(String[] args) {

    String[] vowels = new String[5];

    vowels[0] = "a";
    vowels[1] = "e";
    vowels[2] = "i";
    vowels[3] = "o";
    vowels[4] = "u";

    String[] instruments = new String[4];

    instruments[0] = "cello";
    instruments[1] = "guitar";
    instruments[2] = "violin";
    instruments[3] = "double bass";

    for (int a = 0; a < instruments.length; a++)
     {
		String instrument = instruments[a];

		for (int i = 0; i < vowels.length; i++)
		{
			instrument = instrument.replace(vowels[i], "");
		}

		System.out.println(instrument);
     }
 }