对于我的班级,我应该创建一个程序,使用用户输入的变量计算和打印多维数据集的音量。它必须要求用户定义所有变量。它还必须通过使用Try,catch和finally关键字来预测来自用户的错误。因此,如果用户输入的内容不正确,则会显示错误消息。
我正在尝试编译该程序,但它没有这样做。我已经抓住了#34; dividebyzero异常和溢出激活。如果有人可以帮助我并告诉我我的代码有什么问题,我将不胜感激。
'This program will calculate and print the volume of a cube using variables inputted by the user
Sub Main()
Console.WriteLine("Cube Volume Finder, Input side length")
Try
Dim X As Integer = Console.ReadLine()
Dim inttemp As Integer
inttemp = X / 0
Catch ex As DivideByZeroException
Console.WriteLine("Divide by zero exception has occured")
Finally
System.Console.WriteLine(intTemp)
End Try
Try
Dim X As Integer = Console.ReadLine()
Dim Y As Integer
Y = X ^ 3
Catch Z As OverflowException
System.Console.WriteLine("A overflow exception has occured")
Finally
System.Console.WriteLine(Y)
End Try
Console.WriteLine("Press any key to exit the program")
Console.ReadKey()
End Sub
End Module
提前致谢
答案 0 :(得分:1)
在该块外部看不到在If / Try / For / While等...块中声明的变量。所以你的变量intTemp和Y被声明,但就像你的代码离开try块一样,它们就会消失。您应该在块
之前移动声明说,第一个try / catch块似乎没用。您是否正在尝试除以零的异常?
Sub Main()
Console.WriteLine("Cube Volume Finder, Input side length")
' Commented out, this is not needed to calculate the volume of a cube
' Dim inttemp As Integer
' Try
' Dim X As Integer = Console.ReadLine()
' 'inttemp = X / 0
' Catch ex As DivideByZeroException
' Console.WriteLine("Divide by zero exception has occured")
' Finally
' System.Console.WriteLine(intTemp)
' End Try
Dim Y As Integer
Try
Dim X As Integer = Console.ReadLine()
Y = X ^ 3
Catch Z As OverflowException
System.Console.WriteLine("A overflow exception has occured")
Finally
System.Console.WriteLine(Y)
End Try
Console.WriteLine("Press any key to exit the program")
Console.ReadLine()
End Sub
请记住,您的代码存在严重问题。您的项目使用Option Strict Off编译。这允许从字符串到整数的自动转换。但这是非常危险的,应该避免 您应该始终检查用户输入的类型和值是否正确
Dim userInput As String = Console.ReadLine()
Dim X As Integer
If Int32.TryParse(userInput, X) Then
Y = X ^ 3
Else
Console.WriteLine("Invalid number!")
End If