开发者

Run time error in vb.net , want to avoid a number in the list

开发者 https://www.devze.com 2023-02-28 03:31 出处:网络
Imports System Public Class Test Public Shared Sub Main() Dim n As Integer n = Console.ReadLine Do While n <> 42
Imports System

Public Class Test
   Public Shared Sub Main() 
       Dim n As Integer
       n = Console.ReadLine
       Do While n <> 42
           System开发者_如何学Go.Console.WriteLine(n)
           n = Console.ReadLine
       Loop
   End Sub
End Class

I am getting a run time error for this code. How can I change it. and how to limit the loop to print number from 1 to 42 and not 5 in the list ?


I think the easiest solution to the runtime crash is to treat 'n' as a String and not an Integer.

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

The runtime error will occur when the inputed value cannot be converted into an Integer with your original code. Conversely, you could use something else, like TryParse() to handle the case where the conversion fails.

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

The above code will work, but any input value that fails to convert to an integer will still be written to the console. IE if you input 'A', it will output '0'. If you only want to print inputed numbers that are numeric and also not equal to 42 you'd need to change the above. TryParse() does return a boolean value indicating if the parse was successful.

I hope that helps, I don't fully understand what you meant with '5' in your question. Can you clarify?


You could validate the input is an integer before writing it to the console and reject other input.

  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
0

精彩评论

暂无评论...
验证码 换一张
取 消