JAVA:如何使用 toString 将二维字符数组表示为字符串? [英] JAVA : How can I represent a 2D character array as a String using a toString ?

查看:15
本文介绍了JAVA:如何使用 toString 将二维字符数组表示为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 LRV(最近最少访问)算法制作程序.基本上,我为机器人设计了遍历网格(这是一个二维字符数组)的算法.机器人在穿越网格时检查每个单元格是否为 EMPTY(由-"定义)、OCCUPIED(由O"定义)或 BLOCKED(由X"定义).这些单元格只能被称为 Sensor 的对象占据(它有自己的类).无法遍历 BLOCKED 单元格.每次机器人必须移动时,它都会从传感器接收一个方向.所以一开始,机器人会被放置在网格上,它会放下一个传感器并从中获取方向,或者从预先存在的传感器中获取方向.

I am making a program using the LRV(Least recently visited) Algorithm. Basically, I design the algorithm for a robot to traverse through a grid (which is a 2D char array). The robot whilst traversing the grid checks whether each cell is either EMPTY (defined by '-'), OCCUPIED ( defined by 'O' ) or BLOCKED (defined by 'X'). The cells can only be occupied by an object known as Sensor (this has its own class). BLOCKED cells cannot be traversed on. Each time the robot must move, it receives a direction from the sensor. So in the beginning the robot would be placed on the grid and it would drop a sensor and get a direction from it, or get a direction from a pre-existing sensor.

现在我已经解释了我的程序,我的具体问题是,我有我的 GridMap 类

Now that I've explained my program, my specific question is, I have my GridMap class

public class GridMap {
  private int height;
  private int width;
  private char[][] grid;


  public GridMap(int x, int y) { 
    height=x;
    width=y;  
    grid = new char [x][y];
  }
  public int getHeight(){
    return height;
  }
  public int getWidth(){
    return width;
  }
  public String toString(){
    String s1 = 
    return s1;
  }
  public char getElementAt(int x, int y){
  }
  public void setElementAt(int x, int y){
  }
  public boolean isCellBlocked(int x, int y){
  }
  public double getCoverageIndex(){
    return COVERAGE_INDEX;
  }
}

我想知道的是如何将我的二维字符数组表示为一串 -、O 和 X.我尽量详细,如果有人有任何问题,我愿意尽快回答.任何帮助将不胜感激.谢谢

What I want to know is how can I represent my 2D char array as a string of -, O's and X's. I tried to be as detailed as possible, if anyone has any questions I'd be willing to answer asap. Any help will be highly appreciated. Thanks

瓦伦

推荐答案

这是你的意思吗?

public String toString()
{
    StringBuilder builder = new StringBuilder();
    for(int i = 0; i < getHeight(); i++)
    {
        for(int j = 0; j < getWidth(); j++)
        {
            builder.append(grid[i][j]);
        }
    }    
    return builder.toString();
}

这篇关于JAVA:如何使用 toString 将二维字符数组表示为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