java - 为什么在 for 循环后不打印计数?
问题描述
每次循环后都会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--;
}
解决方案
以下代码块中的条件将导致ArrayIndexOutOfBoundsException
当i = n - 1时,if ((a[i + 1] - a[i]) > 2)
将尝试从a[n - 1 + 1]
ie获取一个a[n]
您已经知道无效的元素,因为 in 的索引在toa[]
的范围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
这是因为count1++
被执行为1 2,
,5 6
而6 7
whilecount++
仅被执行为2 5
。
推荐阅读
- asp.net - 使用 ASp.net 核心从 appsettings.json 获取 Json 数组
- javascript - 如何检查事件是否可以从 GWT 代码中取消?
- r - 使用 lubridate 生成三个月的日期和时间
- php - 像使用字母字符串 bindParam 查询
- javascript - 像 doX(doY(doZ(data))) 这样的链接函数是不好的做法吗?
- php - SendGrid - 电子邮件不发送 / PHP
- neo4j - Neo4j: How Can I display the row position?
- google-apps-script - 将 Gmail api 与 Google 应用程序制造商集成
- r - 如何在 R 中更改箱线图的 x 轴(以便缩放)
- ios - iOS 请求始终授权仅首次显示权限警报