提问人:Mayur Hovale 提问时间:11/15/2020 最后编辑:Arvind Kumar AvinashMayur Hovale 更新时间:1/18/2021 访问量:239
为什么 for 循环后不打印计数?[已结束]
Why the count is not printing after for loop? [closed]
问:
在每个循环之后并更新。在输入后,我没有得到任何输出。count
count1
Scanner
Scanner sc = new Scanner(System.in);
int t = sc.nextInt(); // t=1
while (t != 0) {
int n = sc.nextInt(); // n=5
int a[] = new int[n]; // a = { 1,2,5,6,7 }
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
int count = 0, count1 = 0;
for (int i = 0; i < n; i++) {
if ((a[i + 1] - a[i]) > 2) {
count++;
} else {
count1++;
}
}
// this doesn't get printed
System.out.println(count + 1 + " " + count1);
t--;
}
答:
0赞
Zahid Khan
11/15/2020
#1
int count=0,count1=0;
for (int i = 0; i < n; i++)
应替换为
int count=0,count1=0;
for (int i = 0; i < n-1; i++) {
您正在尝试访问内存位置,该位置是n+1
a[i + 1]
ArrayIndexOutOfBoundsException.
0赞
Razib
11/15/2020
#2
由于您尝试连续进行测试用例输入,因此仅在此处不起作用。我将在这里发布一个通用结构。请尝试以下方法 -t--
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for(int i = 0; i < t; i++){
int n = in.nextInt();
//do your stuff here
// now you could take input and process them t times
}
//finally don't forget to close the input stream.
in.close();
}
0赞
Arvind Kumar Avinash
11/15/2020
#3
以下代码块中的条件将导致 as when i = n - 1,将尝试从 i.e 中获取一个元素,因为 中的索引在 to 的范围内:ArrayIndexOutOfBoundsException
if ((a[i + 1] - a[i]) > 2)
a[n - 1 + 1]
a[n]
a[]
0
n - 1
for (int i = 0; i < n; i++) {
if ((a[i + 1] - a[i]) > 2)
你可以这样说
for (int i = 0; i < n -1 ; i++) {
if ((a[i + 1] - a[i]) > 2)
在此更正之后,下面给出了示例运行的结果:
1
5
1 2 5 6 7
2 3
这是因为 被执行为 ,而 while 只被执行 。count1++
1 2,
5 6
6 7
count++
2 5
评论
ArrayIndexOutOfBoundsException
for
i == n-1
if ((a[i + 1] - a[i]) > 2)
a[i+1]
i
n-1
System.out.println