Thursday, April 6, 2017

Random File: Program Code ( visual basic )

Computer Science(9608) notes and Resources










Imports System.IO
Module Module1



    Structure employeerecord

        <VBFixedString(15)> Dim firstname As String
        <VBFixedString(15)> Dim lastname As String
        <VBFixedString(15)> Dim title As String

    End Structure



    Dim employee As employeerecord
    Dim filenumber As Integer
    Dim lastrec As Integer
    Dim position As Integer
    Dim reclength As Long = Len(employee)
    Dim deleted As Boolean = False




    Function randomgetlastrecord() As Integer
        filenumber = FreeFile()
        FileOpen(filenumber, "d:/employee.txt", OpenMode.Random, , , reclength)
        Dim lastrecord As Long
        lastrecord = 1

        Do While Not (EOF(filenumber))

            FileGet(filenumber, employee, lastrecord)
            lastrecord = lastrecord + 1

        Loop

        FileClose(filenumber)
       Return lastrecord

    End Function





    Sub randominputintofile()

        Dim employeefirstname As String
        Dim employeelastname As String
        Dim employeetitle As String

        Dim i As Integer

        For i = 1 To 3

            lastrec = randomgetlastrecord()

            filenumber = FreeFile()
            FileOpen(filenumber, "d:/employee.txt", OpenMode.Random, , , reclength)

            Console.WriteLine("enter firstname")
            employeefirstname = Console.ReadLine()
            Console.WriteLine("enter lastname")
            employeelastname = Console.ReadLine()
            Console.WriteLine("enter title")
            employeetitle = Console.ReadLine()

            employee.firstname = employeefirstname
            employee.lastname = employeelastname
            employee.title = employeetitle

            FilePut(filenumber, employee, lastrec)
            FileClose(filenumber)

        Next

    End Sub





    Sub randomgetfromfile()
        filenumber = FreeFile()
        FileOpen(filenumber, "d:/employee.txt", OpenMode.Random, , , reclength)

        position = 1

        Do While Not EOF(filenumber)

            FileGet(filenumber, employee, position)
            Console.WriteLine(employee.firstname & " " & employee.lastname & " " & employee.title)
            position = position + 1

        Loop

        FileClose(filenumber)

    End Sub

    Sub randomsearchrecord()

        Dim sname As String
        Console.WriteLine("enter name to search")
        sname = Console.ReadLine()

        filenumber = FreeFile()

        Dim found As Boolean = False
        FileOpen(filenumber, "d:/employee.txt", OpenMode.Random, , , reclength)

        Do While Not EOF(filenumber) And found = False

            FileGet(filenumber, employee, )

            If (Trim(employee.firstname) = sname) Then
                position = Loc(filenumber)
                found = True
            End If

        Loop

        If found = True Then
            Console.WriteLine("record found at position " & position)
            deleted = True

        Else
            Console.WriteLine("no record exits ")
        End If

        FileClose(filenumber)

    End Sub






    Sub randomupdaterecord()

        randomsearchrecord()

        Console.WriteLine("required position is " & position)

        filenumber = FreeFile()
        FileOpen(filenumber, "d:/employee.txt", OpenMode.Random, , , reclength)

        Seek(filenumber, position)

        employee.lastname = "dangol"
        employee.title = "lecturer"

        FilePut(filenumber, employee, )
        FileClose(filenumber)
    End Sub






    Sub randomdeleterecord()

        randomsearchrecord()
        Dim filenumber1, filenumber2 As Integer
        filenumber1 = FreeFile()
        FileOpen(filenumber1, "d:/employee.txt", OpenMode.Random, , , reclength)

        filenumber2 = FreeFile()
        FileOpen(filenumber2, "d:/employeenew.txt", OpenMode.Random, , , reclength)

        Do While Not EOF(filenumber1)

            If (Loc(filenumber1) <> position - 1) Then
                FileGet(filenumber1, employee, )
                FilePut(filenumber2, employee, )
            Else
                FileGet(filenumber1, employee, )
            End If
        Loop

        FileClose(filenumber1)
        FileClose(filenumber2)

        Kill("d:/employee.txt")

        Rename("d:/employeenew.txt", "d:/employee.txt")

        If deleted = True Then
            Console.WriteLine("Record deleted successfully")
        End If


    End Sub





    Sub Main()

        Console.WriteLine("Random file handling")
        Console.WriteLine("")
        Console.WriteLine("enter 1 to add record")
        Console.WriteLine("")
        Console.WriteLine("enter 2 to list record")
        Console.WriteLine("")
        Console.WriteLine("enter 3 to search record")
        Console.WriteLine("")
        Console.WriteLine("enter 4 to edit record")
        Console.WriteLine("")
        Console.WriteLine("enter 5 to delete record")
        Console.WriteLine("")

        Dim choice As Integer
        Console.WriteLine("ENTER YOUR CHOICE")
        choice = Console.ReadLine()
        Select Case choice
            Case 1
                randominputintofile()
            Case 2
                randomgetfromfile()
            Case 3
                randomsearchrecord()
            Case 4
                randomupdaterecord()
            Case 5
                randomdeleterecord()
            Case Else
                Console.WriteLine("invalid entry")
        End Select

        Console.ReadLine()

     End Sub



