C# C# Objects Loops and Final Touches Playing the Game

Chris Kopcow
Chris Kopcow
2,190 Points

When asking a player to place towers using the console, is there a more concise way to write this?

In the video, Jeremy asks us to try coding up something that asks players where they'd like to place a tower using the console.

So I paused the video and did so, as you can see in Game.cs of my snapshot: https://w.trhou.se/umbbk0jvz8

I ran it through the compiler, and it worked, which is great. But I couldn't help but think there was a more concise way of writing the same thing. I have the console ask the player about each coordinate individually, so that way I could run int.Parse and construct their tower's map location piece coordinate by coordinate.

Instead, is there a way to just ask the player for both coordinates at once and somehow, say, parse the string "3, 5" as a map location right away?

1 Answer

Steven Parker
Steven Parker
119,881 Points

You can split the input into an array and then parse the elements individually:

              Console.Write("Enter the X,Y coordinates (0 - 7 , 0 - 4): ");
              var entryXY = Console.ReadLine();
              var coords = entryXY.Split(',');
              int towerOneX = int.Parse(coords[0]);
              int towerOneY = int.Parse(coords[1]);
Chris Kopcow
Chris Kopcow
2,190 Points

Oh, I see, that's interesting. Would I have to construct or initialize the coords array somehow prior to this, or does it automatically know there's two items in this array because you're splitting the string into two parts?

Steven Parker
Steven Parker
119,881 Points

The variable only holds a reference to the array created by "Split", so it needs no initialization.

But if you want to be more precise in the declaration, you could use "string[]" instead of "var".

Chris Kopcow
Chris Kopcow
2,190 Points

Oh alright, I see now. Thanks so much!