我制作了一个小型系统,它使用seatCount来填充一定数量的座位(没有行)。现在我制作了一个方法来填充座位并返回一张地图,地图返回一定数量的座位空闲的位置(例如3-2表示在地点3处开始有两个座位。
这很好用但是如果我说最多有5个座位而座位5是免费的,那么该方法不会将其返回到地图。
以下是使用的代码:
对象座位
public class Seat {
public Integer availability;
public Integer seatNumber;
public boolean IsFree() {
if(availability == 0){
return true;
}
else return false;
}
public String toString() {
return "{ " + seatNumber + ", free: " + IsFree() + " } ";
}
}
此方法创建一个LinkedList,并使用' 1'填充可用性。 (拍摄)或' 0' (可用)通过giveRandomAvailability()方法
static LinkedList fillList(int seats){
LinkedList<Seat> list = new LinkedList<Seat>();
seats = seatCount;
for(int i = 0; i < seats; i++){
Seat seat = new Seat();
seat.availability = giveRandomAvailability();
seat.seatNumber = (i + 1);
list.add(seat);
}
return list;
}
这是无法正常工作的方法,它应该用可用的座位填充地图,但是当最后一个元素可用时,它不会映射。 以下是输出示例:
[{ 1, free: true } , { 2, free: true } , { 3, free: false } , { 4, free: true } , { 5, free: true } ]
{1=2}
你可以看到第一部分处理得很好但它也应该包含4 = 2。
方法:
static Map fillSeats(){
int n = 3;
LinkedList<Seat> newList = fillList(seatCount);
int consecutiveLength = 0; // Consecutive free seats length
int index = 0;
int startIndex = -1; // Store the start of consecutive free seats
System.out.println(newList.toString());
Map<Integer, Integer> consecutiveMap = new HashMap<>(); // Store startIndex -> length
for (Seat seat : newList) {
if (seat.IsFree()) {
if (startIndex < 0) {
startIndex = index;
}
consecutiveLength ++;
} else {
consecutiveMap.put(startIndex + 1, consecutiveLength);
if (consecutiveLength == n) {
// Found, do something here
}
// Reset
startIndex = -1;
consecutiveLength = 0;
}
index++;
}
return consecutiveMap;
}
我在这里找不到问题,非常感谢帮助。
答案 0 :(得分:4)
好吧,如果该组包含 <config-file target="AndroidManifest.xml" parent="/*">
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
</config-file>
<config-file target="AndroidManifest.xml" parent="/manifest/application">
<receiver android:name=".CallReceiver" >
<intent-filter> <action android:name="android.intent.action.PHONE_STATE" /> </intent-filter>
</receiver>
</config-file>
的最后一个元素,那么你的循环不会添加最后一组连续席位。您应该在循环后添加逻辑以添加最后一个组:
List
答案 1 :(得分:1)
您对consecutiveMap.put
的调用仅存在于循环的else
子句中,并且由于列表中的最后一个元素是免费的,因此最终的两个席位永远不会执行此代码。
seat.IsFree() == true
,增量计数器seat.IsFree() == true
,增量计数器seat.isFree() == false
,为地图添加值,重置计数器seat.isFree() == true
,增量计数器seat.isFree() == true
,增量计数器然后循环终止,因此最终的计数器不会添加到地图中。