Tuesday, March 25, 2008

Boxes of Stars (Loops continued)

We learned how we could use loops to print out stars in various patterns like a box of stars [code]:



Or even an empty box of stars :



We have to use a Nested For Loop in order to print out lines of stars row by row. The outer loop represents each row, and the inner loop represents each column. Each row was constructed by using a String, since we can only print to a listbox one line at a time.

In the empty stars example we have to use If/Else statements in order to tell if we were printing out one of the borders. If we were at a border (outer or inner control variable is equal to 1 or num, where num is the total number of rows and columns) then we would print out a star, Else we will only print out a space.

Your HW is to print out the empty box of stars. You must ask the user if what number they like and then check to make sure that the number is in a range of 3 to 20.

Tuesday, March 18, 2008

Loops

We finished up Chapter 6.1 in class today. We learned that we could use loops in order to accomplish tasks that should be done several times using Loops. We learned about three types of loop structures:

Do Until
Do While
For Next


We can write a loop using any of these three structures and any loop written in one of these structures can be rewritten using one of the other two. The basic syntax for each of these loops are:


For variable = (starting point) To (ending point)
'Do statements until we reach the ending point
Next 'Update condition variable

'**************************************

'Set condition before entering loop
Do While condition
'Do statements until condition is false
'Update the condition
Loop

'**************************************

'Set condition before entering loop
Do
'Do statements until condition is true
'Update the condition
Loop Until condition


In all three loop structures we have three parts that are the same:
1) A starting point for the condition we are checking
2) An endpoint for the condition
3) An update for the condition

We must have all three things for the loop to execute and end execution. Without (3) from above for example, we would have an infinite loop which is definitely not what was intended.

Also notice that the Do While and the Do Until loops are opposites. Do While loops until the condition is False whereas the Do Until loop will loop until the condition is True. Also the Do Until is always guaranteed to loop at least once. We have no such guarantee with the Do While loop.

Do While Examples

Dim i As Integer = 1
Do While i <= 10
'List out the numbers from 1 to 10
lstOut.Items.Add( i )
i += 1
Loop


Dim i As Integer = 1
Dim num As Integer
num = CInt(InputBox("Enter a #:",""))
Do While i <= num
'List out the numbers from 1 to num
lstOut.Items.Add( i )
i += 1
Loop

Do Until Examples

Dim i As Integer = 1
Do
'List out the numbers from 1 to 10
lstOut.Items.Add( i )
i += 1
Loop Until i > 10


Dim i As Integer = 1
Dim num As Integer
num = CInt(InputBox("Enter a #:",""))
Do
'List out the numbers from 1 to num
lstOut.Items.Add( i )
i += 1
Loop Until i > num

For Next Examples

For( i As Integer = 1 To 10)
'List out the numbers from 1 to 10
lstOut.Items.Add( i )
Next


Dim num As Integer
num = CInt(InputBox("Enter a #:",""))
For( i As Integer = 1 To num)
'List out the numbers from 1 to num
lstOut.Items.Add( i )
Next

Writing to Files

In order to write to files, you will have to create a StreamWriter. Here is an example:

Dim sw As IO.StreamWriter
sw = IO.File.CreateText("newfilename.txt")
sw.WriteLine("This will go in the new file")
sw.Close()

If you use CreateText as shown above, then the file in quotes will be created and ready for use. If the file existed before you opened it, the file contents will be deleted, even if nothing is writen to the file. If you just want to place the new text at the end of the existing file, you can use AppendText() instead of CreateText().

Another thing you should know, is that the text will not be written to the file unless you Close() the file.

If you simply place the name of the file in quotes without an absolute path, then the file will be saved in the MyDocuments\Visual Studio 2005\Projects\[project name]\[project name]\bin\Debug folder, where [project name] is the name of your project.

File I/O [Reading a File]

Reading Data From Text Files:

There are a few rules to follow when trying to read data from a text file. Text files are written using the standard program Notepad or recently Notepad++. They have the extension .txt. So here are the rules to use them in a VB program.

1. Declare a variable that will handle the reading. For the purpose of the examples below:

