所以我正在进行Java赋值,其中我得到了一个大数组。我被告知以相反的顺序打印阵列中的前20个项目,然后再次以相反的顺序打印接下来的20个项目,依此类推,直到我到达数组的末尾。
我能够计算出如何反向打印第一个项目,但后来我在实现一些东西时遇到了问题,这些东西可以让我从原始数组中继续执行。
我一次只能储存21件物品。
这是我到目前为止的(50件而不是20件)
public static void doIt(BufferedReader r, PrintWriter w) throws IOException {
LinkedList<String> s = new LinkedList<String>();
int counter = 0;
int max = 50;
for (String line = r.readLine(); line != null; line = r.readLine()) {
if (counter < max) {
s.addFirst(line);
counter++;
}
if (counter == max) {
for (String n : s) {
System.out.println(n);
}
}
}
}
我想知道是否有人能帮我,不确定我能在这里做什么。
首先,每当counter
达到20的倍数时以及当它达到max
时,都需要打印列表。然后,打印s
的内容后,清除列表:
s.clear();
这将删除所有元素,以便再次填充。您还需要在for
循环退出后打印列表,否则最后几项将不打印。
请注意,在此代码中的任何位置都没有使用数组。使用LinkedList
是否遵循了作业精神尚不清楚。但只有你知道准则是什么。
我希望这能让你开始:
void example() {
for (int i = 0; i < 50; i++) { //fill array to be read (for this example)
myArray[i] = i;
}
readback();
}
void readback() {
int batch = 1; //represents a portion of the read operation
int batchSize = 20; //the size of the read portion
int pos = 0; //the current index of the array while it is being read
int hi; //the top of the batch
int lo; //the bottom of the batch
while (pos < myArray.length) {
if (batch*batchSize<myArray.length) { //make sure you are not going over the array boundary
hi = batch*batchSize;
lo = hi - batchSize;
} else {
hi = myArray.length;
lo = pos;
}
for (int i = hi - 1; i >= lo; i--) { //read
System.out.println(myArray[i]);
pos++;
}
batch++; //go to the next batch
}
}
对于问题的这一部分:
我被告知以相反的顺序打印数组中的前20个项目,然后再次以相反的次序打印接下来的20个项目。以此类推,直到我到达数组的末尾。
一个简单的解决方案是:
- 迭代数组中的20个位置
- 将此位置存储在临时索引中
- 迭代回打印数组的20个位置
- 从存储的临时索引重复过程
此外,请记住最后一次打印的元素是否少于20个。
int size = 20; // size of reversed chunks
for(int i = 0; i < array.length; i += size) {
int j = (i + (size - 1) < array.length) ? (i + size - 1) : array.length - 1;
for(; j >= i; j--) {
System.out.print(array[j] + " ");
}
}
但是,您的代码中没有数组,所以我不确定您的意思。您正在从文件中读取值,然后使用LinkedList
反向打印这些值。用于反向打印(以及大多数"反向"操作)的更好、更自然的数据结构是Stack
,尽管Java对LinkedList
的实现允许Stack
(LIFO)行为。它通常只是用作Queue
(FIFO)结构。我的答案也将使用LinkedList
,以使其与您的方法一致,但请考虑将来在这种情况下使用Stack
。
因此,由于您正在从文件中逐行读取数字,以下是您可以做的:
您可以读取并插入
LinkedList
顶部的数字,直到达到max
值或文件的末尾您已经有该部分在工作
通过从
LinkedList
顶部删除所有数字来打印所有数字,这将使它们以相反的顺序您正在打印它们,但没有通过调用
s.clear()
删除它们或清除列表一旦到达文件末尾,可能会导致值仍在
LinkedList
中,因为您在到达max
项目之前到达了文件末尾,并且循环已完成,但未打印任何内容。同时打印这些值。
另一件事是,您似乎没有写入文件,因此不需要函数的PrintWriter
参数。
这是代码:
public static void doIt(BufferedReader r) throws IOException {
LinkedList<String> s = new LinkedList<String>();
int counter = 0;
int max = 50;
for (String line = r.readLine(); line != null; line = r.readLine()) {
if (counter < max) {
s.addFirst(line);
counter++;
}
if (counter == max) {
while(!s.isEmpty()) { // remove and print in reverse order
System.out.println(s.removeFirst());
}
counter = 0; // reset counter
}
}
// print the remaining elements, if they exist
while(!s.isEmpty()) { // remove and print in reverse order
System.out.println(s.removeFirst());
}
}