2016-03-20 25 views
0

入力ボックスに文字を入力するか、入力ボックスを空白のままにすると、プログラムがクラッシュします。なぜ私の妥当性検査は動作しないのですか?入力ボックスvb 2013入力ボックスの文字列変換エラー

Option Strict On 
Public Class frmPickUpSticks 
Dim playersTurn As Boolean = False 
Dim remainingSticks As Integer 'count sticks 
Dim losses As Integer = 0 'count player losses 
Private Sub btnNewGame_Click(sender As Object, e As EventArgs) Handles btnNewGame.Click 
    lblOutput.Text = "" 
    remainingSticks = CInt(InputBox("How many matchsticks would you like (5 - 25)?", "Pick Number of Matches!")) 
    'Validate input 
    If IsNumeric(remainingSticks) Then 
     If (remainingSticks >= 5) And (remainingSticks <= 25) Then 
      DisplayMatches() 
      If (remainingSticks Mod 4 = 1) Then 
       MessageBox.Show("You go first!") 
       playersTurn = True 
       turns() 
      Else 
       MessageBox.Show("I go first.") 
       turns() 
      End If 
     Else 
     MessageBox.Show("Please enter a number between 5 and 25.") 
    End If 
Else 
    MessageBox.Show("Input must be numeric.", "Input Error") 
End If 

答えて

0

あなたは自動的にInputBox関数のどのユーザータイプを取り、入力のための数を見込んで任意の関数やメソッドにこの入力を渡すことはできません。 InputBoxメソッドは文字列を返すように設計されており、この文字列を変換する必要がありますが、文字列を解析する方法を知っているメソッドを使用する必要があります。さもなければ、数値以外の値(CInt)を扱うように設計されていないメソッドは例外を引き起こします。

代わりに、何らかの解析を試みる必要があります。NETライブラリには、多くのツールが用意されています。あなたのケースで正しいものはInt32.TryParse

Dim remainingSticks As Integer 
Dim userInput = InputBox("How many matchsticks .....") 
If Int32.TryParse(userInput, remainingSticks) Then 
    .... ok your remainingStick contains the converted value 
Else 
    MessageBox.Show("You should type a valid integer number between 5-25") 

あるInt32.TryParseは、あなたの入力文字列を見て、有効な整数値に変換しようとします。成功した場合、2番目のパラメータは変換された整数を含み、Trueを返します。失敗した場合はfalseを返し、2番目のパラメータはデフォルト値の0を返します。もちろん

整数へのsuccesfullの変換後、あなたは=もうあなたは

が文字列

STとSTを暗くInputBox関数で文字列変数を使用する必要がありますIsNumeric関数

+0

ありがとうございました!それはうまくいった! – Trapper100

+0

助けになるのはうれしいです。サイトの新しいユーザーであることは、[回答の受け取り方法はどうすればよいですか](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) – Steve

0

でチェックする必要はありませんInputBox関数( "あなたは希望どのように多くのマッチ棒(5から25)?"、 "一致数を選んで!"))

remainingSticks =ヴァル(ST)

。 。 。

+0

「Val'数値が大きすぎてIntegerに変換できない場合は例外がスローされます。さらに、2016年頃にはまだVB6の互換機能をすべて忘れてしまいます。 – Steve

+0

lol @vb6互換性は忘れてしまいます。 。 。私は自分自身を助けることができない、私はPOWERBASIC時代、 –

関連する問題