【发布时间】:2018-06-25 15:52:14
【问题描述】:
这个问题来自https://www.hackerrank.com/,链接是https://www.hackerrank.com/challenges/java-list/problem。 在下面的代码中,while 循环运行了两次,根据问题我们需要输入 Q,Q 次操作要在声明的数组中执行。为此,我运行了两次循环,以便获得所需的结果。
import java.util.*;
public class javaList {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int i, x;
ArrayList L = new ArrayList(N);
for (i = 0; i < N; i++) {
L.add(sc.nextInt());
}
int Q = sc.nextInt();
i = 0;
// for normal running i have multiplied Q by 2 so that i can get the results
while (i < Q * 2) {
System.out.println("Loop: " + i);
String s = sc.nextLine();
int sz = L.size();
// code for checking insert
if (s.equals("Insert")) {
x = sc.nextInt();
int y = sc.nextInt();
//if the position i am looking exists then just replace
// i need to insert at index x of array L but array.size() gives one more than the last index
if ((sz - 1) >= x) {
L.add(x, y);
}
//if the position i am looking does not exist then create
else {
for (int j = sz; j <= x; j++) {
//add number to desired place
if (j == x)
L.add(y);
//in between the two endings of array and insertion adding default value 0
else
L.add(0);
}
}
//checking code for Delete
} else if (s.equals("Delete")) {
x = sc.nextInt();
//if the desired location exists then only replace
if ((sz - 1) >= x) {
L.remove(x);
}
}
i++;
}
for (i = 0; i < L.size(); i++) {
System.out.print(L.get(i) + " ");
}
}
}
我想知道为什么循环在一次运行中运行两次。
【问题讨论】:
-
我看到代码中有多个循环。哪个运行了两次,您希望它运行多少次?
-
对不起,先生,我会为特定任务制定方法。
-
While 循环。
-
while (i < Q * 2)将导致循环执行Q * 2次。这是你想要的吗? -
对于这个问题,我这样做了。 while(i
标签: java arrays loops arraylist while-loop