我正在做作业,并在文本文件中提供了一些数据。我必须将数据放入2个堆栈中,但是它们一次只能容纳7个数据。
示例数据t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14
Stack<String> lift1 = new Stack<>();
Stack<String> lift2 = new Stack<>();
String[] cargo = ecf.getArray("ConstructionData6.txt");
for(int k=0; k<cargo.length; k++)
{
lift1.push(cargo[k]);
}
System.out.println("Lift Cargo: ");
System.out.println("lift1: " +lift1);
System.out.println("lift2: " +lift2);
输出将是:
提升1:[t1,t2,t3,t4,t5,t6,t7]
提升2:[t8,t9,t10,t11,t12,t13,t14]
最佳答案
因为这是一项家庭作业,所以我将不提供任何Java代码,而仅提供伪代码。
示例数据集有14个项目,但可以有15个项目吗? 25吗一个好的解决方案将具有足够的动态性来处理变化。我建议一个堆栈的集合,集合中的每个堆栈最多容纳7个项目。
// Again, this is not actually Java, just pseudo code
// Create a place to put your restructured data
Collection theStacks = new Collection();
theStacks.push( new Stack<>() );
Stack<> whichStack = null;
String[] cargo = ecf.getArray("ConstructionData6.txt");
for (int k=0; k<cargo.length; k++) {
// Pick the correct stack to put stuff in
if (the last stack in theStacks has length > 7) {
// If the most recent stack has 7 things in it, make a new one
theStacks.push( new Stack<>() );
}
whichStack = the last stack in theStacks;
// Push it, push it real good
whichStack.push(cargo[k]);
}
更好的办法是用变量或常数替换“幻数” 7。