我写了一个小程序。
Сondition:“给定一个大小为n的数组。在数组的每个负数元素之后插入一个零值的元素。”我使用2个ArrayList数组解决了这个任务。我想知道是否有可能只使用一个阵列获得解决方案?
该计划的代码:
public class Task_108 {
public void Task108(){
System.out.println("Input size of array: ");
Scanner scn = new Scanner(System.in);
int sizeArr = scn.nextInt();
ArrayList<Integer> ArrIntNum = new ArrayList<>(sizeArr); // Declare array
Random rnd = new Random();
int val;
// Filling array random elements from -20 to 20
for(int i = 0; i < sizeArr; i++){
val = -20 + rnd.nextInt(41);
ArrIntNum.add(i, val);
}
// Output array on the screen
System.out.println(ArrIntNum.toString());
ArrayList<Integer> ArrWithZeroAftNegVal = new ArrayList<>(); // Declare once more array
// Adding zero after every negative number in array ArrIntNum and write in array ArrWithZeroAftNegVal
for(int i = 0; i < sizeArr; i ++){
if(ArrIntNum.get(i) < 0) {
ArrWithZeroAftNegVal.add(ArrIntNum.get(i));
ArrWithZeroAftNegVal.add(0);
}
else
ArrWithZeroAftNegVal.add(ArrIntNum.get(i));
}
// Output edited array on the screen
System.out.println(ArrWithZeroAftNegVal.toString());
}
}
答案 0 :(得分:0)
像这样:
import java.util.ArrayList;
public class Task_108 {
public void Task108(){
System.out.println("Input size of array: ");
Scanner scn = new Scanner(System.in);
int sizeArr = scn.nextInt();
ArrayList<Integer> arrIntNum = new ArrayList<Integer>(sizeArr); // Declare array
Random rnd = new Random();
// Filling array random elements from -20 to 20
for(int i = 0; i < arrIntNum.size(); i++)
arrIntNum.add(-20 + rnd.nextInt(41));
// Output array on the screen
System.out.println(arrIntNum);
// Adding zero after every negative number in array ArrIntNum
for(int i = 0; i < sizeArr; i++) {
if(arrIntNum.get(i) < 0)
arrIntNum.add(i + 1, 0);
}
// Output edited array on the screen
System.out.println(arrIntNum);
}
}
我也为您简化了代码。
答案 1 :(得分:0)
ListIterator
很自然地工作,允许在同一个数组上添加元素:
ListIterator<Integer> i = ArrIntNum.listIterator();
while (i.hasNext()) {
Integer value = i.next();
if (value < 0) i.add(0);
}