有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将循环长度设置为2D数组长度?

我有java代码,可以对内部循环的长度执行此操作

char[][] board = new char[3][3];

for(int a = 0; a < board.length; a++)
{
   for(int b = 0; b < board[a].length; b++)
   {
      //my code here
   }
}

但当我在c#as中尝试时

for(int b = 0; b < board[a,].Length; b++)

它会产生错误

"Syntax error: value expected"

如果我把这个值写下来

for(int b = 0; b < board[a,b].Length; b++)

它会产生错误

char does not contain a definition for Length

有人能帮我吗

试试这个

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            char[,] board = { { 'a', 'b', 'c' }, { 'd', 'e', 'f' }, { 'g', 'h', 'i' } };

            for (int a = 0; a < board.GetLength(0); a++)
            {
                for (int b = 0; b < board.GetLength(1); b++)
                {
                    char test = board[a,b];
                    //my code here
                }
            }
        }
    }
}

共 (1) 个答案

  1. # 1 楼答案

    您可以使用GetLength方法。 见here