簡體   English   中英

C#使用帶有二維數組的輸入坐標打印“ *”字符

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

我一直在嘗試做幾天前收到的任務。 基本上,該任務是C#中的控制台應用程序:

提示用戶輸入2個坐標,直到輸入單詞“ stop”。 按下單詞“ stop”后,在每個輸入坐標處打印一個“ *”(星號字符)。 打印坐標的字段為20x20。 我曾嘗試這樣做,但無濟於事。 如果有人可以幫助我並向我展示如何將輸入x,y存儲到2d數組中,那就太好了:)

該應用程序應如何工作: http : //imgur.com/a/SnC1k

[0,5] [18,18]等是輸入的坐標,稍后將其打印在下方。 不需要打印“#”字符,它們只是在這里幫助理解任務。

我如何嘗試但無法正常工作:

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("*");
            }






        }


    }
    }
    }

我做的代碼只是沒有做。 它顯示了多個錯誤,這些錯誤我不知道如何解決,而我唯一能做的就是讓它在我輸入第一個坐標時立即打印一個char,而不是在單詞STOP之后在每個輸入的坐標處都打印char。被擊中。

創建一個20x20的2d數組。 提示用戶輸入x和y。 一旦每個都在數組[x,y]中存儲了1,則用戶在數組中單擊了stop循環,如果為null則打印為“#”,如果為0,則打印為“ *”,如果為1,則打印為“ *”。

編輯,按照這些思路,我沒有檢查它是否可以工作或編譯,但應該可以使您走上正確的軌道。

    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("");
        }
    }

由於只需要顯示矩陣樣式的輸出,因此不需要使用Console.SetCursorPosition(x, y);

另外,您應該以某種方式閱讀用戶輸入,並為給定位置設置適當的值,而不是存儲坐標。

試試這個,讓我知道它如何為您工作。 您也可以在小提琴中看到它。 輸入兩個空格分隔的數字,然后輸入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();
        }
    }
}

希望這可以幫助!

我建議分解任務,將整個常規塞入一個Main作為不良做法; 你應該:

- ask user to enter coordinates
- print out the map

讓我們提取方法:

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.");
  }
}

打印出來

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);
}

最后,您需要做的就是調用方法:

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

  Console.ReadKey();
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM