Question Get user-input variables to match set values (no matter the order they are entered)

Mynotoar

Active member
Joined
Sep 27, 2012
Messages
28
Location
England
Programming Experience
Beginner
Hey! I should start with a clarification: I'm new to the forums, and I'm also very new to VB. I started studying it at A-level Computing nearly three weeks ago. So please bear in mind that I'm nowhere near an expert and may need simple explanations :). Also, I'm working with a console application, and not a... whatever the other thing is called!

So what I'm trying to do is to create a quiz where you can answer the questions in any order. Say I have a five-question quiz. First I declare five values that are constants, they're the answers, and they're what'll be referred to. So I'll call them "red", "orange", "green", "blue" and "black". The program I want to write would then have you enter at least five variables, one at a time. If the variable matches the constant, so you type in "orange" (we'll assume everything is forced to lowercase so there are no case problems,) then it determines whether "orange" matches any of the five constants. If it does, it tallies up a value called "score" which would be totalled once you've filled all five answer slots or something like that.

If it was in order, I'd understand how to do it just fine. Here's what my code would look like - so you get an idea of the things I know, too.

VB.NET:
Module Module1

    Sub Main()
        Dim variable1, variable2, variable3, variable4, variable5 As String
        Dim constant1, constant2, constant3, constant4, constant5 As String
        Dim score As Integer
        constant1 = "red"
        constant2 = "orange"
        constant3 = "green"
        constant4 = "blue"
        constant5 = "black"
        score = 0
        'I'm just clearing it in case I want to include a Do loop later.


        Console.WriteLine("Enter a colour that starts with r.")
        variable1 = Console.ReadLine
        If LCase(variable1) = constant1 Then
            score = score + 1
            'The answer is correct, the score is now 1.
        Else
            score = score
        End If
        Console.WriteLine("Enter a colour that starts with o.")
        variable2 = Console.ReadLine
        If LCase(variable2) = constant2 Then
            score = score + 1
        Else
            score = score
        End If
        Console.WriteLine("Enter a colour that starts with g.")
        variable3 = Console.ReadLine
        If LCase(variable3) = constant3 Then
            score = score + 1
        Else
            score = score
        End If
        Console.WriteLine("Enter a colour that starts with b.")
        variable4 = Console.ReadLine
        If LCase(variable4) = constant4 Then
            score = score + 1
        Else
            score = score
        End If
        Console.WriteLine("Enter a colour that starts with b.")
        variable5 = Console.ReadLine
        If LCase(variable5) = constant5 Then
            score = score + 1
        Else
            score = score
        End If
        Console.WriteLine("You got " & score & "/5.")
        Console.ReadLine()
    End Sub


End Module

So this is just asking you to enter the variable, checking the variable (forced into lowercase) matches the constant, and if it does then the "score" value goes up, and is tallied at the end.

That's fine. But how on Earth could I do it out of order? In my head, I'm thinking that I'd have to say for every line that you input something like "Does it match constant1, does it match constant2, does it match constant3..." etc., and that would be tedious if I were doing 118 questions instead of 5. Is there a more efficient way? And if there isn't, how do I do it the first way, because I can't work that out either? I tried using "or" to say "If variable1 = constant1 OR constant2 OR constant3" but that doesn't work, it thinks I'm trying to convert the variable type or something silly.

Can anyone offer any help/advice? Input would be greatly and warmly appreciated :) <3.
 
Hi,

This is quite easy to fix but on the basis that you only started VB 3 weeks ago I do not want to start confusing you with techniques that you may not have touched on yet.

Suffice to say that what you need to do is hold your answers in some sort of container say a List(Of String) and then create and call a Function passing the entered data as a parameter which then iterates through the list, using some form of loop, checking for the entry of a correct answer which then returns either 0 or 1 depending on whether a correct entry was made. This value can then be added to your score.

In summary, what you need to study is:-

