用Java填充布尔数组 [英] Populating a Boolean Array in Java

查看:233
本文介绍了用Java填充布尔数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为一个相当绿色的Java编码器,我给自己设定了尝试编写简单文本冒险的艰巨挑战.毫不奇怪,我已经遇到了困难!

As a fairly green Java coder I've set myself the hefty challenge of trying to write a simple text adventure. Unsurprisingly, I've encountered difficulties already!

我正在尝试为Location类提供一个属性,以存储其中包含的退出项.我为此使用了一个布尔数组,以保留代表每个出口的true/false值.我不完全相信

I'm trying to give my Location class a property to store which exits it contains. I've used a boolean array for this, to essentially hold true/false values representing each exit. I'm not entirely convinced that

a),这是最有效的方法,并且

a) this is the most efficient way to do this and

b),我正在使用正确的代码填充数组.

b) that I'm using the right code to populate the array.

我希望收到所有反馈,即使是对完整的代码进行大修!

I would appreciate any and all feedback, even if it is for a complete code over-haul!

目前,在实例化Location时,我会生成一个字符串,并将其发送给setExits方法:

At present, when instantiating a Location I generate a String which I send through to the setExits method:

    String e = "N S U";
    secretRoom.setExits(e);

在Location类中,setExits看起来像这样:

In the Location class, setExits looks like this:

public void setExits(String e) {
    if (e.contains("N"))
        bexits[0] = true;
    else if (e.contains("W"))
        bexits[1] = true;
    else if (e.contains("S"))
        bexits[2] = true;
    else if (e.contains("E"))
        bexits[3] = true;
    else if (e.contains("U"))
        bexits[4] = true;
    else if (e.contains("D"))
        bexits[5] = true;
}

老实说,我认为这看起来特别笨拙,但我想不出另一种方法来做到这一点.我现在也不完全确定如何编写getExits方法...

I'll be honest, I think this looks particularly clunky, but I couldn't think of another way to do it. I'm also not entirely sure now how to write the getExits method...

欢迎任何帮助!

推荐答案

是否有任何理由使您使用String s执行此操作,而不传递booleans,即

Is there any reason why you are doing this with Strings and aren't passing in booleans, i.e.

public void setExits(boolean N, boolean E, boolean S, boolean W, boolean U, boolean D) 

还是有设置者?

public void setNorthOpen(boolean open)
{
  bexits[4] = open;
}

第二,为什么要将出口存储为布尔数组,这是一个很小的有限集,为什么不只是

Secondly, why are you storing the exits as an array of booleans, it's a small finite set, why not just

boolean N,S,E,W,U,D;

这样,您就不必跟踪每个方向是数组中的哪个数字.

As then you don't need to keep track of which number in the array each direction is.

这是一个正确的答案(如果不是像@gexicide那样的最佳选择),但我完全鼓励任何人在这里查看其他答案,以有趣的方式看一下如何用Java以不同的方式完成事情.

This is a correct answer (if not completely optimal like that of @gexicide) but I fully encourage anyone to look at the other answers here for an interesting look at how things can be done in Java in different ways.

以供将来参考

有效的代码属于代码审查,而不是堆栈溢出.尽管正如@kajacx所指出的,该代码实际上不起作用.

Code which works belongs on Code Review, not Stack Overflow. Although as @kajacx pointed out, this code shouldn't -in fact- work.

这篇关于用Java填充布尔数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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