End Module




                                                           - CIE A-LEVEL COMPUTER SCIENCE (  9608 )

Exception handling


Computer Science(9608) notes and Resources





Exception: An exception is a problem that occurs during the execution of a program due to unforeseen circumstances such as an attempt to divide by zero while the program is running.



 Exception handling: Exception handling is a mechanism in which a programming construct is ‘used to consistently trap, intercept and handle the error occurred during application execution



Advantages of Exception Handling

•      Exception handling allows us to control the normal flow of the program by using  exception handling in program.

•      It throws an exception whenever a calling method encounters an error providing that the calling method takes care of that error.

•      It also gives us the scope of organizing and differentiating between different errors types using a separate block of codes. This is done with the help of try-catch blocks.

•      Provides a type-safe, integrated approach for coping with the unusual predictable problem that arises while executing program.

•      Provide means to detect and report an “exceptional circumstance” so  that appropriate action can be taken

•      Easy identification of program code and error handling code (separating error handling code from “regular” code)

•      Meaningful error reporting

•      Grouping error types and error differentiation

•      Increased reliability and better performance







Module Module1

    Sub Main()
        Dim num1, num2 As Integer
        Console.WriteLine("Enter any number: ")
        num1 = Console.ReadLine()
        Console.WriteLine("Again enter any number: ")
        num2 = Console.ReadLine()
        Console.WriteLine("numberator/denominator = " & (num1 / num2))
        Console.ReadLine()
    End Sub

End Module

 If the user enter value 6 for num1 and value 3 for num2, the answer is 2
 If the user enter value 0 for num2, the answer is infinity
 If a user enters a char or any string value., the program crashes





To solve any unforeseen event, the try catch block can be used

Module Module1

    Sub Main()
        Dim num1, num2 As Integer
        Try
            Console.WriteLine("Enter any number: ")
            num1 = Console.ReadLine()
            Console.WriteLine("Again enter any number: ")
            num2 = Console.ReadLine()
            Console.WriteLine("numberator/denominator = " & (num1 / num2))
        Catch ex As Exception
            Console.writeline("Invalid input")
        End Try
        Console.ReadLine()
    End Sub

End Module


Now, the problem is resolved and the user is informed about the wrong input.




Importance of exception handlingTo make sure that program always run smoothly and does not crash any event.


                                                           - CIE A-LEVEL COMPUTER SCIENCE (  9608 )

Serial File: Program code ( visual basic )

Computer Science(9608) notes and Resources







Writing records to file

Module Module1

    Sub Main()

        Dim sw As IO.StreamWriter
        sw = IO.File.CreateText("d:/staff.txt")

        sw.WriteLine("ram 100")
        sw.WriteLine("shyam 200")
        sw.WriteLine("hari 300")
        sw.WriteLine("sita 400")
        sw.WriteLine("gita 500")

        sw.Close()

        Console.ReadLine()
    End Sub

End Module













Appending records to file



Module Module1

    Sub Main()

        Dim sw As IO.StreamWriter
        sw = IO.File.AppendText("d:/staff.txt")

        sw.WriteLine("ramesh 600")
        sw.WriteLine("suresh 700")
        sw.WriteLine("gopal 800")

        sw.Close()

        Console.ReadLine()
    End Sub

End Module











Reading all records from file

Imports System.IO
Module Module1

    Sub Main()

        Dim staffdtl As String
        Dim sr As StreamReader
        sr = File.OpenText("d:/staff.txt")

        Do Until sr.Peek = -1

            staffdtl = sr.ReadLine()

            Console.WriteLine(staffdtl)

        Loop

        sr.Close()

        Console.ReadLine()
    End Sub

End Module










Searching name in the list