1) Containers, i.e. List, Dictionary, Hash Table etc.
2) Functions - How to create, pass parameters, return values, call functions etc

Notes on your code:-

1) Score = 0 after your declarations - This is not necessary since all defined integers default to zero unless otherwise specified.

2) score = score - (You use this in your else statement after each question test) - This is totally unnecessary since what is the point of setting a variable to itself? It's like saying 1=1 or 2=2 etc. To that end, your else statement is therefore also totally unnecessary.

3) score = score + 1 - a shorthand way to accomplish this in VB.NET is score += 1

4) Sorry, but I do not know what you mean by "Bumping"?

5) You mentioned that you tried If variable1 = constant1 OR constant2 OR constant3 and it failed due to type conversion. This is because you are actually doing a bitwise comparison in your statement being "constant1 OR constant2 OR constant3". What you should have said is "If variable1 = constant1 or variable1 = constant2 or variable1 = constant3 etc"

Good luck,

Cheers,

Ian
 
Last edited:
Ian, you're wonderful, that's just what I was looking for! On your code notes: I'm aware that it's not necessary to set score to 0, but as I commented in the code, I did it just in case I ever wanted to put a Do loop in the system, so it would reset the score every time the program restarts. Thank you very much for the += shorthand, too! And you're right to point out that the score=score is redundant, I think I put it there because I wanted nothing to happen but wasn't sure if you could leave an Else blank - seems a bit silly now that I think about it.

Bumping is the forum term for making a post without necessarily any useful content (often just the word "Bump") so that it will appear at the top of the forums, but this is mostly when a thread disappears over the next page, as mine did - so I was a little cheeky and posted the bump question to get it back to the top.

Also, thank you very much for explaining the type conversion error! That had me wondering.

All in all, you've been really helpful, and I really appreciate it, but I've one more question for you, if you're still here: where's the best place online aside from these fora to get VB console help? Every time I look I usually encounter something designed for the broader type of VB - I even came across a webpage that says VB doesn't work in console applications! In any case, I'm having a hard time finding a decent source of information on VB and would be welcome to any suggestions for online information!

Thanking you muchly :).

Leo
 
Hi Leo,

Re: "Bumping", well you learn something new every day - that's a new one on me so I will take your word for it.

Re: Console Programming, I have done very little console programming myself since I have predominantly been in the forms environment but what you must remember is that many, many (being 90%) of the principals that you learn in the forms environment will also apply to the console environment.

To that end, I will have a look round the net myself and see if I can find anything useful specific to console programming.

Cheers,

Ian
 
Hi Leo,

Had a quick look on the net now and what I see is that nearly every reference to VB.NET console programming assumes a proficient level of VB.NET knowledge and therefore only focus on demonstrating the console elements that make a console program work.

I would therefore suggest that you need to start your VB.NET development with a good book that focuses on teaching you the programming techniques that you can use in VB.NET to create programs. Only then will you be able to take the knowledge that you have gained in this study and apply it to console programming.

Have a look at this as a staring reference:-

Mastering Microsoft Visual Basic 2010: Amazon.co.uk: Evangelos Petroutsos: Books

Good luck,

Cheers,

Ian
 
If you check lower down on the main vbdotnetforums, you will find a Console subforum right under the VB.NET listing. Look for it.
I teach Visual Basic using mostly Console applications. This is simply a quick and easy way to learn the basic structure and logic of the language without the distractions of a GUI (Graphical User Interface). I create my own demos and samples for my students to introduce each new concept, first using Console apps, and then follow up with samples using Windows Forms apps.

Regarding your own project, it will be a lot easier to create after you have learned to use Select Case (instead of multiple If Thens), arrays, subprocedures & functions, string methods, and random. So far, you seem to have done a lot after only 3 weeks. Good luck, and don't forget to check out the Console subforum. I may be able to help you out if you need any hints regarding the text-based Console syntax. You can even use commands to change the colors, etc. and make the interface look really cool.

