简体   繁体   English

C#使用带有二维数组的输入坐标打印“ *”字符

[英]c# printing a “*” char using entered coordinates with 2d array

I have been trying to do a task I recieved a few days earlier. 我一直在尝试做几天前收到的任务。 Basically the task is a console application in C# : 基本上,该任务是C#中的控制台应用程序:

Prompt the user for input of 2 coordinates in untill the word "stop" is entered. 提示用户输入2个坐标,直到输入单词“ stop”。 Once the word "stop" is hit, print a "*"(star char) at each of the input coordinates. 按下单词“ stop”后,在每个输入坐标处打印一个“ *”(星号字符)。 The field where the coordinates are printed is 20x20. 打印坐标的字段为20x20。 I have tried doing this, but to no avail. 我曾尝试这样做,但无济于事。 If somebody could help me out and show me how to store the input x,y into a 2d array, that'd be great :) 如果有人可以帮助我并向我展示如何将输入x,y存储到2d数组中,那就太好了:)

How the application should work : http://imgur.com/a/SnC1k 该应用程序应如何工作: http : //imgur.com/a/SnC1k

The [0,5] [18,18]etc are the entered coordinates which are later on printed down below. [0,5] [18,18]等是输入的坐标,稍后将其打印在下方。 The "#" chars dont need to be printed , they are here only to help with the understanding of the task. 不需要打印“#”字符,它们只是在这里帮助理解任务。

How I tried to do it but DIDN'T work : 我如何尝试但无法正常工作:

namespace ConsoleApplication1
{   
class Program
{
    static void Main(string[] args)
    {
        bool stopped = false;
        int x=0;
        int y=0;


        while (stopped)
        {
            string[,] coordinates = Console.ReadLine();
            string response = Console.ReadLine();
            response = response.ToLower();

            if (response == "STOP")
                stopped = true;
            else
            {
                string[] xy = coordinates.Split(',');
                x = int.Parse(xy[0]);
                y = int.Parse(xy[1]);

                Console.SetCursorPosition(x, y);
                Console.Write("*");
            }






        }


    }
    }
    }

The code I did just doesn't do it. 我做的代码只是没有做。 It shows multiple errors that I do not know how to fix and the only thing I was able to do is get it to print a char immediately when I enter the first coordinates, instead of printing a char at every entered coordinate, AFTER the word STOP is hit. 它显示了多个错误,这些错误我不知道如何解决,而我唯一能做的就是让它在我输入第一个坐标时立即打印一个char,而不是在单词STOP之后在每个输入的坐标处都打印char。被击中。

Create a 20x20 2d array. 创建一个20x20的2d数组。 Prompt the user for the x and y. 提示用户输入x和y。 Once you have each store a 1 in your array[x,y] once the user hits stop loop through the array and print '#' if null or 0 and print '*' if its a 1. 一旦每个都在数组[x,y]中存储了1,则用户在数组中单击了stop循环,如果为null则打印为“#”,如果为0,则打印为“ *”,如果为1,则打印为“ *”。

Edit, something along these lines I didn't check if this works or compiles but should get you on the right track. 编辑,按照这些思路,我没有检查它是否可以工作或编译,但应该可以使您走上正确的轨道。

    int[,] grid = new int[20,20];
    while (!stopped)
    {
        string[,] coordinates = Console.ReadLine();
        string response = Console.ReadLine();
        response = response.ToUpper();

        if (response == "STOP")
            stopped = true;
        else
        {
            string[] xy = coordinates.Split(',');
            x = int.Parse(xy[0]);
            y = int.Parse(xy[1]);
            grid[x,y] = 1;  
        }

        for (int i = 0; i < 20; i++)
        {
            for (int j = 0; j < 20; j++)
            {
                if (grid[i, j] > 0)
                    Console.Write("*");
                else
                    Console.Write("#");
            }
            Console.WriteLine("");
        }
    }

As you only need to display a matrix-style output you don't need to use Console.SetCursorPosition(x, y); 由于只需要显示矩阵样式的输出,因此不需要使用Console.SetCursorPosition(x, y);

Also you should read the user input somehow and set the proper value for the given position instead of store the coordinates. 另外,您应该以某种方式阅读用户输入,并为给定位置设置适当的值,而不是存储坐标。

Try this and let me know how this works for you. 试试这个,让我知道它如何为您工作。 You can see it also on this fiddle. 您也可以在小提琴中看到它。 Enter the coordinates as two space-separated numbers and enter stop to print. 输入两个空格分隔的数字,然后输入stop进行打印。

using System;

public class Program
{
    public static void Main(string[] args)
    {
        int x=0;
        int y=0;
        char[,] coordinates = new char[20,20];

        while (true)
        {
            //user must enter 2 3 for example.
            string[] response = Console.ReadLine().Split(new[]{" "}, StringSplitOptions.RemoveEmptyEntries);
            if (response[0].ToLower() == "stop")
                break;

            x = int.Parse(response[0]);
            y = int.Parse(response[1]);

            coordinates[x,y] = '*';
        }


        //Print the output
        for(var i = 0; i < 20; i++)
        {
            for( var j = 0; j < 20; j++)
                if (coordinates[i,j] == (char)0)
                    Console.Write('#');
                else 
                    Console.Write(coordinates[i,j]);

            Console.WriteLine();
        }
    }
}

Hope this helps! 希望这可以帮助!

I suggest decomposing the task, cramming entire rountine into a single Main as bad practice; 我建议分解任务,将整个常规塞入一个Main作为不良做法; you should: 你应该:

- ask user to enter coordinates
- print out the map

Let's extract the methods: 让我们提取方法:

private static List<Tuple<int, int>> s_Points = new List<Tuple<int, int>>();

private static void UserInput() {
  while (true) {
    string input = Console.ReadLine().Trim(); // be nice, let " stop   " be accepted

    if (string.Equals(input, "stop", StringComparison.OrdinalIgnoreCase))
      return;

    // let be nice to user: allow he/she to enter a point as 1,2 or 3   4 or 5 ; 7 etc.
    string[] xy = input.Split(new char[] { ',', ' ', ';', '\t' },
                              StringSplitOptions.RemoveEmptyEntries);
    int x = 0, y = 0;

    if (xy.Length == 2 && int.TryParse(xy[0], out x) && int.TryParse(xy[1], out y)) 
      s_Points.Add(new Tuple<int, int>(x, y));
    else
      Console.WriteLine($"{input} is not a valid 2D point.");
  }
}

Printing out 打印出来

private static void PrintMap(int size = 20) {
  // initial empty map; I prefer using Linq for that, 
  // you can well rewrite it with good old for loops
  char[][] map = Enumerable.Range(0, size)
    .Select(i => Enumerable.Range(0, size)
       .Select(j => '#')
       .ToArray())
    .ToArray();

  // fill map with points; 
  // please, notice that we must not print points like (-1;3) or (4;100) 
  foreach (var point in s_Points)
    if (point.Item1 >= 0 && point.Item1 < map.Length &&
        point.Item2 >= 0 && point.Item2 < map[point.Item1].Length)
      map[point.Item1][point.Item2] = '*';

  // The string we want to output; 
  // once again, I prefer Linq solution, but for loop are nice as well
  string report = string.Join(Environment.NewLine, map
    .Select(line => string.Concat(line)));

  Console.Write(report);
}

Finally, all you have to do it to call the methods: 最后,您需要做的就是调用方法:

static void Main(string[] args) {
  UserInput(); 
  PrintMap();

  Console.ReadKey();
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM