【问题标题】:Use of AND operator in VB.Net Case statement在 VB.Net Case 语句中使用 AND 运算符
【发布时间】:2017-10-25 11:31:25
【问题描述】:

我正在用 VB 制作石头、纸、剪刀游戏。我正在寻找一种方法来完成以下工作:

Select Case userInput
       Case = "rock" And computerOutput = "scissors"
                Console.WriteLine("You win! You picked " & userInput & ", and the computer picked " & computerOutput & "! Rock beats Scissors, hit enter to continue...")
                Console.ReadLine()
                userScore = userScore + 1

userInput 和 computerInput 总是石头、纸或剪刀。

但是当我尝试它时,我收到以下错误:

System.InvalidCastException: 'Conversion from string "rock" to type 'Boolean' is not valid.'

我是 VB 新手,所以不太清楚该怎么做。

【问题讨论】:

  • 我们需要查看更多代码才能理解您的问题。
  • 这不是编写 Select Case 语句的方法。你应该看Excel VBA Introduction Part 14 - Select Case Statements
  • 我猜你用的是vb.net?请在Case = "rock" And computerOutput = "scissors"行之前和之后再提供几行代码
  • 我将编辑帖子以添加它

标签: .net vb.net visual-studio


【解决方案1】:

你可以按照这个写SELECT CASE声明:

Select [ Case ] testexpression  
    [ Case expressionlist  
        [ statements ] ]  
    [ Case Else  
        [ elsestatements ] ]  
End Select  

对于您的代码,您可以这样尝试:

Select Case userInput
   Case "rock"
        if computerOutput = "scissors" then
            Console.WriteLine("You win! You picked " & userInput & ", and the computer picked " & computerOutput & "! Rock beats Scissors, hit enter to continue...")
            Console.ReadLine()
            userScore = userScore + 1
        end if

【讨论】:

  • 很高兴听到您的问题得到解决。也请将答案标记为有用(赞成)。
【解决方案2】:

错误代码告诉你一切。您正在将字符串类型转换为布尔类型。而不是这样做,您应该使用 IF 语句根据字符串的结果来做一些事情。例如:

Select Case userInput
Case "rock"
    if computerOutput = "scissors" then
    Console.WriteLine("You win! You picked " & userInput & ", and the 
    computer picked " & computerOutput & "! Rock beats Scissors, hit enter 
    to continue...")
    Console.ReadLine()
    userScore = userScore + 1
    end if

但我看不出是什么导致了这个错误。请发布您的所有代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 2015-05-18
    • 1970-01-01
    • 2021-04-02
    • 2019-05-08
    • 1970-01-01
    • 2012-11-04
    相关资源
    最近更新 更多