这是一个后续问题。我需要使用select case将数字转换为vb.net中的单词。我们不允许使用函数,if else,loops,subs和arrays。我所做的是划分每个数字位置(一个,几十个,几百个等)。现在我担心的是当我尝试打印我存储在每个数字位置的声明变量时,它总是给我一个错误消息“由于保护级别而无法访问”。
有人可以给我一个如何存储它们并打印一次的提示吗?由于最大输入是五位数,我不想以“硬编码”的方式进行。
以下是我的代码示例:
text
答案 0 :(得分:0)
您的代码存在许多问题。这似乎有效。我在代码中添加了注释,以便您可以看到有什么不同以及为什么。此外,在函数中使用此代码并使用函数外部的代码分配标签文本将是更好的编程实践。阅读“单一责任”和SOLID编程原则。你走了。
'this in my example just makes sure that all the
'variables are declared. If you have declared them
'outside this code, you should be able to delete them
'They need to be declared outside of the Select..Case
'statements, otherwise they would only be visible inside
'the Select..Case statements
Dim tens, ones As Integer
Dim strTens As String = ""
Dim strOnes As String = ""
Select Case input >= 20 And input <= 99
Case True
'This is a simplified version of your code.
'Math.floor returns a result that is a Double
'type, so strictly speaking you should convert it
'to an integer type
tens = CInt(Math.Floor(input \ 10))
'your original calculation wil result in an
'incorrect result for example if input=22
'32 divided by 10 is 3.2. 3.2 mod 10 will
'be 3.2
'The method below returns the correct result
ones = CInt(Math.Floor(input Mod 10))
Select Case tens
Case 2
strTens = "Twenty "
Case 3
strTens = "Thirty "
End Select
Select Case ones
Case 1
strOnes = "One"
Case 2
strOnes = "Two"
End Select
'Using + to concatenate strings is a bad idea
'because + will attempt to perform and arithmetic
'add operation and if either string is not purely
'digits, I think you will get an "InvalidCastException"
'when you try to run it. Using & indicates your
'intention to concatenate them not add numbers
test = strTens & " " & strOnes
'You didn't specify what to do if the number is outside
'you range of 20-99. This is a poor way of doing that,
'but simple enough for your needs for now
Case Else
MessageBox.Show("Number must be >19 and <100")
test = ""
End Select