我的代码
Random random = new Random();
int economySeat = random.nextInt(23 - 12 + 1) + 12;
seatNumber = economySeat;
if (seatManager.getSeats()[seatNumber] == false) {
seatManager.getSeats()[seatNumber] = true;
}
从显示范围内的布尔数组中随机选择经济座位。如何在我运行程序时选择空座位?目前,当只剩下一个座位时,我必须多次按下一个选择按钮,例如
答案 0 :(得分:1)
此解决方案不允许SeatManager的消费者提交随机数来获得席位。相反,它使用随机索引为座位返回随机随机座位号。我认为这是更干净的实施。您可以针对您的UI进行调整。
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Random;
public class SeatConsumer
{
public static void main(String [] Args)
{
SeatManager sm = new SeatManager();
int RandomEconomySeat = 0;
while(RandomEconomySeat > -1)
{
RandomEconomySeat = sm.GetRandomEconomySeat();
if(RandomEconomySeat > -1 && sm.SetEconomySeat(RandomEconomySeat))
{
System.out.println(sm);
}
else
{
return;
}
}
}
}
class SeatManager
{
private final int StartingEconomy = 12;
private final int EndingEconomy = 24;
private boolean [] seats;
private ArrayList<Integer> availableSeats = new ArrayList<Integer>();
private ArrayList<Integer> seatIndexes = new ArrayList<Integer>();
public SeatManager()
{
seats = new boolean[(EndingEconomy+1)-StartingEconomy];
for(int i=StartingEconomy; i<=EndingEconomy; i++)
{
availableSeats.add(i);
seatIndexes.add(i);
}
}
public int GetRandomEconomySeat()
{
Random random = new Random();
random.setSeed((Calendar.getInstance().getTimeInMillis()));
if(availableSeats.size() > 0)
{
int randomIndex = random.nextInt(availableSeats.size());
return availableSeats.get(randomIndex);
}
return -1;
}
public boolean SetEconomySeat(int seat)
{
if(seat >0)
{
int seatIndex = seatIndexes.indexOf(seat);
seats[seatIndex]=true;
if(availableSeats.contains(seat))
{
int availSeatIndex = availableSeats.indexOf(seat);
availableSeats.remove(availSeatIndex);
return true;
}
return false;
}
return false;
}
public String toString()
{
String temp = "";
for(boolean b : seats)
{
//should use string builder; however this is a quick example
if(b)
{
temp += "1 ";
}
else
{
temp += "0 ";
}
}
return temp;
}
}