Dim sr As IO.StreamReader


The StreamReader is part of the IO (input.output) library. This will read a stream of characters coming from the internet or a disk. The text file will be located on the disk drive.

2. Then, using the variable, execute the statement:

sr = IO.File.OpenText( filename )

where filename is the exact name and path of the text file. For the purpose of the course, ALL text files must be in the bin\Debug folder where your project is located. Here is an example path:

My Documents\Visual Studio 2005\Projects\program\program\bin\Debug

That is indeed a long path. Place the text file in that folder so you don't need to type out the whole name each time.

3. Then, read the data lines IN ORDER, the same order they appear in the file.

To place data from the file into a variable, use the ReadLine function available from the StreamReader library. Using the rule about input from the InputBoxes, everything read from a file will be stored as a string. If you need to gather a numeric value from the file, use the appropriate conversion function from the previous section.

strVar = sr.ReadLine 'any string variable
numVar = CDbl( sr.ReadLine ) 'a double type variable

If all the statements in the file have been read, each subsequent ReadLine call will get a value of Nothing by default.

4. Finally, close the file and continue with the program (if anything else is left).

sr.Close()

That is it in terms of gathering data from a text file. Here is a short program from the textbook example. The text file is called "PAYROLL" and contains the following data IN ORDER:

Mike Jones
7.35
35
John Smith
6.75
33

Program:


Private Sub btnCompute_Click(...) Handles btnCompute.Click

Dim sr As IO.StreamReader = IO.File.OpenText("PAYROLL.TXT")
'The file is in the bin subfolder in Debug

Dim name As String
Dim hourlyWage, hoursWorked, salary As Double

name = sr.ReadLine
hourlyWage =
CDbl(sr.ReadLine)
hoursWorked =
CDbl(sr.ReadLine)
salary = hourlyWage * hoursWorked
lstPayroll.Items.Add(name &
" " & FormatCurrency(salary))

name = sr.ReadLine
hourlyWage =
CDbl(sr.ReadLine)
hoursWorked =
CDbl(sr.ReadLine)
sr.Close()

salary = hourlyWage * hoursWorked
lstPayroll.Items.Add(name &
" " & FormatCurrency(salary))

End Sub




We already know how to read from a file, by creating a StreamReader. For example:

Dim sr As IO.StreamReader
sr = IO.File.OpenText("nameOfFile.txt")

We can then read through the file by using a loop:

Do While sr.Peek <> -1
lstBox.Items.Add(sr.ReadLine)
Loop


Imports

Ever get tired of writing ``IO'' in front of everything dealing with files? You can import it at the top of your code and then you will not have to type it ever again:

Imports System.IO
Public Class
Form1

Notice that it goes BEFORE the class declaration of Form1. Now the code for declaring and using a StreamReader changes:

Dim sr As StreamReader
sr = File.OpenText("nameOfFile.txt")

Tuesday, March 4, 2008

Select Case

We will finish Chapter 5.3 on 3/6 which ends with Select Case. Remember that Select Case is just another structure that works like If statements. For example:

Dim num As Integer
num = CInt(txtIn.Text)
Select Case num
Case 1
MsgBox("You entered 1",,"")

Case 2 To 5
MsgBox("You entered a number from 2-5",,"")

Case 7,9,11
MsgBox("You entered an odd number from 7-11",,"")

Case Is > 12
MsgBox("You entered a number greater than 12",,"")

Case Else
MsgBox("You entered some other number",,"")

End Select

All of this works like the classic If/ElseIf/Else structure. so we could rewrite the above using If statements:

Dim num As Integer
num = CInt(txtIn.Text)
If num = 1 Then
MsgBox("You entered 1",,"")
ElseIf 2 <= num And num <= 5 Then
MsgBox("You entered a number from 2-5",,"")
ElseIf num = 7 Or num = 9 Or num = 11 Then
MsgBox("You entered an odd number from 7-11",,"")
ElseIf num > 12 Then
MsgBox("You entered a number greater than 12",,"")
Else
MsgBox("You entered some other number",,"")
End If


You can also use Select Case to compare Strings just like you can with If statements.