Writing while Statements

Chia sẻ: Nghia Tuan | Ngày: | Loại File: PDF | Số trang:5

0
43
lượt xem
2
download

Writing while Statements

Mô tả tài liệu
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Báo cáo bằng văn bản trong khi Bạn sử dụng một tuyên bố, trong khi liên tục chạy một tuyên bố trong khi một biểu thức Boolean là đúng sự thật. Cú pháp của một tuyên bố trong khi đó là: booleanExpression (trong khi) tuyên bố Biểu thức Boolean được đánh giá

Chủ đề:
Lưu

Nội dung Text: Writing while Statements

  1. Writing while Statements You use a while statement to repeatedly run a statement while a Boolean expression is true. The syntax of a while statement is: while ( booleanExpression ) statement The Boolean expression is evaluated and, if it's true, the statement runs and the Boolean expression is evaluated again. If the expression is still true, the statement is repeated and the expression evaluated again. This process continues until the Boolean expression evaluates to false when the while statement exits; execution then continues with the first statement after the while statement. A while statement shares many syntactic similarities with an if statement (in fact, the syntax is identical except for the keyword): • The expression must be a Boolean expression. • The Boolean expression must be written inside parentheses. • If the Boolean expression evaluates to false when first evaluated, the statement does not run. • If you want to perform two or more statements under the control of a while statement, you must use curly braces to group those statements in a block. Here's a while statement that writes the values 0 through 9 to the console: int i = 0; while (i != 10) { Console.WriteLine(i); i++; } All while statements should terminate at some point. A common beginner's mistake is forgetting to include a statement to eventually cause the Boolean expression to evaluate to false and terminate the loop. In the example, the i++ statement performs this role. NOTE The variable, i, in the while loop controls the number of iterations that are performed. This is a very common idiom, and the variable that performs this role is sometimes called the Sentinel variable. In the following exercise, you will write a while loop to read the contents of a source file one line at a time and write each line to a text box in a Windows application.
  2. Write a while statement 1. Using Visual Studio 2005, open the WhileStatement project, located in the \Microsoft Press\Visual CSharp Step by Step\Chapter 5\WhileStatement folder in your My Documents folder. 2. On the Debug menu, click Start Without Debugging. Visual Studio 2005 builds and runs the Windows application. The application itself is a simple text file viewer, allowing you to select a file and display its contents. 3. Click Open File. The Open dialog box opens. 4. Navigate to the \Microsoft Press\Visual CSharp Step by Step\Chapter 5\ WhileStatement\WhileStatement folder in your My Documents folder. 5. Select the Form1.cs file, and then click Open. The name of the source file, Form1.cs, appears in the small text box, but the contents of Form1.cs do not appear in the large text box. This is because the code that reads the contents of the source file and displays it in the large text box has not yet been implemented. You will add this functionality in the following steps. 6. Close the form and return to Visual Studio 2005. 7. Display the code for the file Form1.cs in the Code and Text Editor window. Locate the openFileDialog_FileOk method. This method is called when the user clicks the Open button after selecting a file in the Open dialog box. The body of the method is currently implemented as follows: string fullPathname = openFileDialog.FileName; FileInfo src = new FileInfo(fullPathname); filename.Text = src.Name; /* add while loop here */ The first statement declares a string variable called fullPathname and initializes it to the FileName property of the openFileDialog object. This statement initializes fullPathname to the full name (including the folder) of the source file selected in the Open dialog box. NOTE The openFileDialog object is an instance of the OpenFileDialog component that is available in the Toolbox. This component provides methods that you can use to
  3. display the standard Windows Open dialog box, select a file, and retrieve name and path of the selected file. The second statement declares a FileInfo variable called src and initializes it to an object that represents the file selected in the Open dialog box. (FileInfo is a class provided by the Microsoft .NET Framework that allows you to manipulate files.) The third statement assigns the Text property of the filename control to the Name property of the src variable. The Name property of the src variable holds the name of the file selected in the Open dialog box without its folder. This assignment makes the name of the file appear in the filename component of the Windows form. 8. Replace the /* add while loop here */ comment with the following statement: source.Text = ""; The source field is the large text box on the form. Setting its Text property to the empty string ("") clears any text that is currently displayed. 9. Type the following statement after the line you just added to the openFileDialog_FileOk method: TextReader reader = src.OpenText(); This statement declares a TextReader variable called reader. (TextReader is another class, provided by the .NET Framework, that you can use for reading streams of characters from sources such as files. It is located in the System.IO namespace) The OpenFileDialog class provides the OpenText method for opening the file selected by the user in the Open dialog. The OpenText method returns a TextReader object. This statement initializes reader to the TextReader object returned from the src.OpenText method call. The reader variable can now be used to read the file chosen by the user. 10. Type the following statements after the previous line you added to the openFileDialog_FileOk method: 11. string line = reader.ReadLine(); 12. while (line != null) 13. { 14. source.Text += line + '\n'; 15. line = reader.ReadLine(); 16. } reader.Close();
  4. This code declares a string variable called line which is used to hold each line of text as the reader reads it from the file. The statement calls the reader.ReadLine method to read the first line from the file. This method returns either the next line of text, or a special value called null if there are no more lines to read. The result of this call is assigned to the line variable. The Boolean expression at the start of the while loop examines the value in the line variable. If it is not null, the body of the loop displays the line of text by appending it to the end of the Text property of the source TextBox, together with a newline character ('\n' – the ReadLine method of the TextReader object strips out the newline characters as it reads each line, so the code needs to add it back in again). The while loop then reads in the next line of text (this is the update part of the loop) before performing the next iteration. When the loop finishes, the call to the Close method of the TextReader object closes the file. TIP As you become more experienced with C# syntax, you will find that you can abbreviate the code in the while loop as follows: string line; while ((line = reader.ReadLine()) != null) { source.Text += line + '\n'; } reader.Close(); In this case, the Boolean expression at the start of the loop also performs the initialization and update. The ReadLine method is called, and the return value assigned to the line variable. However, an assignment statement actually yields a value—the value of the expression being assigned. Therefore, you can compare the result of an assignment expression by using a relational operator to produce a Boolean result. In this example, if the value assigned is null, the value of the assignment expression is null, and the comparison to null is true. 17. On the Debug menu, click Start Without Debugging. 18. Click Open File. The Open dialog box opens. 19. Navigate to the \Microsoft Press\Visual CSharp Step by Step\Chapter 5\WhileStatement\WhileStatement folder in your My Documents folder. Select the Form1.cs file and then click Open. This time the contents of the selected file are displayed in the text box:
  5. 20. In the text box, locate the openFileDialog_FileOk method. Verify that this method contains the code you just added. 21. Click Close. You return to the Visual Studio 2005 programming environment.
Đồng bộ tài khoản