2011-04-21 60 views
0
Imports System 

Public Class Test 
    Public Shared Sub Main() 
     Dim n As Integer 
     n = Console.ReadLine 
     Do While n <> 42 
      System.Console.WriteLine(n) 
      n = Console.ReadLine 
     Loop 
    End Sub 
End Class 

我得到此代碼的運行時錯誤。我該如何改變它。以及如何限制循環打印數字從1到42而不是列表中的5?在vb.net運行時錯誤,想避免列表中的數字

+0

你能提供你正在得到的錯誤嗎? – 2011-04-21 19:44:41

+0

我想你會在'n = Console.ReadLine'上得到編譯錯誤,因爲'ReadLine'返回字符串' – Andrey 2011-04-21 19:45:46

+0

嘗試'n = CInt(Console.ReadLine)' – 2011-04-21 19:46:54

回答

0

我認爲運行時崩潰的最簡單解決方案是將'n'視爲字符串而不是整數。

Dim s As String 
    s = Console.ReadLine 
    Do While s <> "42" 
     System.Console.WriteLine(s) 
     s = Console.ReadLine 
    Loop 

當輸入值無法用原始代碼轉換爲Integer時,將發生運行時錯誤。相反,你可以使用別的方法,比如TryParse()來處理轉換失敗的情況。

Dim n As Integer 
    Integer.TryParse(Console.ReadLine, n) 
    Do While n <> 42 
     System.Console.WriteLine(n) 
     Integer.TryParse(Console.ReadLine, n) 
    Loop 

上述代碼可以正常工作,但任何輸入值無法轉換爲整數仍然會寫入控制檯。 IE如果輸入'A',它將輸出'0'。如果您只想打印數字且不等於42的輸入數字,則需要更改上述內容。 TryParse()確實返回一個布爾值,指示解析是否成功。

我希望有幫助,我不完全理解你的問題中'5'的含義。你能澄清嗎?

+0

TryParse返回布爾值。 – 2011-04-21 19:52:18

+0

@Bala R - 你100%正確。感謝您糾正我的錯誤。 – 2011-04-21 20:04:25

0

在寫入控制檯並拒絕其他輸入之前,您可以驗證輸入是整數。

Dim n As Integer 
    Dim input As String 
    Do While n <> 42 
    input = Console.ReadLine 
    If Not String.IsNullOrEmpty(input) AndAlso IsNumeric(input) Then 
     n = CInt(input) 
     System.Console.WriteLine(n) 
    Else 
     System.Console.WriteLine("Invalid input.") 
    End If 
    Loop