程式設計基礎:輸入和輸出
計算機程式碼的一個重要部分是允許您的使用者將資料輸入到程式中,例如文字,按鍵,甚至是來自運動感測器遊戲控制器的數 據流。
資料進入程式後,您希望系統輸出響應,這些響應可以採取以下形式:輸出到螢幕:圖形、文字、輸出到聲音裝置、列印 文件或輸出到另一個程式的資料。
對於本單元,您需要熟悉一些輸入和輸出命令。出現在螢幕上的那個小黑框被稱為控制檯。在 VB.NET 中,所有從該控制檯讀寫 的命令都可以從console.命令訪問,讓我們來看看一些命令。
對於 AS 課程,您不太可能需要超出列印到螢幕命令和寫入檔案命令(稍後介紹)之外的內容。在 VB.NET 中,有兩個寫入螢幕命令 您應該熟悉它們。
console.write("Hello") 'writes the word hello to the screen
console.writeline("Hello") 'writes the word Hello to the screen and adds a carriage return (new line)
讓我們看看一個實際例子
console.write("Hello ")
console.write("how ")
console.write("are ")
console.writeline("you?")
console.writeline("I'm fine thank ")
console.write("you.")
這將輸出以下內容
注意writeline和write命令之間的區別。
Python 沒有像 VB.NET 那樣的兩個獨立命令。print命令預設會在每個字串的末尾新增一個新行。這是一個示例
print("This is the first line. This is the second half of the first line.")
print("This is the second line.")
將產生以下輸出
如果要將多個內容輸出到同一行,您必須在print命令中新增end=""。這告訴 Python,不要以換行符 結束,而是以空字串結束。因此,以下示例輸出全部在同一行
print("This output will", end="")
print(" all appear ", end="")
print("on the same line.", end="")
|
擴充套件:VB.NET 中的控制檯方法 我們可以用 console.
應該會出現一些建議。使用 還有一個命令可以輸出一個小的、令人討厭的聲音,您不太可能需要在考試中瞭解它,並且您的老師很可能討厭它。 console.beep() 'plain beep
console.beep(2000,500) 'beep at 2000Hz for 0.5 seconds
在MSDN 網站上了解有關 |
為了使您的程式具有互動性,您需要讓使用者輸入命令,在考試中,這些命令很可能是文字指令或從檔案讀取(稍後介紹)。您可能 在明年看到按鈕和遊戲控制器。在 VB.NET 中,有兩種型別的輸入命令您需要了解。
variable1 = console.readline() 'reads input until user presses enter and stores it in variable1
variable2 = console.read() 'reads one key press/character and stores the ASCII code in variable2. We'll learn more about this later
讓我們看一個快速示例,說明它可能在哪裡使用
dim name as string 'declare a variable called name
console.write("Please insert your name:") ' write "Hello" and the name to the screen
name = console.readline() 'assign the user's input into the variable name
console.writeline("Hello " & name) ' write "Hello" and the name to the screen
還有console.ReadKey()命令可以讀取單個字元。看一個例子
dim urChoice as char 'declare the name
console.writeline("Please select from options 1,2,3 or 4:")
urChoice = console.Readline() 'read the users input into the variable name
console.writeline("You chose : " & urChoice )
在 Python 中,只有一種命令用於從鍵盤讀取使用者輸入,即input。這是一個示例
print("Please enter your name:")
name = input()
print("Hello ", name)
如果您輸入您的姓名為 Alice,將得到以下結果
|
練習:輸入和輸出 以下程式碼輸出什麼 console.writeline("The ")
console.write("Cat")
console.write("sat ")
console.writeline("on ")
console.writeline("the " & "mat")
dim num as integer = 19
console.writeline("The average age ")
console.write("of a combat soldier ")
console.write("in Vietnam was " & num)
答案 console.writeline("My favourite colours:")
console.writeline("Red")
console.writeline("Blue")
對於以下輸入,以下程式碼將是什麼樣子 dim age as string
dim name as integer
console.writeline("Enter your name: ")
age = console.readline()
console.writeline("Enter your age: ")
name = console.readline()
console.writeline("Hello " & name & ". You are " & age & " years old ")
輸入 John |
