VB单选题(第7章)
- 格式:doc
- 大小:137.50 KB
- 文档页数:17
VB第七章测试题Visual Basic 6.0第七章测试题⼀、填空题1、⽂件管理控件有___________,__________,___________。
2、⽤于连接驱动器个数的属性是_________。
3、在⽬录列表框控件中,返回当前⽬录中⼦⽬录个数的属性是_________,返回当前路径的索引的属性是_________。
当前展开的⽬录⽤索引值_____表⽰。
当前展开⽬录以下的⽬录范围是___________ 。
4、在⽂件列表框控件中返回是否在⽂件列表框控件中进⾏复选的属性是__________。
5、当在⽂件列表中单击⼀个⽂件时发⽣_______事件。
6、⽂件访问的类型有3种:________,_______,_________。
7、顺序⽂件中记录的长度是_______的,随机⽂件中记录的长度是______的。
8、打开顺序⽂件的⽅式有三种,分别是_______,_______,______。
9、⽂件号取值范围是______________。
10、缓冲区⼤⼩不超过________字节,默认______字节。
11、关闭顺序⽂件的语句是_________。
12、在顺序⽂件中⽤来测试⽂件⼤⼩的函数是______。
13、⽤来测试⽂件末尾的函数是________。
14、定义记录类型的语句是_______。
15、打开随机⽂件时,应选择__________ ⼦句。
16、对随机⽂件进⾏读写分4个步骤:_______________,____________________,______________________,______________________________。
17、在随机⽂件中,将记录读⼊变量的语句是________,将变量写⼊记录的语句是_________。
18、FSO对象模型包含在____________类型库中。
要引⽤该对象可选择_______菜单中的_______命令。
19、若要访问⼀个已有的驱动器、⽂件夹和⽂件,可以使⽤___________________对象中的_________,_________,_________⽅法。
第7章过程7.1 编写程序,利用Sub过程计算下式的值:s=a!+b!+c!a,b,c的值由键盘输入【参考答案】程序代码设计Private Sub Form_Click()Dim s As Integer, n As IntegerFor i = 1 To 3n = InputBox("n=")Call fact(n, f)s = s + fNext iPrint "s="; sEnd SubPrivate Sub fact(n, f)f = 1For i = 1 To nf = f * i图7-1程序运行结果Next iEnd Sub运行结果:如a、b、c的值分别输入为4、5、6则程序运行结果如图7-1所示:7.2 编写程序,打印100~200之间的所有素数。
要求:(1) 每行输出5个素数。
(2) 利用Function过程判断每个数是否为素数,是返回1,否则返回0。
【参考答案】程序代码设计Private Sub Form_Click()Print 2;k = 1For i = 3 To 100f = prime(i)If f = 1 Thenk = k + 1If k Mod 5 = 0 Then Print i Else Print i;End IfNext iEnd SubPrivate Function prime(n)prime = 1For i = 2 To n - 1 If n Mod i = 0 Then prime = 0: Exit ForNext iEnd Function程序运行结果如图7-2所示:7.3 编写程序,利用Function 过程计算下式的值: (1+2+3+…+m)+(1+2+3+…+n) y = ─────────────── (1+2+3+…+p)【参考答案】程序代码设计Private Sub Form_Click()m = Val(InputBox("输入m:"))n = Val(InputBox("输入n:"))p = Val(InputBox("输入p:"))y = (sum(m) + sum(n)) / sum(p)Print "sum="; yEnd SubPrivate Function sum(n)s = 0For i = 1 To ns = s + iNext isum = sEnd Function运行结果:如输入m 值为:20,n 值为:15,p 值为:10则程序运行结果如图7-3所示:7.4 编写Function 过程计算n!,调用该函数过程计算下式的值:S=1+1/(1+4!)+1/(1+4!+7!)+…+1/(1+4!+…+19!)【参考答案】程序代码设计Private Sub Form_Click()s = 0t = 0For i = 1 To 19 Step 3图7-2程序运行结果图7-3程序运行结果t = t + fact(i)s = s + 1 / tNext iPrint "s="; sEnd SubPrivate Function fact(n)f = 1For i = 1 To nf = f * iNext ifact = fEnd Function程序运行结果如图7-4所示。
第一章Visual Basic程序设计概述一、选择题1.Visual Basic是一种面向对象的可视化程序设计语言,采用了___A___的编程机制。
(A)事件驱动(B)按过程顺序执行(C)从主程序开始执行(D)按模块顺序执行2.在Visual Basic中最基本的对象是___C_____,它是采用程序的基石,是其它程序的容器。
(A)文本框(B)命令按钮(C)窗体(D)标签3.多窗体程序是由多个窗体组成。
在缺省情况下,VB在应用程序执行时,总是把____D____指定为启动窗体。
(A)不包含任何控件的窗体(B)设计时的第一个窗体(C)包含控件最多的(D)命名为Form1的窗体4.有程序代码如下:Text1.Text = "Visual Basic"则:Text1,Text和"Visual Basic"分别代表_____C___。
(A)对象,值,属性(B)对象,方法,属性(C)对象,属性,值(D)属性,对象,值5.Visual Basic是一种面向对象的程序设计语言,_____A___不是面向对象系统所包含的三要素。
(A)变量(B)事件(C)属性(D)方法6.Visual Basic的一个应用程序至少包含一个____B____文件,该文件存储窗体上使用的所有控件对象和有关的________、对象相应的________过程和________代码。
(A)模块、方法、事件、程序(B)窗体、属性、事件、程序(C)窗体、程序、属性、事件(D)窗体、属性、事件、模块7.以下不属于Visual Basic的工作模式是_____A___模式。
(A)编译(B)设计(C)运行(D)中断8.在VB集成环境创建VB应用程序时,除了工具箱窗口、窗体中的窗口、属性窗口外,必不可少的窗口是___C_____。
(A)窗体布局窗口(B)立即窗口(C)代码窗口(D)监视窗口9.保存新建的工程时,默认的路径是___B_____。
(A)My Documents (B)VB98 (C)\ (D)Windows10.将调试通过的工程经“文件”菜单的“生成.exe文件”编译成.exe后,将该可执行文件拿到其他机器上不能运行的主要原因是________。
教案讲稿第七章常用控件[旧课复习]:复习内容:1. 一维数组求和,求平均等2. 复习列表框组合框,为控件做准备复习目的:巩固一维数组,二维数组的应用复习时长:大约5分钟[新课导入]:导入方式:通过复习列表框引入本章节的常用控件,列举常用控件在日常软件中的使用方法。
导入目的:增强学生的学习积极性导入时长:大约5分钟[新课讲授]:重点:各种常用控件(单选按钮、复选框、滚动条、计时器)难点:计时器的应用(Interval属性,Timer事件)方法:运用多媒体辅助教学,采用案例教学和任务驱动等教学法。
7.1单选按钮单选按钮又称为选项按钮(OptionButton),单选按钮一般总是作为一个按钮组来完成工作的。
单选按钮组是一组相互排斥的选项按钮,在一般情况下,在单选按钮组中一次只能选择一个选项,如果一次要选择多个单选按钮,可以使用框架控件把单选按钮分组。
单选按钮的主要属性有:1.Caption属性:单选按钮的文本内容。
2.Value属性:单选按钮是否被选中的属性。
如果将该值为True或-1,单选按钮被选中,如果将该值为False或0,单选按钮未被选中。
3.Style属性:单选按钮的外观。
该值取0时,是标准的Windows风格;取1时,是图形风格。
单选按钮的事件:Click事件:单击单选按钮时触发该事件。
1.使用单选按钮控件【例7.1】设计一个简易血型选择器,用户界面如图7-1所示,由四个单选按钮和一个命令按钮以及一个文本框组成。
选中血型后单击“选择”按钮,结果显示在文本框中。
图7-1 简易血型选择器设计步骤如下:(1)建立应用程序用户界面。
(2)编写代码编写命令按钮Commandl的Click事件代码:Private Sub Command1_Click()If Option1.Value = True Then Text1.Text = "您是O型血"If Option2.Value = True Then Text1.Text = "您是A型血"If Option3.Value = True Then Text1.Text = "您是B型血"If Option4.Value = True Then Text1.Text = "您是AB型血"End Sub7.2 复选框复选框(CheckBox)可以从多个选择中选择一个或多个选项。
7.13. Searching a Sorted Array with Array Method BinarySearchLinear searches work well for small or unsorted arrays, but, for large unsorted arrays, linear searching is inefficient. If the array is sorted, the high-speed binary search technique can be used with class Array’s BinarySearch method. Our app that demonstrates method BinarySearch is nearly identical to the one in Fig. 7.14, so we show only the differences here. The complete code is located in the Fig07_15 folder with this chapt er’s examples. The sample outputs are shown in Fig. 7.15. The GUI for this app is identical to the one in Fig. 7.13.a) Creating random values to searchb) Searching for a value that is in the arrayc) Searching for a value that is not in the arrayFig. 7.15. Binary search of an array.As in Fig. 7.14, the user clicks the Create Data Button to generate random values. For method BinarySearch to perform correctly, the array must have been sorted. Method createDataButton_Click uses the following call to Array method Sort before displaying the values in the dataListBox:Array.Sort(searchData) ' sort array to enable binary searchingIn method searchButton_Click, we replaced lines 40–48 of Fig. 7.14 withDim index As Integer = Array.BinarySearch(searchData, searchKey)which uses Array method BinarySearch to perform a binary search for a key value. The method receives two arguments—the sorted integer array searchData (the array to search) and integer searchKey (the search key). If the value is found, method BinarySearch returns the index of the search key; otherwise, it returns a negative number.7.14. Rectangular ArraysThe arrays we’ve studied so far are one-dimensional arrays—they contain a list of values and use only one index to access each element. In this section, we introduce multidimensional arrays, which require two or more indices to identify particular elements. We concentrate on two-dimensional arrays—also known as rectangular arrays—which are often used to represent tables of values consisting of data arranged in rows and columns (Fig. 7.16). Each row is the same size, and each column is the same size (hence the term ―rectangular‖). To identify a particular table element, we specify two indices—by convention, the first identifies the element’s row, the second the element’s column. Figure 7.16 illustrates a rectangular array, a, containing three rows and four columns. A rectangular array with m rows and n columns is called an m-by-n array; the array in Fig. 7.16 is a 3-by-4 array.Fig. 7.16. Two-dimensional array with three rows and four columns.Every element in array a is identified in Fig. 7.16 by an element name of the form a(i, j), where a is the name of the array and i and j are the indices that uniquely identify the row and column, respectively, of each element in array a. Array indices are zero based, so the names of the elements in row 0 all have a first index of 0; the names of the elements in column 3 all have a second index of 3.Declaring and Initializing Rectangular ArraysA two-dimensional rectangular array numbers with two rows and two columns can be declared and initialized withClick here to view code imageDim numbers(1, 1) As Integer' numbers in a 2 by 2 arraynumbers(0, 0) = 1' leftmost element in row 0numbers(0, 1) = 2' rightmost element in row 0numbers(1, 0) = 3' leftmost element in row 1numbers(1, 1) = 4' rightmost element in row 1Alternatively, the initialization can be written on one line, as shown with and without local type inference below:Click here to view code imageDim numbers = {{1, 2}, {3, 4}}Dim numbers(,) As Integer = {{1, 2}, {3, 4}}In the second declaration, the comma in (,) indicates that numbers is a two-dimensional array. The values are grouped by row in braces, with 1 and 2 initializing numbers(0, 0) and numbers(0, 1), respectively, and 3 and 4 initializing numbers(1, 0) and numbers(1, 1), respectively. The compiler determines the number of rows by counting the number of sub-initializer lists (represented by the sets of data in curly braces) in the main initializer list. Then the compiler determines the number of columns in each row by counting thenumber of initializer values in the subinitializer list for that row. The subinitializer lists must have the same number of elements for each row.Manipulating a Rectangular ArrayThe app in Fig. 7.17 initializes rectangular array values and uses nested For...Next loops to traverse the array (that is, to manipulate every array element). The contents of the array are displayed in outputTextBox.Click here to view code image1' Fig. 7.17: RectangularArray.vb2' Initializing and displaying a rectangular array.3Public Class RectangularArray4' display the contents of a rectangular array5Private Sub RectangularArray_Load(sender As Object,6 e As EventArgs) Handles MyBase.Load78Dim values(,) As Integer = {{1, 2, 3}, {4, 5, 6}}910' output elements of the values array11For row = 0To values.GetUpperBound(0)12For column = 0To values.GetUpperBound(1)13 outputTextBox.AppendText(values(row, column) & vbTab)14Next column1516 outputTextBox.AppendText(vbCrLf)17Next row18End Sub' RectangularArray_Load19End Class' RectangularArrayFig. 7.17. Initializing and displaying a rectangular array.The app declares rectangular array values (line 8) and uses an initializer list to determine the number of rows, number of columns and initial values of the array’s elements. The initializer list contains two sublists. The number of sublists determines the number of rows in the array. The compiler uses the number of elements in the first sublistto determine the number of columns in each row. All subsequent sublists must have the same number of initializers as the first sublist; otherwise, a compilation error occurs. The first sublist initializes row 0 of the array to the values 1, 2 and 3; the second sublist initializes row 1 of the array to the values 4, 5 and 6.The nested For...Next statements in lines 11–17 display the elements of rectangular array values. The outer For...Next statement traverses the rows; the inner For...Next statement traverses the columns within a row. Each For...Next statement calls method GetUpperBound to obtain the upper bound of the dimension it traverses. GetUpperBound with the argument 0 (line 11) returns the number of rows. GetUpperBound with the argument 1 (line 12) returns the number of columns in each row.7.15. Case Study: Maintaining Grades Using a Rectangular ArrayWe now present a substantial case study using rectangular arrays. Consider the following problem statement:An instructor gives three tests to a class of 10 students. The grades on thesetests are integers in the range from 0 to 100. The instructor has asked you todevelo p an app to keep track of each student’s average and the class average.The instructor has also asked that there be a choice to view the grades as eithernumbers or letters. Letter grades should be calculated according to thefollowing grading system:Th e app should allow a user to input each student’s three test grades, thencompute each student’s average and the class average for all grades entered sofar. The app should display numeric grades by default. It should also display agrade distribution chart showing how many of the numeric grades fall into theranges 0–9, 10–19, ... 90–99 and 100.We’ll use a rectangular array with 10 rows and three columns to store the student grades. This app uses most of the programming concepts you’ve learned up to now i n this book. Figure 7.19 shows sample outputs for the Grade Report app.a) Grade Report window after the user has enter ed the first student’s grades and isabout to submit them.b) Grade Report window after five students’ grades have been entered.c) Grade Report window after the user has entered all 10 students’ grades.d) Grade Report window after the user has ente red all 10 students’ grades andclicked the Letter RadioButton to display letter grades.Fig. 7.18. Sample outputs for the Grade Report app.GUI for the Grade Report AppFigure 7.19 presents the GUI for the Grade Report app. In this app, we introduce RadioButton controls to allow the user to select between displaying grades in numeric or letter format. A RadioButton is a small white circle that either is blank or contains a small dot. When a RadioButton is selected, a dot appears in the circle. A RadioButton is known as a state button because it can be in only the ―on‖ (True) state or the ―off‖ (False) state. You’ve previously used the CheckBox state buttons (introduced in Chapter 5).Fig. 7.19. GUI for the Grade Report appRadioButton s are similar to CheckBox es, but RadioButton s normally appear as a group—only one RadioButton in the group can be selected at a time. Like car radio preset buttons, which can select only one station at a time, RadioButton s represent a setof options in which only one option can be selected at a time—also known as mutually exclusive options. By default, all RadioButton s become part of the same group. To separate them into several groups, each group must be in a different container (typically a GroupBox).A RadioButton’s Boolean Checked property indicates whether the RadioButton is checked (contains a small dot) or unchecked (blank). If the RadioButton is checked, the Checked property returns True; otherwise, it returns False.A RadioButton also generates an event when its checked state changes. Event CheckedChanged occurs when a RadioButton is either selected or deselected. We use this event to switch between the numeric grade and letter grade views in the gradesListBox.Grade Report AppOver the next several figures we’ll discuss the Grade Report app’s code. Due to the size of this app, we’ve split the source code into several small figures.Figure 7.20 declares class GradeReport’s instance variables and Load event handler. The rectangular array grades (line 4) has 10 rows and 3 columns to store the grades for 10 students and three exams per student. Variable studentCount (line 5) keeps track of the number of students processed so far. After 10 students are processed, the app disables the input TextBox es and Submit Button. The GradeReport_Load event handler (lines 8–13) displays the column heads in the gradesListBox.Click here to view code image1' Fig. 7.20: GradeReport.vb2' Grade report using a rectangular array.3Public Class GradeReport4Dim grades(9, 2) As Integer' stores 10 students' grades on 3 tests5Dim studentCount As Integer = 0' number of students entered67' display heading in gradeListBox8Private Sub GradeReport_Load(sender As Object,9 e As EventArgs) Handles MyBase.Load10' headings row for gradesListBox11 gradesListBox.Items.Add(vbTab & vbTab & "Test 1" & vbTab &12"Test 2" & vbTab & "Test 3" & vbTab & "Average")13End Sub14Fig. 7.20. Grade Report app: Instance variables and method GradeReport_Load. Method submitButton_ClickWhen the user enters three grades, then presses the Submit Button, method submit-Button_Click (Fig. 7.21) processes the three grades and displays the current class average and a bar chart showing the grade distribution for all grades entered so far. Lines 20–22 get the three grades from the TextBox es and assign them to the elements of the grades array in row studentCount. Lines 25–37 build a String representing the current student’s grades and average. Lines 28–37 loop through the current row of the grades array and append either a letter grade or numeric grade, based on whether the letterRadioButton’s Checked property is True. If so, line 32 calls method LetterGrade to get the letter representation of the numeric grade. Otherwise, line 35 appends the numeric grade. Line 40 calls method CalculateStudentAverage to obtain the current student’s average for the three exams.Click here to view code image15' process one student's grades16Private Sub submitButton_Click(sender As Object,17 e As EventArgs) Handles submitButton.Click1819' retrieve the student's grades20 grades(studentCount, 0) = Convert.ToInt32(test1TextBox.Text)21 grades(studentCount, 1) = Convert.ToInt32(test2TextBox.Text)22 grades(studentCount, 2) = Convert.ToInt32(test3TextBox.Text)2324' begin creating String containing the student's grades and average 25Dim output As String = "Student " & studentCount & vbTab2627' append each test grade to the output28For column = 0To grades.GetUpperBound(1)29' if the Letter RadioButton is checked30If letterRadioButton.Checked = True Then31' append letter grade to the output32 output &= vbTab & LetterGrade(grades(studentCount, column))33Else34' append number grade to the output35 output &= vbTab & grades(studentCount, column)36End If37Next3839' append the student's test average to the output40 output &= vbTab & CalculateStudentAverage(studentCount)4142 gradesListBox.Items.Add(output) ' add output to the ListBox43 studentCount += 1' update number of students entered44 averageLabel.Text = CalculateClassAverage() ' display class average45 DisplayBarChart() ' display the current grade distribution4647' clear the input TextBoxes and set focus to first TextBox48 test1TextBox.Clear()49 test2TextBox.Clear()50 test3TextBox.Clear()51 test1TextBox.Focus()5253' limit number of students54If studentCount = grades.GetUpperBound(0) + 1Then55 inputGroupBox.Enabled = False' disable GroupBox's controls56End If57End Sub' submitButton_Click58Fig. 7.21. Grade Report app: Method submitButton_Click.Line 42 displays the information for the current student. Line 43 updates the student count. Line 44 and 45 call the methods CalculateClassAverage and DisplayBarChart to determine the current class average and to display a grade distribution chart based on the grades that have been entered so far. Lines 48–51 prepare the user interface to receive the next student’s grades by clearing the TextBox es and giving the focus to the test1-TextBox. Finally, lines 54–56 check whether grades have been entered for 10 students. If so, line 55 sets the inputGradeGroupBox’s Enabled property to False, which disables all the controls in the GroupBox, preventing the user from entering more grades.Method RadioButton_CheckChanged: Handling Multiple Events with One Event HandlerAt any time, the user can select the Numeric or Letter RadioButton to change how the grades are displayed in the gradesListBox. When the selected RadioButton changes, method RadioButton_CheckedChanged (Fig. 7.22) is called. In this example, we handle both RadioButton’s CheckedChanged events with the same event handler. To do this, double click the Numeric RadioButton, then rename the event handler to RadioButton_Checked-Changed. Next, add letterRadioButton.CheckedChanged to the Handles clause of the event handler (lines 62–63). Now this method is called when the CheckChanged event occurs for either RadioButton. In this case, as long as at least one student has been processed, line 67 calls method DisplayGrades to update the presentation of the grades in gradesListBox.Click here to view code image59' handles Numeric and Letter RadioButtons' CheckChanged events60Private Sub RadioButton_CheckedChanged(sender As Object,61 e As EventArgs) _62Handles numericRadioButton.CheckedChanged,63 letterRadioButton.CheckedChanged6465' if there are grades to display, call DisplayClassGrades66If studentCount > 0Then67 DisplayClassGrades()68End If69End Sub' RadioButton_CheckedChanged70Fig. 7.22. Grade Report app: Method RadioButton_CheckedChanged. Method CalculateStudentAverageMethod CalculateStudentAverage (Fig. 7.23) processes one row of the grades array to determine the corresponding s tudent’s average. The method returns a String containing either the letter grade for that student’s average or the numeric value, depending on whether the letterRadioButton’s Checked property is True.Click here to view code image71' calculates a student's test average72Function CalculateStudentAverage(row As Integer) As String73Dim gradeTotal As Integer = 0' student's total grade7475' sum the grades for the student76For column = 0To grades.GetUpperBound(1)77 gradeTotal += grades(row, column)78Next7980Dim studentAverage As String = String.Empty' output string8182' calculate the student's test average83If letterRadioButton.Checked = True Then84 studentAverage =85 LetterGrade(gradeTotal / (grades.GetUpperBound(1) + 1))86Else87 studentAverage = String.Format("{0:F}",88 (gradeTotal / (grades.GetUpperBound(1) + 1)))89End If9091Return studentAverage ' return the student's average92End Function' CalculateStudentAverage93Fig. 7.23. Grade Report app: Method CalculateStudentAverage. Method CalculateClassAverageMethod CalculateClassAverage (Fig. 7.24) processes the grades array to determine the class average for all the grades entered so far. The method returns a String containing either the letter grade for the class average or the numeric value, depending on whether the letterRadioButton’s Checked property is True.Click here to view code image94' calculates the class average95Function CalculateClassAverage() As String96Dim classTotal As Integer = 0' class's total grade9798' loop through all rows that currently contain grades99For row = 0To studentCount - 1100' loop through all columns101For column = 0To grades.GetUpperBound(1)102 classTotal += grades(row, column) ' add grade to total103Next column104Next row105106Dim classAverage As String = String.Empty' output string107108' if the Letter RadioButton is checked, return letter grade109If letterRadioButton.Checked = True Then110 classAverage = LetterGrade(classTotal /111 (studentCount * (grades.GetUpperBound(1) + 1)))112Else' return numeric grade113 classAverage = String.Format("{0:F}", (classTotal /114 (studentCount * (grades.GetUpperBound(1) + 1))))115End If116117Return classAverage ' return the class average118End Function' CalculateClassAverage119Fig. 7.24. Grade Report app: Method CalculateClassAverage.Method LetterGradeMethod LetterGrade (Fig. 7.25) receives a numeric grade and returns the corresponding letter grade as a String.Click here to view code image120' determines a letter grade corresponding to a numeric grade121Function LetterGrade(grade As Double) As String122Dim output As String' the letter grade to return123124' determine the correct letter grade125Select Case grade126Case Is >= 90127 output = "A"128Case Is >= 80129 output = "B"130Case Is >= 70131 output = "C"132Case Is >= 60133 output = "D"134Case Else135 output = "F"136End Select137138Return output ' return the letter grade139End Function' LetterGrade140Fig. 7.25. Grade Report app: Method LetterGrade.Method DisplayClassGradesMethod DisplayClassGrades (Fig. 7.26) displays the student grades and averages in the gradesListBox. Line 143 clears the ListBox’s current contents and lines 146–147 display the column heads in the ListBox. Lines 150–169 processes the grades array to display all the grades entered so far, displaying letter grades if letterRadioButton’s Checked property is True. Line 172 updates the class average and displays the result in averageLabel.Click here to view code image141' display the grades for all students entered142Sub DisplayClassGrades()143 gradesListBox.Items.Clear() ' clear the ListBox144145' add the header to the ListBox146 gradesListBox.Items.Add(vbTab & vbTab & "Test 1" & vbTab &147"Test 2" & vbTab & "Test 3" & vbTab & "Average")148149' loop through all the rows150For row = 0To studentCount - 1151Dim output As String = "Student " & row & vbTab152153' loop through all the columns154For column = 0To grades.GetUpperBound(1)155If letterRadioButton.Checked = True Then156' add letter grade to output string157 output &= vbTab & LetterGrade(grades(row, column))158Else159' add number grade to output string160 output &= vbTab & (grades(row, column))161End If162Next column163164' add the student's average to the output165 output &= vbTab & CalculateStudentAverage(row)166167' add the output to the ListBox168 gradesListBox.Items.Add(output)169Next row170171' update the class average172 averageLabel.Text = CalculateClassAverage()173End Sub' DisplayClassGrades174Fig. 7.26. Grade Report app: Method DisplayClassGrades.Method DisplayBarChartMany apps present data to users in a visual or graphical format. For example, numeric values are often displayed as bars in a bar chart. In such a chart, longer bars represent proportionally larger numeric values (see Fig. 7.18). Method DisplayBarChart (Fig. 7.27) displays a graphical summary of the grade distribution by creating a bar chart that shows how many numeric grades fall into each of the ranges 0–9, 10–19, ... 90–99 and 100. Click here to view code image175' display a bar chart of the grade distribution176Sub DisplayBarChart()177 barChartListBox.Items.Clear() ' remove current items178179' stores frequency of grades in each range of 10 grades180Dim frequency(10) As Integer181182' for each grade, increment the appropriate frequency183For row = 0To studentCount - 1184For column = 0To grades.GetUpperBound(1)185 frequency(grades(row, column) \ 10) += 1186Next column187Next row188189' for each grade frequency, display bar of asterisks190For count = 0 To frequency.GetUpperBound(0)191Dim bar As String' stores the label and bar192193' create bar label ( "00-09: ", ..., "90-99: ", "100: " )194If count = 10Then195 bar = String.Format("{0, 5:D}: ", 100)196Else197 bar = String.Format("{0, 2:D2}-{1, 2:D2}: ",198 count * 10, count * 10 + 9)199End If200201' append bar of asterisks202For stars = 1To frequency(count)203 bar &= ("*")204Next205206 barChartListBox.Items.Add(bar) ' display bar207Next count208End Sub' DisplayBarChart209End Class' GradeReportFig. 7.27. Grade Report app: Method DisplayBarChart.Lines 180–187 summarize the number of grades in each range using the elements of the 11-element array frequency. Next, lines 190–207 build a String containing the range of values represented by the current bar (lines 194–199) and a bar of asterisks representing the number of grades that fall into that range (lines 202–204). Line 206 then displays this String in the barCharListBox. The format String s in lines 195 and 197 use field widths to control the number of characters in which each value is output. The format specifier {0, 5:D} (line 195) indicates that an integer value will be displayed in a field of 5 characters right justified by default. So, if the number contains fewer than 5 characters, it will be preceded by an appropriate number of spaces. The format specifier {0, 2:D2} (line 197) indicates that an integer will be displayed in a field of 2 characters. The D2 forces the number to use two character positions—single digit numbers are preceded by a leading 0.7.16. Resizing an Array with the ReDim StatementAn array’s size cannot be changed, so a new array must b e created if you need to change the size of an existing array. The ReDim statement ―resizes‖ an array at execution time by creating a new array and assigning it to the specified array variable. The old array’s memory is eventually reclaimed by the runtime. Figure 7.28 demonstrates the ReDim statement.Click here to view code image1' Fig. 7.28: ReDimTest.vb2' Resize an array using the ReDim statement.3Public Class ReDimTest4' demonstrate ReDim5Private Sub ReDimTest_Load(sender As Object,6 e As EventArgs) Handles MyBase.Load78' create and initialize two 5-element arrays9Dim values1() As Integer = {1, 2, 3, 4, 5}10Dim values2() As Integer = {1, 2, 3, 4, 5}1112' display array length and the elements in array13 outputTextBox.AppendText(14"The original array has " & values1.Length & " elements: ")15 DisplayArray(values1)1617' change the size of the array without the Preserve keyword18ReDim values1(6)1920' display new array length and the elements in array21 outputTextBox.AppendText("New array (without Preserve) has " &22 values1.Length & " elements: ")23 DisplayArray(values1)2425' change the size of the array with the Preserve keyword26ReDim Preserve values2(6)27 values2(6) = 7' assign 7 to array element 62829' display new array length and the elements in array30 outputTextBox.AppendText("New array (with Preserve) has " &31 values2.Length & " elements: ")32 DisplayArray(values2)33End Sub3435' display array elements36Sub DisplayArray(array() As Integer)37For Each number In array38 outputTextBox.AppendText(number & " ")39Next4041 outputTextBox.AppendText(vbCrLf)42End Sub' DisplayArray43End Class' ReDimTestFig. 7.28. Resize an array using the ReDim statement.Line 9 creates and initializes a five-element array values1. Line 10 creates a second array named values2 containing the same data. Lines 13–15 display the size and elements of values1. Line 18 uses a ReDim statement to change the upper bound of values1 to 6, so that the array now contains seven elements. The ReDim statement contains keyword ReDim, followed by the name of the array to be "resized" and the new upper bound in parentheses. Lines 21–23 then display the size and elements of values1 again. The output of Fig. 7.28 shows that after the ReDim statement executes, the size of values1 is changed to 7 and the value of each element is reinitialized to the default value of the type of the array element (that is, 0 for Integer s). To save the original data stored in an array, follow the ReDim keyword with the optional Preserve keyword. Line 26 uses Preserve in the ReDim statement to indicate that the existing array elements are to be preserved in the now larger array after the array is resized. If the new array is smaller than the original array, the existing elements that are outside the bounds of the new array are discarded. If the new array is larger than the original array, all the existing elements are preserved in the now larger array, and the extra elements are initialized to the default value of the type of the array element. For example, after line 26 executes, the value of values2(5) is 0. Line 27 assigns the value 7 to values2(6), so that the now larger array values2 contains elements 1, 2, 3, 4, 5, 0 and 7. Lines 30–32 display the size and elements of values2.7.17. Wrap-UpThis chapter began our discussion of data structures, using arrays to store data in and retrieve data from lists and tables of values. We demonstrated how to declare an array, initialize an array and refer to individual elements of an array. We showed how to pass arrays to methods. We discussed how to use the For Each...Next statement to iterate。
实习内容:例题7-1以下程序段用来在C盘根目录下建立一个名为test.txt的顺序文件。
例题7-2某班30名同学学习成绩如表7-2所示。
建立一个名为“student.txt”的顺序文件存放该班同学的学习成绩,每条记录包括学号、姓名、高数、英语、物理、计算机刘向数据。
例题7-3对例题7-2中生成的“student.txt”文件记录进行如下处理:(1)计算每个学生的平均成绩。
(2)将平均成绩大于或等于80分的记录写入“student1.txt”文件中。
例题7-4统计例题7-3中生成的“student1.txt”文件中的记录数。
例题7-5将例题7-2生成的顺序文件“student.txt”读出,按随机方式写入随机文件“student2.txt”中。
例题7-6从随机文件“student2.txt”中读出数据,计算平均成绩,并将大于或等于80分的学生成绩写入另一个随机文件“student3.txt”中。
例题7-7以二进制模式建立一个数据文件,其中的内容是随机产生的100个大写字母。
例题7-8以二进制方式读取文件text。
Txt,并将结果显示在文本框中。
例题7-9编写一个复制文件的程序。
例题7-10编写一个加密软件,要求将源文件按“字节逐位倒排序加密法”,加密。
习题7-3把随机产生的200个4位整数存入顺序文件file1.txt中。
事件代码为:Private Sub Command1_Click()Dim a(1 To 200) As Integer, i%, n%, m%For i = 1 To 200a(i) = Int(Rnd * 9000 + 1000)Next iOpen "H:\VB实习\周晓伟\实验七\file1.txt" For Output As #1For m = 1 To 200Write #1, a(m);If m Mod 20 = 0 ThenPrint #1,End IfNext mCloseEnd Sub运行结果为:习题7-4从第三题的file1.txt文件中读出数据存入数组a中,从中挑选出所有各位和百位是偶数的数据存入数组b中,并存储到随机文件file2.txt中。
373 下列可调整图片框(PictureBox)的大小以适合图片的属性是().A) stretchB) autosizeC) pictureD) oledropmode答案 B374 图像框(Image)控件中,可缩放图片的属性是().A) autosizeB) pictureC) stretchD) oleDrawMode答案 C375 下面()对象在运行时一定不可见.A) LabelB) TimerC) TextD) Option答案 B376 下面哪些控件不会影响到界面设计效果().A) 定时器B) 文本框C) 标签D) PictureBox控件答案 A377 下面哪些控件不会影响到界面设计效果().A) LabelB) TextC) CommonDialogD) Frame答案 C378 形状控件所显示的图形不可能是().A) 圆B) 椭圆C) 圆角正方形D) 等边三角形答案 D379 选中复选框控件时,value属性的值是().A) TrueB) falseC) 0D) 1答案 D382 要将一个组合框设置为简单组合框(SimpleCombo),则应将其Style属性设置为().A) 0B) 1C) 2D) 3答案 B383 要使一个图片框控件能自动地附着在窗体的一条边上,应设置它的()属性.A) PictureB) AlignmentC) BorderD) Align答案 D384 要在窗体上显示图片,需设置窗体的()属性.A) CaptionB) IconC) PictureD) ControlBox答案 C385 一个菜单项是不是一个分隔条,由()属性决定.A) Name(名称)B) CaptionC) EnabledD) Visible答案 B386 以下()对象不具有Clear方法.A) 列表框B) 组合框C) 标签D) 图片框(PictureBox)答案 D387 以下不具有Picture属性对象是().A) 窗体B) 图片框(PictureBox)C) 图像框(Image)D) 文本框答案 D388 以下不允许用户在程序运行时输入文字的控件是().A) 标签框B) 文本框C) 下拉式组合框D) 简单组合框答案 A389 以下控件中不属于容器的是().A) Form控件B) PictureBoxC) ImageD) Frame答案 C390 引用列表框的最后一项应使用().A) List1.List(List1.ListCount-1)B) List1.List(List1.ListCount)C) List1.List(ListCount)D) List1.List(ListCount-1)答案 A391 用户可以通过设置菜单项的()属性值为FALSE来使该菜单项不可见.A) HideB) CheckedC) VisibleD) Enabled答案 C392 在VB中,下列不能作为存放对象的容器是().A) 窗体B) 框架C) 图片框(PictureBox)D) 图像框(Image)答案 D393 在程序代码中修改滚动条的value 属性时将触发滚动条的()事件.A) changeB) scrollC) dragdropD) gotfocus答案 A394 在列表框中当前被选中的列表项的序号是由下列哪个属性表示().A) ListB) IndexC) ListIndexD) TabIndex答案 C395 组合框的类型由Style属性决定,简单组合框的Style属性值应为().A) 0B) 1C) 2D) 3答案 B396 组合框的三种不同风格:下拉组合框、简单组合框和下拉列表框由()属性决定.A) StyleB) BoderStyleC) FillStyleD) DrawStyle答案 A397 组合框控件是将()组合成一个控件.A) 列表框控件和文本框控件B) 标签控件和列表框控件C) 标签控件和文本框控件D) 复选框控件和选项按钮控件答案 A398 组合框有三种风格,它们由Style属性所决定,其中为下拉列表框时, Style属性值应为().A) 0B) 1C) 2D) 3答案 C399 要清除已经在图片框(Picture)P1中打印的字符串而不清除其中加载的的图像,应使用语句().A) A.P1.ClsB) P1.picture=LoadPicture("")C) P1.Print ""D) P1.piture ""答案 A400 要清除组合框Combol中的所有内容,可以使用()语句.A) Combo1.ClsB) Combo1.ClearC) Combo1.DeleteD) Combo1.Remove答案 B401 用键盘的光标键选中某一菜单项,并按回车将触发菜单的()的事件.A) KeyPressB) KeyDownC) ClickD) KeyUp答案 C402 用鼠标拖动滚动条中滚动框并释放,将触发滚动条的()事件.A) ScrollB) ChangeC) DragOverD) A和B答案 D403 为使计时器控件每隔5秒钟产生一个计时器事件(Timer事件),则应将其Interval 属性值设置为().A) 5B) 500C) 300D) 5000答案 D404 当在滚动条内拖动滚块时触发()事件.A) KeyUpB) KeyPressC) ChangeD) Scroll答案 D405 设置框架的()属性值为False,其标题会变灰,框架中所有的对象均被屏蔽.A) NameB) CaptionC) EnabledD) Visible答案 C406 下列选项中不正确的是().A) 每个菜单项都是一个对象,所以也有属性和事件.B) 菜单项的属性不可以在属性窗口中设计.C) 每个菜单项都只有一个Click事件.D) 菜单编辑器中,标题可不输入,而名称必须输入答案 B407 Visual Basic 6.0中任何控件都有的属性是().A) BackColorB) CaptionC) NameD) BorderStyle答案 C408 假定有一个菜单,名为MenuItem,为了运行时使该菜单项失效,应使用的语句为().A) MenuItem.Enabled = TrueB) MenuItem.Enabled = FalseC) MenuItem.Visible = TrueD) MenuItem.Visible = False答案 B409 在修改列表框内容时,AddItem方法的作用是().A) 清除列表框中的全部内容B) 删除列表中指定的内容C) 在列表框中添加一个项目D) 在列表框中插入一行文本答案 C410 如果在窗体上已经创建了一个文本框对象Text1,可以通过()事件获得输入键值的ASCII码.A) ChangeB) LostFocusC) KeyPressD) GotFocus答案 C411 下列控件中,没有Caption属性的是().A) 框架B) 列表框C) 复选框D) 单选按钮答案 B412 复选框的Value属性为1时,表示().A) 复选框未被选中B) 复选框被选中C) 复选框内有灰色的勾D) 复选框操作错误答案 B413 在下列说法中,正确的是().A) 通过适当的设置,可以在程序运行期间让定时器显示在窗体上B) 在列表框中不能进行多项选择C) 容器内不能有容器对象D) 框架也有Click和DblClick事件答案 D414 在用菜单编辑器设计菜单时,必须输入的项有().A) 快捷键B) 标题C) 索引D) 名称答案 D415 当用户按下并且释放一个键后会触发KeyPress、KeyUp和KeyDown事件,这三个事件发生的顺序是().A) KeyPress、KeyDown 、KeyUpB) KeyDown、KeyUp、KeyPressC) KeyDown、KeyPress、KeyUpD) 没有规律答案 C416 定时器的Interval属性以()为单位指定Timer事件之间的时间间隔.A) 分B) 秒C) 毫秒D) 微秒答案 C417 将通用对话框CommandDialog1的类型设置成另存为对话框,可调用该控件的()方法.A) ShowOpenB) ShowSaveC) ShowColorD) ShowFont答案 B418 要在图片框P1中打印字符串"HowAreYou",应使用语句().A) Picture1.Print="HowAreYou"B) P1.Picture=LoadPicture("HowAreYou")C) P1.Print "HowAreYou"D) Print "HowAreYou"答案 C419 设组合框Combo1中有3个项目,则以下能删除最后一项的语句是().A) Combo1.RemoveItem TextB) Combo1.RemoveItem 2C) Combo1.RemoveItem 3D) Combo1.RemoveItem Combo1.Listcount答案 B420 下列方法中可用于列表框动态添加数据的是().A) addB) additemC) addlistD) removeitem答案 B421 将CommonDialog通用对话框的类型设置为字体对话框,可设置该控件的()属性.A) FontB) FilterC) flagsD) Action答案 D422 清除列表框的所有选项应选择下列哪种方法().A) ClearB) ClsC) ClearItemD) RemoveItem答案 A423 RGB 函数通过红.绿.蓝三基色混合产生某种颜色,其语法为RGB (红.绿.蓝),括号中红、绿、蓝三基色的成分使用0~255之间的整数.若使用三个滚动条分别输入三种基色,为保证输入数值有效,则应设置()属性.A) Max和MinB) Smallchange和 LargeChangeC) Scroll和ChangeD) Value答案 A424 列表框控件中的列表内容是通过()属性设置的.A) NameB) CaptionC) ListD) Text答案 C425 ()对象不能作为控件的容器.A) FormB) PictureBoxC) ShapeD) Frame答案 C426 程序运行后,在窗体上单击鼠标,此时窗体不会接收到的事件是().A) MouseDownB) MouseUpC) LoadD) Click答案 C427 下列不能用commondialog 控件调用的对话框是().A) open/saveB) helpC) fontD) search答案 D428 计时器的interval属性为0时,表示().A) 计时器失效B) 相隔0秒C) 相隔0 毫秒D) 计时器的enable属性为false答案 A429 如果在图片框上使用绘图方法绘制一个实心圆,则图片框的()属性决定了该圆的颜色.A) BackColorB) ForeColorC) FillColorD) DrawStyle答案 C430 单击滚动条的滚动箭头时,产生的事件是().A) ClickB) ScrollC) ChangeD) Move答案 C431 简单组合框的style值为().A) 0B) 1C) 2D) 3答案 B432 不能通过()来删除列表框中的选项.A) List属性B) Removeltem方法C) Clear方法D) Test属性答案 D433 激活主菜单的按键是().A) F1或Ctrl键B) Ctrl键或Atl键C) F10或Ctrl键D) F10或Atl键答案 B434 图像框(Image)的何项属性设置为true时,可使图形自动调整大小,填满整个图像框().A) WidthB) PictureC) NameD) Stretch答案 D435 任何控件都具有的属性是().A) TEXTB) CAPTIONC) NAMED) FORECOLOR答案 C436 为使文本框显示滚动条,必须首先设置的属性是().A) MulitilineB) AutosizeC) AlignmentD) Scrollbars答案 A437 设置列表框选中的文本用()属性.A) selectedB) captionC) textD) list答案 D438 将通用对话框类型,设置为字体对话框,可修改该控件的()属性.A) fontB) filenameC) filterD) action答案 D439 如果没有在列表框中选择项目,且列表框的MultiSelect属性值为默认值(0~None),则执行语名List1.RemoveItemList1.ListIndex的结果是().A) 删除列表框的最后一项B) 删除列表框的第一项C) 出错D) 删除列表框中的最后添加的一项答案 C440 要判断"命令按钮"是否被鼠标单击,应在"命令按钮"的事件中判断.A) ChangB) KeyDownC) ClickD) KeyPress答案 C441 文本框(Text1)中有选定的文本,执行 Text1.SelText="Hello"的结果是___.A) "Hello"将替换掉原来选定的文本B) "Hello"将插入到原来选定的文本之前C) Text1.SelLength为5D) 文本框中只有"Hello"答案 A442 框架内的所有控件是___.A) 随框架一起移动、显示、消失和屏蔽B) 不随框架一起移动、显示、消失和屏蔽C) 仅随框架一起移动仅随框架一起显示和消失D)答案 A443 下列不能打开菜单编辑器的操作是___ ___.A) 按Ctrl+EB) 单击工具栏中的"菜单编辑器"按钮C) 执行"工具"菜单中的"菜单编辑器"命令D) 按Shift + Alt + M答案 D444 Clear方法适用于() 控件.A) 图片框B) 窗体C) 复选框D) 组合框答案 D445 Cls方法可清除窗体或图片框中的信息是 .A) Picture属性设置的背景图案B) 在设计时放置的控件C) 程序运行时产生的图形和文字D) 以上方法都对答案 C446 在窗体上画一个名称为Timer1的计时器控件,要求每隔0.1秒发生一次计时器事件,则以下正确的属性设置语句是A) Timer1. Enabled =0.1B) Timer1.Interval =0.1C) Timer1. Enabled=100D) Timer1.Interval=100答案 D447 在窗体上画一个名称为Label1的标签,然后画一个名称为HScroll1的滚动条,其Min和Max属性分别为0和100.程序运行后,如果移动滚动框,则在标签中显示滚动条的当前值.以下能实现上述操作的程序段是A) Private Sub HScroll_Change()Label1.Caption=HScroll1.ValueEnd SubB) Private Sub HScroll_Click()Label1.Caption =HScroll1.ValueEnd SubC) Private Sub HScroll_Change()Label1.Text=HScroll.CaptionEnd SubD) Private Sub HScroll_Click()Label1. Text =HScroll.CaptionEnd Sub答案 A448 以下叙述中错误的是A) 在KeyPress事件过程中能识别键盘的按下与释放B) 在KeyPress事件过程中可以通过KeyAscii值来识别回车键C) 在KeyDown和KeyUp事件过程中,将键盘输入的"A"和"a"视作相同的字母D) 在KeyPress事件过程中, 将键盘输入的"A"和"a"视作不同的字母答案 A449 若有一菜单项(名为MenuItem),为了在运行时使该菜单项失效(变灰),应使用的语句是A) MenuItem.Enabled = TrueB) MenuItem.Visible = FalseC) MenuItem.Checked = TrueD) MenuItem.Enabled = False答案 D450 标准工具箱中的控件().A) 数目是固定不变的B) 数目可以增加或减少C) 包含了VisualBasic所有控件D) 在窗体建立对象时不一定被使用答案 B451 单击滚动条两端的任一个滚动箭头,将触发该滚动条的()事件.A) ScrollB) KeyDownC) ChangeD) Dragover答案 C452 下列对象中没有焦点属性的是().A) 命令按钮控件B) 窗口控件C) 文本框控件D) 单选框控件答案 B453 为了用键盘打开菜单和执行菜单命令,第一步应按的键是().A) 功能键F10或AltB) Shift+功能键F4C) Ctrl或功能键F8D) Ctrl+Alt答案 A454 用标准工具栏中的工具按钮不能执行的操作是().A) 添加工程B) 打印源程序C) 运行程序D) 打开工程答案 B455 下列操作中不能向工程中添加窗体的是().A) 执行"工程"菜单中的"添加窗体"命令B) 单击工具栏上的"添加窗体"按钮C) 右击窗体,在弹出菜单中选择"添加窗体"命令D) 右击工程资源管理器,在弹出菜单中选择"添加"命令,然后在下一级菜单中选择"添加窗体"命令答案 C456 当一个工程含有多个窗体时,其中的启动窗体是().A) 启动 Visual Basic 时建立的窗体B) 第一个添加的窗体C) 最后一个添加的窗体D) 在"工程属性"对话框中指定的窗体答案 D457 语句listl.removeitem 1 将删除list.listindext等于()的项目..A) 0B) 2C) 3D) 1答案 D458 若要清除列表框的所有内容,可用什么方法实现A) RemoveItemB) ClsC) ClearD) 以上均不可以答案 C459 要使时钟控件Timer1的Timer事件不起作用,以下正确的语句是A) Timer1.Visible=FalseB) Timer1.Enabled=FalseC) Timer1.Interval=1000D) Timer1.Index=0答案 B460 要获得用户在组合框输入的内容,应利用的组合框的属性是A) ListB) SelectedC) ListIndexD) Text答案 D461 将数据项"China"添加到列表框(List1)中成为第一项应使用的语句是()。