-1

Fair warning, I'm a complete beginner in this language.

I want to put together a simple quiz using C# that asks for user input for a favorite color, and then puts out a response based on what they type in. Right now I'm just using a bunch of if statements to check the inputs, but that requires me to copy/paste those if statements for every color. Is there a way I can use an array of some sort that'll let me put all the colors and responses together? I know you can use an array for numbers, but I can't figure out if you can do the same for words.

Again, I'm a pretty bare bones beginner, so if this is a stupid question, I apologize.

Sorry, here's my code:

using System;

namespace Whee
{
    class Program
    {
          static void Main(string[] args)
          {
               Console.WriteLine("What is your favorite color?");
               string color = Console.ReadLine();

               if (color == "blue")
               {
                   Console.WriteLine ("You must be a calm person.");
               }
               if else (color == "red")
               { 
                   Console.WriteLine ("You must be a Sith Lord.");
               }

               if (color == "green")
               {
                   Console.WriteLine ("Dolla bills y'all!");
               }
               if (color == "orange")
               {
                   Console.WriteLine ("What is this I don't even");
               }
               else
               {
                   Console.WriteLine ("You fail at colors. Try again.");
               }
      }
}
Yoshi_64
  • 306
  • 2
  • 9
  • There are potentially a couple of ways to go here; can you post some of your existing code? – istrupin May 01 '17 at 21:43
  • 3
    It sounds to me you need to work a bit on your design and understanding the problems you're experiencing in terms of design and implementation for your code. Do you have any other programming experience? Sometimes its best to draw from that and ask "how can I achieve this in X language?" Without knowing what you've tried, this comes of as a "code this for me" kind of question, so I suggest you show what you've implemented first, demonstrate where you are struggling with, and we can help more from there. Share your code and don't be afraid, everyone starts somewhere. – Yoshi_64 May 01 '17 at 21:44
  • I did Java in college like, ten years ago, so while I did have that experience, I don't really remember any of it, and I don't know how I'd do what I want to do in Java. I don't think I went so far with it as to do that kind of code. I'd really just like an indication of what kind of code snippets I can use, and I can google how they work. – Eric Sandler May 01 '17 at 21:51
  • Break out the pencil and paper and start flowcharting this, and if this is going to be a part of a larger construct (eg User preferences) design with that in mind. Eventually you will up with the color and increment command, but implementation can can very from `if...then` to `switch...case` to more abstract such as `User.AddAnotherBluePerson` – Mad Myche May 01 '17 at 21:51
  • So using the structure you have now, you'll always need to map colors to responses in one way or another. To avoid using if/else statements you could use a [dictionary](https://www.dotnetperls.com/dictionary) or a [switch statement](http://stackoverflow.com/a/15046580/7385884) – istrupin May 01 '17 at 21:52
  • This is really just meant to be a simple program for students to learn from. If this is going to be way too complex, I'll shelve it in favor of something simpler (until closer to the end of the year, anyway). That said, this isn't meant to be anything more than just demonstrating how C# works and how they can use it. It's not going to be a game or full-on app or anything (at least, not yet...) – Eric Sandler May 01 '17 at 21:54
  • So the next question I have is "What do you need fixed here?" Is it that you don't like checking a bunch of statements for possible answers? Because there are ways, but that can be more complex depending on what you want to do. Are you hoping to give users a special answer for EVERY color option? Certain ones? Does case sensitivity matter? So the thing here, is it can be broad. To answer one of your question, you can set an Array and save answers in them. Choose from a `String[]` or `Vector` or similar container that can grow over time. – Yoshi_64 May 01 '17 at 21:58
  • Ideally I'd like to have at least certain answers for certain responses, if not every color. I'd love to have it not be case sensitive, yeah, but I know that my students will probably not use caps, because they're lazy typers. And yes, I really would like to avoid having to check a bunch of statements for possible answers. Makes the code look nicer rather than a bunch of copy/pasted if/else statements. – Eric Sandler May 01 '17 at 22:02
  • For `String` comparison, check out this SO post: http://stackoverflow.com/questions/6371150/comparing-two-strings-ignoring-case-in-c-sharp As for how you want to go about this lesson, what exactly are you demonstrating here? I feel the focus shouldn't be making a program just for the sake of "Here's C#" but more for the sake of "Here's how we read the console, perform decision making, store data in an array/container and utilize it for later, etc." You want them to "learn" from it, but I'm not sure what they are supposed to learn personally. – Yoshi_64 May 01 '17 at 22:06

4 Answers4

1

An alternative to the commonly suggested switch statement, would be to place your values inside of a dictionary.

Then, you can search the dictionary for the input value as the Key, and return the Value of that dictionary entry (if it exists). Otherwise, you can output your "You fail at colors. Try again." message.

Dictionary<string, string> colors = new Dictionary<string, string>();
colors.Add("red", "You must be a Sith Lord.");
colors.Add("blue", "You must be a calm person.");
colors.Add("green", "Dolla bills y'all!");
colors.Add("orange", "What is this I don't even");
string color = Console.ReadLine();
string response = null;
colors.TryGetValue(color, out response);
Console.WriteLine(response ?? "You fail at colors. Try again.");

This method could be easier to maintain in the long run, and updates, if this application ever grew in complexity, would not necessarily require a recompilation (which a switch statement would). Instead, it could be pulled from a database, a configuration file, or whatever suited the situation. This source of data could be updated during runtime without having to restart the application.

Chris Thompson
  • 490
  • 5
  • 17
  • I agree with this type of approach (dictionary/hashtable/list/ lookup) IF we are only doing a key-value lookup. if this becomes a part of a larger operation such as incrementing the value within an object or performing some further logic then this would not be the best way to go – Mad Myche May 02 '17 at 14:38
0

As noted in comments you can use a 'switch' statement like this:

