草庐IT

Java-复杂程序中的2D数组索引操作

coder 2024-04-02 原文

在问我的问题之前,我想澄清一些事情。首先,我是Java和程序设计的新手。其次,这是我的第二篇文章,因此,如果我做错了什么,请放轻松。最后,我想解释一下为什么我做错了,而不是在对此帖子的任何回复中只是粘贴的解决方案。为了更好地理解该问题,我将编写分配信息,然后编写给定的Driver类,然后编写由Driver类访问的我的类代码。

我的问题:

如何使我的“建筑物”的左下角在2D数组上为[0] [0]? Here's一个for循环的示例,该示例可将2D数组的左下角更改为[0] [0],但我尝试将其实现到我的searchRoom方法中(玩家角色设置为myHidingPlaces索引),我可以t将myHidingPlaces [0] [0]设为我的2D数组的左下角。我相信我需要使用for循环以某种方式编辑toString方法,但是我不知道该怎么做。

以下是任务:

您要设计一个类“LostPuppy.java”,该类代表迷失在多层建筑中的小狗,
每个楼层包含相同数量的房间。在实例化(或创建)此类的对象时,
每个楼层的每个房间都将初始化为空(为此,您实际上将使用空格“”
目的),并会在丢失小狗的地方选择一个随机的房间。为此,字符“P”将
被放置在这个随机的位置。下面列出了有关构造函数的更多详细信息。

此类的一个对象用作游戏,两个玩家轮流搜索小狗,一个房间
直到发现不幸的小犬只为止的时间。该对象的实例化和搜索将被执行
通过提供给您的“驱动程序”程序,您只需专注于开发
类(驱动程序在文件“PuppyPlay.java”中)