Note: Instead of using the legacy LCase function, it is preferable to use the newer .NET method ToLower. This will make it easier to transition to another .NET language (such as C#) if you want to do so later.
For example, instead of:
If LCase(variable1) = constant1 Then
use:
If variable1.ToLower() = constant1 Then

PS: Which textbook are you using?
 
Last edited:
Ian - thank you again! Yes, I agree, the information out there isn't very helpful - that's why I joined this forum.

Solitaire - Thank you, but we aren't using any textbooks right now - at least, we aren't referring to them for VB. I'll have a look at the subforum :).

Oh wait, I'm already in the Console subforum :p. I don't suppose you'd know of any good other online resources for VB consoles, just so I don't have to ask someone every time? :p. When I say online resources I'm banking on free ones, but if I can pick up something cheap I may be persuaded ;).
 
Console Class (System) Each member has a separate help page that you can click into. Be sure to browse down to Remarks section also.
 
Thank you once again, everyone. Also, I found some help with the List(of string) function and someone showed me how to use the list and then read from it with an if statement. I'm a little closer to my end-goal of creating a quiz on the Periodic Table of Elements. I hate to ask for help again when you've all been so helpful already, but if anyone could give me a push in the right direction as to the next step, I would appreciate it greatly.

So I've set up a code using the List variable that declares 16 elements, and asks you to input three elements and then it will tell you if you got them right. It all works fine, except that I could put in "iron" three times and get a score of three. It allows repeat entries. Is there any way to set it up so that every time the program matches up one of the variables from an answer given, it could be struck from the list so that it couldn't be used again? Or some way of determining if an answer given matches a previously given answer, so as to stop a point from being added?

VB.NET:
Module Module1

    Sub Main()
        Dim elements As New List(Of String)
        Dim answer As String
        Dim score As Integer
        With elements
            .Add("ruthenium")
            .Add("lutetium")
            .Add("rutherfordium")
            .Add("ytterbium")
            .Add("calcium")
            .Add("iron")
            .Add("sulphur")
            .Add("oxygen")
            .Add("carbon")
            .Add("argon")
            .Add("krypton")
            .Add("xenon")
            .Add("neon")
            .Add("lanthanum")
            .Add("actinium")
            .Add("aluminium")
        End With


        Console.WriteLine("Enter an element from the Periodic Table.")
        answer = Console.ReadLine
        If elements.Contains(answer.ToLower()) Then
            Console.WriteLine("Correct.")
            score += 1
        Else
            Console.WriteLine("Incorrect.")
        End If
        answer = Console.ReadLine
        If elements.Contains(answer.ToLower()) Then
            Console.WriteLine("Correct.")
            score += 1
        Else
            Console.WriteLine("Incorrect.")
        End If
        answer = Console.ReadLine
        If elements.Contains(answer.ToLower()) Then
            Console.WriteLine("Correct.")
            score += 1
        Else
            Console.WriteLine("Incorrect.")
        End If
        Console.WriteLine("Your score is " & score)
        Console.ReadLine()
    End Sub


End Module

Oh, and as you can see I used the ToLower() function you suggested, and the += to add to the score variable :).
 
Hi again Leo,

Your getting there. To answer your follow up question, consider what's in the list before you find a correct answer. When you find a correct answer what could you do to the list to ensure you don't match again? In other words, what's the opposite of add?

Cheers,

Ian
 
I've done it!

Hey guys! I've finished my project - I've made a program that does just what I want it to do! After entering your name, you begin a quiz that tests your knowledge of the periodic table - you enter as many elements of the periodic table as you can think of, and then type 'f' and press enter to finish, then it gives you your score, based on how many answers you gave. The answer section is an If... then... in a Do loop that only completes when you type f and press enter - and the whole thing is in another Do loop so you can play it again.

I'm really happy with it, and I'll show you the code: (more below)

