强制用户输入0或1

时间:2018-01-16 20:49:11

标签: c# arrays matrix input

我正在尝试创建m * n矩阵,对于这个矩阵,我希望用户只输入o或1。我想强制用户,直到用户输入0或1。

int m=2; int n=2; 
double[,] DOFmatrix = new double[m, n];
for (int i = 0; i <m; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    double input;
                    Console.Write("Enter value for node in (X,Y) direction either 0 or 1", i,j);
                    while (!double.TryParse(Console.ReadLine(), out input)
                    {
                    Console.Write("Enter correct value for ({0},{1}): ", i, j);
                    }             
                    DOFmatrix[i, j] = input
                }

1 个答案:

答案 0 :(得分:0)

就是这样:

        namespace ConsoleApplication1
        {
            class Program
            {
                static void Main(string[] args)
                {
                    //matrix size is defined and matrix is created
                    int m = 3, n = 3;
                    int value = 0;
                    string input;
                    int[,] matrix = new int[m,n];
                    //instructions are given to the user
                    Console.WriteLine("Please fill the matrix whit values 0 or 1");
                    //matrix size is obtained and used to nest for to fill the matrix
                    for (int i = 0; i < matrix.GetLength(0); i++)
                    {
                        for (int j = 0; j < matrix.GetLength(1); j++)
                        {
                            //do-while statement is used to *trap* the user
                            //until correct input is given
                            do
                            {
                                input = Console.ReadLine();
                                value = Convert.ToInt32(input);
                                if (value != 0 && value != 1)
                                {
                                    Console.WriteLine("Please write 0 or 1");
                                }
                            } while (value != 0 && value != 1);
                            matrix[i, j] = value;
                        }
                    }
                    //Matrix is printed to confirm the input is correct
                    Console.WriteLine("The resulting matrix is:");
                    for (int i = 0; i < matrix.GetLength(0); i++)
                    {
                        for (int j = 0; j < matrix.GetLength(1); j++)
                        {
                            Console.Write(matrix[i,j].ToString()+"\t");
                        }
                        Console.WriteLine();
                    }
                    Console.ReadKey();
                }
            }
        }

如果您有任何疑问,请在评论中告诉我。