Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Microsoft CSharp Programming For The Absolute Beginner (2002) [eng]-1.pdf
Скачиваний:
46
Добавлен:
16.08.2013
Размер:
15.71 Mб
Скачать

However, associating the place with each number (such as the thumb for verse 1 and the shoe for verse 2) is more complex, so I decided to ship that code to another method. Take a look at this line, and you’ll see that it’s a little different:

message += getPlace(verseNum);

This sends the value of verseNum to another method, named getPlace(), but the getPlace() method seems to work differently than doVerse() and doChorus(). It doesn’t stand on its own in a line of code, but it returns a value you can do something with. In this case, the results of the call to getPlace(verseNum) will be appended to the message variable.

Returning a Value

You can write methods that receive values through parameters and methods that send values through a return statement. The Console.ReadLine() method is probably the classic example of the latter kind of method. You can usually spot methods that return a value by the way they are used. The new value is usually printed to the screen or assigned to a variable. Methods that don’t return a value are usually used in a line of code by themselves, such as doChorus(). I designed the getNumber() method so that it will accept a parameter (the verse number) and return the associated place. Here’s how it works:

string message = ""; switch (verseNum){

case 1:

message = "on my thumb "; break;

case 2:

message = "on my shoe "; break;

default:

message = "not yet defined"; break;

} // end switch return message; } // end getPlace

The code works as a simple switch statement. The message variable (again, unrelated to the other message variables because it’s defined locally in a method) gets some value based on the verse number. The value of message is returned in the last line of the method. Any code that invokes this method will receive the value of message.

Trick Use the F11 key trick to watch the flow of code through this program. It’s very important to see how the logic flows between methods. Mastering this trick is the key to building more complex programs successfully.

Figure 4.7 illustrates the output of the song as produced by the Song program.

84

Соседние файлы в предмете Программирование на C++