字段(当然,所有字段都是私有(private)的):

  • 名为myHidingPlaces的字符(字符)数组。这代表行是楼层的建筑物
    列是每个楼层的房间(此建筑物采用不同寻常的编号系统;楼层和
    房间都从零开始)。
  • 这两个整数将保存丢失小狗的地板和房间,名为myFloorLocation和
    myRoomLocation。
  • 一个名为myWinner的字符,当玩家找到小狗时,将为其分配角色
    (驱动程序使用数字“1”和“2”来更清楚地区分玩家和幼犬)。
  • 一个名为myFound的 boolean 值,当找到小狗时将其设置为true。

  • 构造函数:
  • 接收两个整数参数作为用户输入的建筑物楼层和房间数
    在其中,小狗迷路了。
  • 构造函数使用第一个参数将2D数组“myHidingPlaces”实例化为字符数组。
    行(theFloors)和第二个参数作为列(theRooms)。
  • 初始化myHidingPlaces单元格,每个单元格包含一个空格‘(用单引号引起)
  • 使用第一个参数
  • 随机设置myFloorLocation(地板小狗处于打开状态)
  • 使用第二个参数
  • 随机设置myRoomLocation(房间里的小狗在里面)
  • 将myHidingPlaces [myFloorLocation] [myRoomLocation]设置为字符“P”
  • 将myWinner设置为单个空格
  • 将myFound设置为false

  • 方法:
  • roomSearchedAlready接收要搜索的楼层和房间,如果房间有
    已被搜索,否则返回false。
  • puppyLocation接收要搜索的楼层和房间,如果楼层和房间为
    小狗丢了的地方,否则为假。此方法不应更改任何字段。
  • indexOK接收要搜索的楼层和房间,如果楼层和房间的值是
    在数组索引范围内,否则为false(用于检查这些索引不会导致错误)
    当应用于数组时)。
  • numberOfFloors返回建筑物中的楼层数(第一层从零开始)。
  • numberOfRooms返回建筑物每个楼层的房间数(第一个房间开始于
    零,并且所有楼层的房间数均相同)。
  • searchRoom接收要搜索的楼层和房间以及当前播放器(以char类型表示)
    如果找到了小狗,则返回true,否则返回false。如果未找到小狗,还可以搜索
    将接收到的楼层和房间位置的myHidingPlaces数组设置为接收到的玩家值(“1”
    或“2”)OR(如果找到),将myWinner字段设置为当前播放器,并将myFound设置为true。
  • toString显示当前的hiddenPlaces数组及其内容(除了小狗的位置)
    这将一直隐藏,直到找到他/她,此时将调用(驱动程序)toString,并且两者都被调用
    找到小狗和“P”的玩家将显示在同一单元格中…。
  • 现在,也许是toString输出的尴尬部分。通常,在显示2D数组时,
    [0] [0]单元格与矩阵一样显示在左上角。但是,因为小狗
    决定迷失在建筑物而不是矩阵中,拥有一楼将更具视觉感
    (第0行)显示在底部,其上方的第二层……最后是顶层,那么……在顶部!至
    保存单词,仔细查看下一页提供的示例运行。您的输出应该看起来像
    与示例运行的下一页上看到的相同。

  • 这是驱动程序:
    import java.util.Random;
    import java.util.Scanner;
    
    /**
     * This program is used as a driver program to play the game from the
     * class LostPuppy.  Not to be used for grading!
     *
     * A puppy is lost in a multi-floor building represented in the class 
     * LostPuppy.class.  Two players will take turns searching the building
     * by selecting a floor and a room where the puppy might be.
     *
     * @author David Schuessler
     * @version Spring 2015
     */
    
    public class PuppyPlay
    {
      /**
       * Driver program to play LostPuppy.
       *
       * @param theArgs may contain file names in an array of type String
       */
      public static void main(String[] theArgs)
      {
        Scanner s = new Scanner(System.in);
        LostPuppy game; 
        int totalFloors;
        int totalRooms;
        int floor;
        int room;
        char[] players = {'1', '2'};
        int playerIndex;
        boolean found = false;
        Random rand = new Random();
    
        do 
        {
          System.out.print("To find the puppy, we need to know:\n"
                           + "\tHow many floors are in the building\n"
                           + "\tHow many rooms are on the floors\n\n"
                           + "             Please enter the number of floors: ");
          totalFloors = s.nextInt();
          System.out.print("Please enter the number of rooms on the floors: ");
          totalRooms = s.nextInt();
          s.nextLine();    // Consume previous newline character    
    
          // Start the game: Create a LostPuppy object:
          game = new LostPuppy(totalFloors, totalRooms);
    
          // Pick starting player
          playerIndex = rand.nextInt(2);
    
          System.out.println("\nFloor and room numbers start at zero '0'");
    
          do 
          {
    
            do 
            {
              System.out.println("\nPlayer " + players[playerIndex]
                                 + ", enter floor and room to search separated by a space: ");
              floor = s.nextInt();
              room = s.nextInt();
    
              //for testing, use random generation of floor and room
              //floor = rand.nextInt(totalFloors);
              //room = rand.nextInt(totalRooms);
            } while (!game.indicesOK(floor, room) 
                     || game.roomSearchedAlready(floor, room));
    
    
            found = game.searchRoom(floor, room, players[playerIndex]);
            playerIndex = (playerIndex + 1) % 2;
            System.out.println("\n[" + floor + "], [" + room + "]");
            System.out.println(game.toString());
            s.nextLine();
          } while (!found);
    
          playerIndex = (playerIndex + 1) % 2;
          System.out.println("Great job player " + players[playerIndex] +"!");
          System.out.println("Would you like to find another puppy [Y/N]? ");
        } 
        while (s.nextLine().equalsIgnoreCase("Y"));
      }
    }
    

    最后,这是我的测试代码:
    import java.util.Random;
    import java.util.Scanner;
    
    public class LostPuppy
    {
       int value;
       char[][] myHidingPlaces;
       int myFloorLocation;
       int myRoomLocation;
       char myWinner;
       boolean myFound;
       Random random = new Random();
    
       public LostPuppy(int theFloors, int theRooms)
       {
          myHidingPlaces = new char[theFloors][theRooms];
    
          for (int i = theFloors - 1; i >= 0; i--)
          {
             for (int j = 0; j <= theRooms - 1; j++)
             {
                myHidingPlaces[i][j] = ' ';
             }
          }
    
          myFloorLocation = random.nextInt(theFloors);
          myRoomLocation = random.nextInt(theRooms);
          myHidingPlaces[myFloorLocation][myRoomLocation] = 'P';
          myWinner = ' ';
          myFound = false;  
       }
       public boolean roomSearchedAlready(int floor, int room)
       {
          return (myHidingPlaces[floor][room] == '1' || 
                  myHidingPlaces[floor][room] == '2');
       }
    
       public boolean puppyLocation(int floor, int room)
       {
          return (myHidingPlaces[floor][room] == 'P');
       }
    
       public boolean indicesOK(int floor, int room)
       {
          return (floor <= myHidingPlaces.length && room <= myHidingPlaces[0].length);
       }
    
       public int numberOfFloors()
       {
          return myHidingPlaces.length - 1;
       }
       public int numberOfRooms()
       {
          return myHidingPlaces[0].length - 1;
       }
    
       public boolean searchRoom(int floor, int room, char player)
       {
          if (puppyLocation(floor, room))
          {
             myFound = true;
             myWinner = player;
             return true;
          }
          else
          {
             myHidingPlaces[floor][room] = player;
             return false;
          }
       }
    
       public String toString()
       {
          int rooms = myHidingPlaces[0].length;
          int floors = myHidingPlaces.length;
    
          System.out.print(" ");
          for (int x = 0; x < rooms; x++)
          {
             System.out.print("___");
          }
    
          for (int y = 0; y < rooms - 1; y++)
          {
             System.out.print("_");
          }
          System.out.print("\n");
    
          for (int r = 0; r < floors; r++)
          {
             System.out.print("| ");
             for (int c = 0; c < rooms; c++)
             {
    
                if (myHidingPlaces[r][c] == 'P' && myFound)
                {
                   System.out.print("" + myWinner + "" + myHidingPlaces[r][c] + "| ");
                }
                else if (myHidingPlaces[r][c] == 'P' && !myFound)
                {
                   System.out.print("  | ");
                }
                else
                {
                   System.out.print(myHidingPlaces[r][c] + " | ");
                }
    
                //System.out.print(myHidingPlaces[r][c] + " | ");
    
             }
             System.out.print("\n");
             for (int i = 0; i < rooms; i++)
             {
                System.out.print("|___");
             }
             System.out.print("|\n");
          }
          return "";
    
       }
    
    }
    

    最佳答案

    您无法用Java创建反向数组,但是您不需要它。您需要考虑建筑物并对其进行操作,就像使用矩阵一样。但是,您需要颠倒打印。同样,通过您提供的链接也不会更改数组中的位置,这只是从最后一个索引到第一个索引的数组遍历。

    因此,您需要上下颠倒地打印阵列,这非常容易。您需要在toString方法中更改一行,然后更改

    for (int r = 0; r < floors; r++)
    


    for (int r = floors - 1; r >= 0; r--)
    

    这样您将获得正确的结果!

    同样在这种情况下,您不需要从最后到第一个填充数组(至少因为您用相同的值填充数组),就像您所做的一样
    for (int i = theFloors - 1; i >= 0; i--) {
        for (int j = 0; j <= theRooms - 1; j++) {
            ...
        }
    }
    

    如果这样做的话会更好(只是更好地阅读代码)
    for (int i = 0; i < theFloors; i++) {
        for (int j = 0; j < theRooms; j++) {
            ...
        }
    }
    

    正如@Dante所说,您还需要更正indicesOK方法,因为数组的最后一个索引是它的length - 1,因此,当您访问myHidingPlaces.lengthmyHidingPlaces[i].length元素时,将抛出ArrayIndexOutOfBoundsException异常。
    public boolean indicesOK(int floor, int room) {
        return (floor < myHidingPlaces.length && room < myHidingPlaces[0].length);
    }
    

    关于Java-复杂程序中的2D数组索引操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31421459/

    有关Java-复杂程序中的2D数组索引操作的更多相关文章

    1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

      总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

    2. ruby - 其他文件中的 Rake 任务 - 2

      我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

    3. ruby-on-rails - Ruby net/ldap 模块中的内存泄漏 - 2

      作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代

    4. ruby - 在 Ruby 程序执行时阻止 Windows 7 PC 进入休眠状态 - 2

      我需要在客户计算机上运行Ruby应用程序。通常需要几天才能完成(复制大备份文件)。问题是如果启用sleep,它会中断应用程序。否则,计算机将持续运行数周,直到我下次访问为止。有什么方法可以防止执行期间休眠并让Windows在执行后休眠吗?欢迎任何疯狂的想法;-) 最佳答案 Here建议使用SetThreadExecutionStateWinAPI函数,使应用程序能够通知系统它正在使用中,从而防止系统在应用程序运行时进入休眠状态或关闭显示。像这样的东西:require'Win32API'ES_AWAYMODE_REQUIRED=0x0

    5. ruby-on-rails - Rails 3 中的多个路由文件 - 2

      Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

    6. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

      我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

    7. ruby - 多次弹出/移动 ruby​​ 数组 - 2

      我的代码目前看起来像这样numbers=[1,2,3,4,5]defpop_threepop=[]3.times{pop有没有办法在一行中完成pop_three方法中的内容?我基本上想做类似numbers.slice(0,3)的事情,但要删除切片中的数组项。嗯...嗯,我想我刚刚意识到我可以试试slice! 最佳答案 是numbers.pop(3)或者numbers.shift(3)如果你想要另一边。 关于ruby-多次弹出/移动ruby​​数组,我们在StackOverflow上找到一

    8. ruby - 如何指定 Rack 处理程序 - 2

      Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack

    9. ruby - 将数组的内容转换为 int - 2

      我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

    10. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

      我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

    随机推荐