VB.NET:
Module Module1

    Sub Main()

        Dim elements As New List(Of String)
        With elements
            .Add("actinium")
            .Add("aluminium")
            .Add("americium")
            .Add("antimony")
            .Add("argon")
            .Add("arsenic")
            .Add("astatine")
            .Add("barium")
            .Add("berkelium")
            .Add("beryllium")
            .Add("bismuth")
            .Add("bohrium")
            .Add("boron")
            .Add("bromine")
            .Add("cadmium")
            .Add("calcium")
            .Add("californium")
            .Add("carbon")
            .Add("cerium")
            .Add("caesium")
            .Add("chlorine")
            .Add("chromium")
            .Add("cobalt")
            .Add("copernicium")
            .Add("copper")
            .Add("curium")
            .Add("darmstadtium")
            .Add("dubnium")
            .Add("dysprosium")
            .Add("einsteinium")
            .Add("erbium")
            .Add("europium")
            .Add("fermium")
            .Add("flerovium")
            .Add("fluorine")
            .Add("francium")
            .Add("gadolinium")
            .Add("gallium")
            .Add("germanium")
            .Add("gold")
            .Add("hafnium")
            .Add("hassium")
            .Add("helium")
            .Add("holmium")
            .Add("hydrogen")
            .Add("indium")
            .Add("iodine")
            .Add("iridium")
            .Add("iron")
            .Add("krypton")
            .Add("lanthanum")
            .Add("lawrencium")
            .Add("lead")
            .Add("lithium")
            .Add("livermorium")
            .Add("lutetium")
            .Add("magnesium")
            .Add("manganese")
            .Add("meitnerium")
            .Add("mendelevium")
            .Add("mercury")
            .Add("molybdenum")
            .Add("neodymium")
            .Add("neon")
            .Add("neptunium")
            .Add("nickel")
            .Add("niobium")
            .Add("nitrogen")
            .Add("nobelium")
            .Add("osmium")
            .Add("oxygen")
            .Add("palladium")
            .Add("phosphorous")
            .Add("platinum")
            .Add("plutonium")
            .Add("polonium")
            .Add("potassium")
            .Add("praseodymium")
            .Add("promethium")
            .Add("protactinium")
            .Add("radium")
            .Add("radon")
            .Add("rhenium")
            .Add("rhodium")
            .Add("roentgenium")
            .Add("rubidium")
            .Add("ruthenium")
            .Add("rutherfordium")
            .Add("samarium")
            .Add("scandium")
            .Add("seaborgium")
            .Add("selenium")
            .Add("silicon")
            .Add("silver")
            .Add("sodium")
            .Add("strontium")
            .Add("sulfur")
            .Add("tantalum")
            .Add("technetium")
            .Add("tellurium")
            .Add("terbium")
            .Add("thallium")
            .Add("thorium")
            .Add("thulium")
            .Add("tin")
            .Add("titanium")
            .Add("tungsten")
            .Add("ununtrium")
            .Add("ununpentium")
            .Add("ununseptium")
            .Add("ununoctium")
            .Add("uranium")
            .Add("vanadium")
            .Add("xenon")
            .Add("ytterbium")
            .Add("yttrium")
            .Add("zinc")
            .Add("zirconium")
        End With
        Dim wronganswerlist As New List(Of String)
        Dim answer, name, endgame As String
        Dim score, total, percentage As Integer
        Dim quit As Boolean = True
        Dim finish As Boolean = True
        Do
            score = 0 : total = 0 : percentage = 0
            Console.Clear()
            Console.ForegroundColor = ConsoleColor.Cyan
            Console.WriteLine("Periodic Table Quiz")
            Console.ForegroundColor = ConsoleColor.White
            Console.WriteLine("Hello! What is your name?")
            name = Console.ReadLine
            Console.WriteLine()
            Console.WriteLine("Welcome, " & name & "! This is a quiz about the Periodic Table of Elements.")
            Console.WriteLine()
            Console.ForegroundColor = ConsoleColor.Cyan
            Console.WriteLine("Instructions:")
            Console.ForegroundColor = ConsoleColor.White
            Console.WriteLine("  1. Type in as many elements from the Periodic Table as you can.")
            Console.WriteLine("  2. Press enter once after each element you guess.")
            Console.WriteLine("  3. Please spell accurately and according to British conventions.")
            Console.WriteLine("  Answers are not case-sensitive.")
            Console.WriteLine("  4. Use full names, not symbols or atomic numbers.")
            Console.WriteLine("  5. When you wish to stop, type 'f' and then press enter to display your score.")
            Console.WriteLine("  6. Don't lose the game.")
            Console.WriteLine()
            Console.WriteLine("Elements:")
            Do
                answer = Console.ReadLine
                If elements.Contains(answer.ToLower()) Then
                    With elements
                        .Remove(answer)
                    End With
                    score += 1
                    total += 1
                    finish = False
                ElseIf answer = "" Then
                    finish = False
                ElseIf answer = "f" Then
                    finish = True
                Else
                    With wronganswerlist
                        .Add(answer)
                    End With
                    total += 1
                    finish = False
                End If
            Loop Until finish = True
            percentage = (score / total) * 100
            Console.WriteLine()
            Console.WriteLine(name & ", your score is " & score & "/" & total & ", or " & percentage & "%")
            Console.WriteLine()
            Console.WriteLine("Would you like to play again?")
            Console.WriteLine("Type 'q' and press enter to quit.")
            Console.WriteLine("Press any key to restart.")
            endgame = Console.ReadLine
            If endgame = "q" Then
                quit = True
            Else
                quit = False
            End If
        Loop Until quit = True

    End Sub
