Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

Chris Kopcow
Chris Kopcow
2,852 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
231,236 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,852 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
231,236 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,852 Points

Oh alright, I see now. Thanks so much!