Results 1 to 5 of 5

Thread: [2005] Problem With If-else Condition

  1. #1

    Thread Starter
    Addicted Member noam309's Avatar
    Join Date
    Aug 2006
    Posts
    225

    Question [2005] Problem With If-else Condition

    [B]
    HI ,I have this code:
    the user choose item from the list (ex-"Colors") , and pressed button
    the program generate a line from that text file which contains 2 word each like this file:

    RED adom
    Yellow zahov
    white lavan
    Green yarok
    etc..

    (the two words suppose to be with different languages).and displays the first word in textbox1, the user enter a word in textbox2 , and if it's the same as word2 it gives him a point.
    THE CODE:

    VB Code:
    1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    2.         If ListBox1.SelectedIndex() Then
    3. Bk:         If TextBox2.Text = String.Empty Then
    4.                 Dim num As New Random
    5.                 Dim lines As String() = File.ReadAllLines("D:\Words\" & ListBox1.SelectedItem & ".txt", FileEncoding)
    6. nextrnd:        Dim Line As String = lines(Integer.Parse(num.Next(0, UBound(lines) + 1)))
    7.                 Dim Pos As Integer = Line.IndexOf(" ")
    8.                 Dim Spted = Split(Was, ",")
    9.                 If UBound(Spted) >= UBound(lines) + 1 Then
    10.                     Dim RightA = (Label9.Text / (Int(Label9.Text) + Int(Label10.Text)))
    11.                     Dim Grade = (RightA * 100)
    12.                     MsgBox("You Finished this test!" & vbCrLf & "Your Grade is: " & Int(Grade), MsgBoxStyle.Information, "Done!")
    13.                     Exit Sub
    14.                 End If
    15.                 If InStr(Was, "," & Line.Substring(0, Pos)) Then GoTo NextRnd
    16.                 TextBox1.Text = Line.Substring(0, Pos)
    17.                 strAnswer = Line.Substring(Pos + 1, Line.Length - Pos - 1)
    18.             Else
    19.                 If TextBox2.Text = strAnswer Then
    20.                     ''    MessageBox.Show("That is Correct!", "Correct", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
    21.                     Label3.Text = "RIGHT!"
    22.                     Label3.ForeColor = Color.Green
    23.                     Label9.Text += 1
    24.                 Else
    25.                     ''  MessageBox.Show("I am Sorry, that answer is not correct!", "Incorrect", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
    26.                     Label3.Text = "WRONG!"
    27.                     Label3.ForeColor = Color.Red
    28.                     Label10.Text += 1
    29.                 End If
    30.                 Label5.Text = TextBox1.Text
    31.                 Label4.Text = strAnswer
    32.                 Was &= "," & TextBox1.Text
    33.                 TextBox2.Text = String.Empty : GoTo Bk
    34.             End If
    35.  
    36.         End If
    37. END sub

    there are two problems with this code:
    1. if I press on an item (file) in the listbox and it contains 2 words
    (ex-"light colors") , it doesn't generate the words into the textbox.
    2.only one or two cells in the listbox function OK .. but item1 and 2 and even more aren't function.
    PLEASE YOUR HELP ...

  2. #2
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: [2005] Problem With If-else Condition

    A few things.

    1) If ListBox1.SelectedIndex() Then should be If ListBox1.SelectedIndex()>-1 Then

    2) Dim RightA = (Label9.Text / (Int(Label9.Text) + Int(Label10.Text)))
    You really should convert the label9.Text into a numeric type before you do the math. If you had Option Strict on, though it would take more typing, this kind of thing would go away. Also on this line, can you be certain that the two labels in the denominator do not add up to 0? That would be a divide by 0 situation.

    3) If InStr(Was, "," & Line.Substring(0, Pos)) Then GoTo NextRnd
    Let me be the first to express my horror at the use of GoTo. It still exists in this language, but you won't find anybody in this forum who supports its use. Better by far if it had been left out of .NET. Re-writing as a loop would be better. Search this forum on GoTo to find an explanation of why this is bad. Search the VB6 forum if you want to find a more emphatic discussion.

    5) Label9.Text += 1
    Again, you are adding an integer to a string. In this case, you could also be concatenating if the compiler interprets this wrong.

    6) Those GoTos have bent my mind. I would have to really study that code to figure out how those loops work, and whether they are correct. For me, this was a good lesson in why not to use loops. I understand what you are trying to do, but it is far from obvious to me whether or not it is correct.

    7) The major problem appears to be that Pos is giving you trouble. Your code looks for the first blank in the string, which will only work if the string has only one blank. This will not work the same for "light color" as it works for "color". It appears then that you will get different behavior from your first example to your second. I have the feeling that this may be the major source of your error, but those loops are confusing me.
    My usual boring signature: Nothing

  3. #3

    Thread Starter
    Addicted Member noam309's Avatar
    Join Date
    Aug 2006
    Posts
    225

    Exclamation Re: [2005] Problem With If-else Condition

    thanks for your reply ,but I still don't know how to fix it, how can I do these loops you were talking about?! and how should I get over the space problem between the 2 words , I need to fix this code a little , every suggest according to the following actions it suppose to do ,will be good.
    thanks,
    Eyal

  4. #4
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: [2005] Problem With If-else Condition

    The spaces issue is a tough one. Is there ever a case where there might be three words? If there are never more than two, then I could suggest a way around that. Even if there are three, I might be able to suggest a way around it, but it gets increasingly awkward VERY fast.

    Could you post an example of what Line might hold. Perhaps the one with the most words?

    As for the Goto, if you put in a loop control something like:

    <just before the line which you have labeled nextrnd:>
    Dim Flag as boolean=True
    Do


    Then replace these lines:

    VB Code:
    1. If InStr(Was, "," & Line.Substring(0, Pos)) Then GoTo NextRnd
    2.                 TextBox1.Text = Line.Substring(0, Pos)
    3.                 strAnswer = Line.Substring(Pos + 1, Line.Length - Pos - 1)

    with:

    [Highlight=VB]
    'Just added a Not, and killed the GoTo.
    If Not InStr(Was, "," & Line.Substring(0, Pos)) Then
    'If this If is not entered, Flag will remain True, and execution will return to the Do.
    TextBox1.Text = Line.Substring(0, Pos)
    strAnswer = Line.Substring(Pos + 1, Line.Length - Pos - 1)
    Flag=False 'This will cause the Do...While loop to exit.
    End If
    Loop While Flag

    That would get rid of the first GoTo. The second one is not so simple. While you could replace it with a simple Do Loop and another boolean variable to control it, that is not the solution I would choose. In fact, after thinking about it for a minute, I would choose to take everything that is in that first If statement, and put it in a separate Sub(). Then I would call the Sub in the if statement, and call it in place of the second GoTo. This is easy to say, but would be a monster to show as an example, and I really have to run. Does it help?

    The spaces are the bigger issue, however, you can think about the GoTo stuff later.
    My usual boring signature: Nothing

  5. #5
    Frenzied Member <ABX's Avatar
    Join Date
    Jul 2002
    Location
    Canada eh...
    Posts
    1,622

    Re: [2005] Problem With If-else Condition

    That has gotta be one of the most confusing bits of code i've seen.

    1) Name your controls (Listbox1 = WordList, Textbox1 = QuestionWord, TextBox2 = AnswerWord)
    2) Don't hard code file paths
    3) Try and keep your presentation logic separated from your Program logic.

    First, as I understand it, what you are attempting to make is a game/test that reads a list of words from files in a directory. Each line in the file has two words the first word is the word in one language and the second is the word in a different language. You want to quiz the user based on this information randomly.

    You seem to be awarding 100 points for every correct answer.

    (I'm working without Visual Studio here so your results may vary :/)
    VB Code:
    1. Option Strict On
    2. Option Explicit On
    3.  
    4. Public Class Form1
    5.  
    6.     Dim rnd As New System.Random()
    7.  
    8.     Private Const WordFilePath As String = "C:\My Documents\Visual Studio 2005\Projects\Quiz\Quiz\Words"
    9.     Private Const WordFileFormat As String = WordFilePath & "\{0}.txt"
    10.  
    11.     'Contains the List of words
    12.     Dim CurrentWordList As ArrayList
    13.     'Contains the current Question
    14.     Dim CurrentQuestion As Question
    15.     Dim Correct As Integer ' A count of how many correct questions
    16.     Dim Incorrect As Integer ' a count of the incorrect questions
    17.  
    18.     'Simple Structure to contain the question
    19.     Private Structure Question
    20.         Dim Question As String
    21.         Dim Answer As String
    22.  
    23.         Public Shared Function ToQuestion(ByVal Question As String, ByVal Answer As String) As Question
    24.             Dim Q As New Question
    25.             Q.Question = Question
    26.             Q.Answer = Answer
    27.             Return Q
    28.         End Function
    29.  
    30.     End Structure
    31.  
    32.     'Loads the Word file into an ArrayList
    33.    
    34.     Private Function ParseWordList(ByVal WordFile As String) As ArrayList
    35.         Dim Words As New ArrayList
    36.         Dim sr As New System.IO.StreamReader(WordFile)
    37.  
    38.         Do While Not sr.EndOfStream
    39.             Dim value() As String = sr.ReadLine().Split(" "c)
    40.             Words.Add(Question.ToQuestion(value(0), value(1)))
    41.         Loop
    42.  
    43.         Return Words
    44.     End Function
    45.  
    46.     Private Function RandomQuestion(ByRef WordList As ArrayList) As Question
    47.         ' this should be moved to global scope
    48.         'This doesn't need any comments *GRIN*
    49.         'Get a random Index
    50.         Dim RandomIndex As Integer = rnd.Next(0, WordList.Count)
    51.         'Get the Random Question
    52.         Dim result As Question = CType(WordList.Item(RandomIndex), Question)
    53.  
    54.         WordList.RemoveAt(RandomIndex)
    55.  
    56.         Return result
    57.     End Function
    58.  
    59.     Private Function ProcessAnswer(ByRef Question As Question, ByVal Answer As String) As Boolean
    60.         If Question.Answer.ToLower = Answer.ToLower Then
    61.             'Correct
    62.             Correct += 1
    63.             Question = Nothing
    64.             Return True
    65.         Else
    66.             Question = Nothing
    67.             Incorrect += 1
    68.             Return False
    69.         End If
    70.     End Function
    71.  
    72.  
    73.     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    74.         Dim WordLists() As String = System.IO.Directory.GetFiles(WordFilePath, "*.txt")
    75.  
    76.         For Each f As String In WordLists
    77.             Dim fi As New System.IO.FileInfo(f)
    78.             lstWordLists.Items.Add(fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length))
    79.         Next
    80.     End Sub
    81.  
    82.     Private Sub lstWordLists_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstWordLists.SelectedIndexChanged
    83.         ' This allows the user to change the word list.
    84.         If lstWordLists.SelectedIndex() = -1 Then
    85.             'Nothing Selected, bail
    86.             Exit Sub
    87.         End If
    88.  
    89.         Dim strWordFile As String = String.Format(WordFileFormat, lstWordLists.SelectedItem)
    90.  
    91.         If Not System.IO.File.Exists(strWordFile) Then
    92.             'There is something wrong,
    93.             Exit Sub ' Bail
    94.         End If
    95.  
    96.         'Set the Current Word List
    97.         CurrentWordList = ParseWordList(strWordFile)
    98.     End Sub
    99.  
    100.     'The user clicks this button to start or move to the next question
    101.     Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNext.Click
    102.  
    103.         ' If there is no current question, load it.
    104.         If IsNothing(CurrentQuestion.Question) Then
    105.             If Not CurrentWordList.Count = 0 Then
    106.                   'New Question...
    107.                    CurrentQuestion = RandomQuestion(CurrentWordList)
    108.                    TextBox1.Text = CurrentQuestion.Question
    109.             Else
    110.                 MessageBox.Show("Text Complete!")
    111.             End If
    112.         Else
    113.  
    114.             'I'm assuming there should be no case sensitivity (remove the .ToLower's if not)
    115.             If ProcessAnswer(CurrentQuestion, TextBox2.Text) Then
    116.                 'User answered question Correctly
    117.                 MessageBox.Show("Correct")
    118.  
    119.                 Me.Text = String.Format("Correct: {0}, Incorrect: {1}!", Correct, Incorrect)
    120.                 '
    121.                 TextBox2.Text = ""
    122.                 TextBox1.Text = ""
    123.  
    124.             Else
    125.                 Me.Text = String.Format("Correct: {0}, Incorrect: {1}!", Correct, Incorrect)
    126.                 MessageBox.Show("Incorrect")
    127.                 'User Answered Question Wrong
    128.             End If
    129.  
    130.         End If
    131.  
    132.     End Sub
    133.  
    134. End Class

    I'll leave the rest to you but this should give you an idea on how to do it.

    Edit: Added code to enumerate the wordlists within a directory.
    Last edited by <ABX; Aug 22nd, 2006 at 07:17 AM.
    Tips:
    • Google is your friend! Search before posting!
    • Name your thread appropriately... "I Need Help" doesn't cut it!
    • Always post your code!!!! We can't read your mind!!! (well, at least most of us!)
    • Allways Include the Name and Line of the Exception (if one is occuring!)
    • If it is relevant state the version of Visual Studio/.Net Framwork you are using (2002/2003/2005)


    If you think I was helpful, rate my post
    IRC Contact: Rizon/xous ChakraNET/xous Freenode/xous

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width