在问我的问题之前,我想澄清一些事情。首先,我是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)的):
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++) {
...
}
}
indicesOK方法,因为数组的最后一个索引是它的length - 1,因此,当您访问myHidingPlaces.length或myHidingPlaces[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/
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
我试图在一个项目中使用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时
作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代
我需要在客户计算机上运行Ruby应用程序。通常需要几天才能完成(复制大备份文件)。问题是如果启用sleep,它会中断应用程序。否则,计算机将持续运行数周,直到我下次访问为止。有什么方法可以防止执行期间休眠并让Windows在执行后休眠吗?欢迎任何疯狂的想法;-) 最佳答案 Here建议使用SetThreadExecutionStateWinAPI函数,使应用程序能够通知系统它正在使用中,从而防止系统在应用程序运行时进入休眠状态或关闭显示。像这样的东西:require'Win32API'ES_AWAYMODE_REQUIRED=0x0
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上找到一个类似的问题
我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代
我的代码目前看起来像这样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上找到一
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
我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]
我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何