    static void Main(string[] args)
    {
        Console.WriteLine("What is your favorite color?");
        string color = Console.ReadLine();
        string response = "";

        switch(color)
        {
            case "blue":
                response = "You must be a calm person.";
                break;
            case "red":
                response = "You must be a Sith Lord.";
                break;
            case "green":
                response = "Dolla bills y'all!";
                break;
            case "orange":
                response = "What is this I don't even";
                break;
            default:
                response = "You fail at colors. Try again.";
                break;
        }
        Console.WriteLine(response);

    }
PhilC
  • 767
  • 3
  • 8
0

One simple solution when you have a slew of if...then and there is only 1 consistent value being checked is to transpose into a switch...case structure"

    string ColorResponse;
    switch (color) {
        case "blue": ColorResponse = "You must be a calm person."; break;
        case "red": ColorResponse = "You must be a Sith Lord."; break;
        case "green": ColorResponse = "Dolla bills y'all!"; break;
        case "orange": ColorResponse = "What is this I don't even"; break;

        // Added this, you can use multiple matches with the same output
        case "fuschia":
        case "chartous": ColorResponse = "Interesting shades."; break;


        // You can add more logic in as well
        case "caramel":
        case "banana":
            if (color == "caramel") { ColorResponse = "I like caramel on sundaes"; }
            else { ColorResponse = "Banana splits are best with 2 cherries"; 
            break;

        // Always end with **default**
        default: ColorResponse = "You fail at colors. Try again."; break;

    }
    Console.WriteLine(ColorResponse);
Mad Myche
  • 1,075
  • 1
  • 7
  • 15
  • I'm taking all these code snippets for later on. I think what I want to do is have the kids use if statements to do it my original, inefficient way, and then show them how to use switch/case to make it more efficient and pretty. Definitely saving the dictionary code for later as well. – Eric Sandler May 02 '17 at 14:25
0

You can also make the game loop over with a sequence of do{}while() as well.

For example:

do
{
    Console.WritLine("What is your favorit color? (Enter QUIT to stop)");
    String color = Console.ReadLine();
    String output = "";
    switch(color)
    {
        case "red":
            output = "You must be a Sith Lord";
            break;
        case "QUIT":
            output = "Good bye, thanks for playing!";
            break;
    }
    Console.WriteLine(output);
}while(!Color.Equals("QUIT"))
Yoshi_64
  • 306
  • 2
  • 9