如何连续地将数组中的项目馈送到两个堆栈中,然后两个堆栈会将数据馈送到队列中



文本文件,其中包含一组项目,如下所示:t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14,t15,t16,t17,t18

两个堆栈和队列限制为每个只能容纳 7 个项目,我需要不断将项目送入堆栈中,然后进入队列。

堆栈的输出将为:

Lift1 :t1,t2,t3,t4,t5,t6,t7Lift2 :t8,t10,t11,t12,t13,t14

我的代码:

public static void main(String[] args) 
{

ECFile ecf = new ECFile();
Stack<String> lift1 = new Stack<>();
Stack<String> lift2 = new Stack<>();
Queue<String> Conveyer = new LinkedList<>();
BlockingQueue<String> bq1 = new ArrayBlockingQueue<>(7);

String[] cargo = ecf.getArray("ConstructionData6.txt");
ecf.displayArray(cargo,"");
int food      = 0;
int materials  = 0;
int tools = 0;
int other     = 0;
bq1.offer("test");
for (int k=0; k<cargo.length; k++)
{
switch(cargo[k].substring(0,1)) 
{
case  "F" : food++;
break;         
case  "M" : materials++;
break;
case  "T" : tools++;
break;    
default   : other++;
break;
}
}
System.out.println("nFood    :  "+food);
System.out.println("Materials : "+materials);
System.out.println("Tools    : "+tools);
System.out.println("Errors   : "+other + "n");


for(int k=0; k<cargo.length; k++) 
{
if(k < 7)
{
lift1.push(cargo[k]);
}
else if(k < 14)
{
lift2.push(cargo[k]);
}

}

System.out.println("Lift Cargo: ");
System.out.println("lift1: " +lift1); 
System.out.println("lift2: " +lift2);

}

我的循环将数据推送到堆栈中,但如果项目多于它们可以容纳的项目,则项目就会丢失。

据我了解这个问题:

将元件送入两个最大容量为 7 的堆栈中 任何未馈入堆栈的项目都会进入队列。

for each item in cargo:
can I put it in the first stack?
else can I put in the second stack?
else put in the queue.

下面是一些代码指针:

if (lift1.size() < MAX_SIZE) {
lift1.push(cargo[k]);
else if (lift2.size() < MAX_SIZE) {
....

编辑:基于下面的评论。

因此,您需要跟踪是否允许堆栈接收项目。如果堆栈处于清空状态,则需要在下一个堆栈中推送项目,如果第二个堆栈进入清空状态,则移动到第一个堆栈。

您需要一个结构来保持堆栈(提升(的状态。您可以创建一个包装类或有一个数组来保存状态。

例如:

class Lift {
int capacity;
boolean emptying;
Stack<String> stack = new Stack<>();
public Lift(int maxCapacity) {
this.capacity = maxCapacity;
this.emptying = false;
}

public boolean push(String item) {
if (!emptying && stack.size() < capacity) {
stack.push(item);
return true;
} else {
//state is emptying
emptying = true;
return false
}
}
public void pushtoQueue(Queue queue) {
while(!stack.isEmpty()) {
queue.add(stack.pop();
}
emptying = false;
}
}

然后你的主循环是

boolean result1 = lift1.push(cargo[k]);
if (!result1) {
lift2.push(cargo[k]);
} 

最新更新