Java 使用ListIterator,添加一个-1“;在arraylist中介于2个偶数整数之间
这是我的第一篇帖子,如果不完美,我道歉。我正在处理一个项目,需要使用ListIterator遍历整数数组列表。在这个遍历过程中,我需要找到所有偶数对,并在它们之间添加“-1”来分隔偶数。这是我目前的代码:Java 使用ListIterator,添加一个-1“;在arraylist中介于2个偶数整数之间,java,iterator,integer,traversal,Java,Iterator,Integer,Traversal,这是我的第一篇帖子,如果不完美,我道歉。我正在处理一个项目,需要使用ListIterator遍历整数数组列表。在这个遍历过程中,我需要找到所有偶数对,并在它们之间添加“-1”来分隔偶数。这是我目前的代码: No two evens. Print the original list. If you find two even numbers then add a -1 between them. Print the new list. */
No two evens. Print the original list. If you find two even numbers then add a -1 between them. Print the new list.
*/
ListIterator<Integer> lt5 = x.listIterator();
System.out.println();
System.out.println("N O E V E N S ");
printArrays(x);
while(lt5.hasNext()) {
if(lt5.next() %2 ==0 && lt5.next()%2==0) {
lt5.previous();
lt5.add(-1);
}
}
System.out.println();
ListIterator<Integer> lt6 = x.listIterator();
while(lt6.hasNext()) {
System.out.print(lt6.next()+" ");
}
没有两个晚上。打印原始列表。如果你找到两个偶数,那么在它们之间加上-1。打印新列表。
*/
ListIterator lt5=x.ListIterator();
System.out.println();
系统输出打印项次(“不可用”);
打印阵列(x);
while(lt5.hasNext()){
如果(lt5.next()%2==0&<5.next()%2==0){
lt5.previous();
lt5.增加(-1);
}
}
System.out.println();
ListIterator lt6=x.ListIterator();
while(lt6.hasNext()){
System.out.print(lt6.next()+);
}
我相信这很简单,但我想不出来。有什么想法吗
我需要使用迭代器如果连续两个晚上后需要
-1
,您可以使用以下代码:
public void modifyList(List<Integer> list){
System.out.println(list);
ListIterator<Integer> it = list.listIterator();
while(it.hasNext()){
if(it.next()%2==0 && it.hasNext() && it.next()%2==0){
it.add(-1);
}
}
System.out.println(list);
}
//Input: [1,2,3,4]
//Output:[1,2,3,4]
//Input: [1,2,4,5,6,8]
//Output:[1,2,4,-1,5,6,8,-1]
public void modifyList(List<Integer> list){
System.out.println(list);
ListIterator<Integer> it = list.listIterator();
while(it.hasNext()){
if(it.next()%2==0 && it.hasNext() && it.next()%2==0){
it.previous();
it.add(-1);
}
}
System.out.println(list);
}
//Input: [1,2,3,4]
//Output:[1,2,3,4]
//Input: [1,2,4,5,6,8]
//Output:[1,2,-1,4,5,6,-1,8]
我将如何在其中合并迭代器?我必须使用迭代器。@HunterChristianDonahue,是的,我看到了你的编辑。修改代码,最后一行不是我们想要的;它应该是
[1,2,4,-1,5,6,-1,8]
。如果您的代码正在输出(我还没有测试过),那么就有问题了。