End Module

But of course, me being me, I have more questions ^^'. I'm having ever so much fun with VB and I want to be writing optimal programs - so if anyone is still around, these aren't high-priority questions, but rather things I'd like to know how to do to polish off this project. Any help, then, would as usual be very highly appreciated :).

Firstly, how do you read and display from a List(of string)? In this code I've declared a list, "wronganswerlist", which doesn't do anything at present. In the If statement, I've set it up so that every time the user inputs a wrong answer that isn't a space or "f", it is added to the list. I want to then be able to display this list of wrong answers at the end so the user knows where they went wrong. I've tried using a .CopyTo in the With tag, but it wants to copy to a "one-dimensional array", and I can't work out how to set that up. When I tried to Dim an array, it didn't work. Is there any good way of reading from Lists?

Secondly, how do I set up a program so that when you press a specific key - not type and press enter as I've been using, which is cumbersome - something happens? For example, if you were to ask the user "Do you want to quit? (y/n)" and have them press y to end the program, and n to trigger a Do loop, how would you go about that? Again, my attempts to do this have been met with poor results.

I'm sorry that I'm asking you guys everything, but I really am struggling to find help anywhere else on the internet! Many thanks to everybody who has been so patient so far :).
 
Display list and press Esc to quit

To answer your questions, here are 2 samples for you to try out and incorporate into your program:

VB.NET:
Module Module1

    Sub Main()
        Dim mylist As New List(Of String)
        With mylist
            .Add("actinium")
            .Add("copper")
            .Add("nickel")
            .Add("silver")
            .Add("uranium")
        End With
        Console.WriteLine("The following answers were wrong:")
        For Each itm As String In mylist
            Console.WriteLine(itm)
        Next itm
        Console.ReadLine()
    End Sub

End Module


VB.NET:
Module Module1

    Sub Main()
        Dim ans As String
        Do
            Console.WriteLine(vbCrLf & "Program goes here")
            Console.WriteLine("Press any key to continue or Esc to quit:  ")
            ans = Console.ReadKey(True).KeyChar
        Loop Until ans = Chr(27)   'This is the Esc key
        Console.WriteLine(vbCrLf & "Ending program now")
        Console.ReadLine()
    End Sub

End Module
 

Latest posts

Back
Top