Imports System.IO
Module Module1

    Sub Main()

        Dim staffdtl As String
        Dim found As Boolean = False
        Dim breakvalue() As String

        Dim sr As StreamReader

        sr = File.OpenText("d:/staff.txt")

        Dim sname As String
        Console.WriteLine("enter name to search")
        sname = Console.ReadLine()

        Do Until sr.Peek = -1

            staffdtl = sr.ReadLine()
            breakvalue = staffdtl.Split(" ")
            If breakvalue(0) = sname Then
                found = True
            End If

        Loop

        sr.Close()

        If found = True Then
            Console.WriteLine(sname & " exists in the list")
        Else
            Console.WriteLine("no record exists")
        End If

        Console.ReadLine()
    End Sub

End Module










Deleting record from a file


Imports System.IO
Module Module1

    Sub Main()

        Dim staffdtl As String
        Dim breakvalue() As String

        Dim sr As StreamReader
        sr = File.OpenText("d:/staff.txt")

        Dim sw As StreamWriter
        sw = File.CreateText("d:/staffnew.txt")

        Dim sname As String
        Console.WriteLine("enter name to delete")
        sname = Console.ReadLine()


     

        Do Until sr.Peek = -1

            staffdtl = sr.ReadLine()
            breakvalue = staffdtl.Split(" ")

            If breakvalue(0) <> sname Then
                sw.WriteLine(staffdtl)
            End If

        Loop

        sw.Close()
        sr.Close()

        File.Delete("d:/staff.txt")
        File.Move("d:/staffnew.txt", "d:/staff.txt")

        Console.ReadLine()
    End Sub


End Module




                                                           - CIE A-LEVEL COMPUTER SCIENCE (  9608 )

STACK: Program code ( visual basic )

Computer Science(9608) notes and Resources






STACK: A Stack has a Last In First Out ( LIFO ) data structure, i.e., the last element to enter would be the first one to be processed.


Implementation of Stack in Visual basic.




Module Module1


    Dim item As String
    Dim top As Integer
    Dim arraystack(10) As String


    Sub Main()
        Dim tempItem As String
        Dim counter As Integer
        Dim choice As Integer

        createEmptyStack()

        Do
            Console.WriteLine("Select any option: ")
            Console.WriteLine("  1. Inserting items in Stack")
            Console.WriteLine("  2. Deleting an item in stack")
            Console.WriteLine("  3. Searching an item in stack")
            Console.WriteLine("  4. Making stack empty")
            Console.WriteLine("  5. Listing all the itms from stack")
            Console.WriteLine("  0. Exit")

            Console.Write("     =>  ")
            choice = Console.ReadLine()
            Select Case choice

                Case 1

                    Console.WriteLine()
                    Console.WriteLine(" Enter item: ")
                    Console.Write("     => ")

                    tempItem = Console.ReadLine()
                    insertItemStack(tempItem)

                    Console.Clear()

                Case 2
                    removeItemStack()
                    Console.Clear()

                Case 3
                    Console.Clear()

                    Console.Write(" Enter an item to be searched: ")
                    tempItem = Console.ReadLine()

                    findItem(tempItem)
                    Console.Clear()

                Case 4

                    createEmptyStack()
                    Console.Clear()

                Case 5

                    Console.Clear()

                    If top = 0 Then
                        Console.WriteLine(" Stack is empty")
                    Else
                        For counter = top To 1 Step -1
                            Console.WriteLine(arraystack(counter))
                        Next
                    End If

                    Console.ReadKey()
                    Console.Clear()

            End Select

        Loop Until choice = 0
    End Sub




    Sub createEmptyStack()
        top = 0
    End Sub




    Sub insertItemStack(ByVal InsertItem As String)
        If top = arraystack.Length() - 1 Then
            Console.WriteLine("Stack is full")
        Else
            top = top + 1
            arraystack(top) = InsertItem
            Console.WriteLine(InsertItem & " inserted into sack")
            Console.WriteLine()
            Console.WriteLine(" Press any key to continue....")
        End If

        Console.ReadKey()
    End Sub





    Sub removeItemStack()
        If top = 0 Then
            Console.WriteLine("Stack is empty")
        Else
            item = arraystack(top)
            top = top - 1
            Console.WriteLine(item & " has been deleted")
            Console.WriteLine()
            Console.WriteLine(" Press any key to continue....")
        End If

        Console.ReadKey()
    End Sub




    Sub findItem(ByVal searchItem As String)
        Dim count As Integer
        For count = top To 1 Step -1
            If arraystack(count) = searchItem Then
                Console.WriteLine(searchItem & " is found at position " & count)
                Console.WriteLine()
                Console.WriteLine(" Press any key to continue....")
            End If
        Next

        Console.ReadKey()
    End Sub



End Module


                                                           - CIE A-LEVEL COMPUTER SCIENCE (  9608 )