java - Why do i get Exception in thread "main" java.util.NoSuchElementException?
问题描述
I'm new at this, and having some trouble with my code. The thing is, it works, but i keep gettingthis "Exception in thread "main" java.util.NoSuchElementException" when i check my exercise in jet brains. But in my IDE it does work. This is the exercise = "Write a program that reads two numbers a a and b b from the keyboard and calculates and outputs to the console the arithmetic average of all numbers from the interval [a;b] [ a ; b ] , which are divisible by 3 3 .
In the example below, the arithmetic average is calculated for the numbers on the interval [−5;12] [ − 5 ; 12 ] . Total numbers divisible by 3 3 on this interval 6 6 : −3,0,3,6,9,12 − 3 , 0 , 3 , 6 , 9 , 12 . Their arithmetic average equals to 4.5"
The program works and returns the 4.5.
This is my code:
int a = in.nextInt();
int b = in.nextInt();
double divisible = 0;
int sum = 0;
double num =0;
for (double i = a; i<b; i ++) {
num = in.nextInt();
if (num%3==0) {
divisible = divisible +1;
sum += num;
}
}
double result = sum/divisible;
System.out.println(result);
Hope u can help me because I really wanna improve my skills and keep learning. Thank you for your time.
解决方案
尝试:
int a = sc.nextInt();
int b = sc.nextInt();
double count = 0;
double sum = 0;
for (double i=a; i<=b; i++) {
// Check if number is divisible by 3
if (i % 3 == 0) {
// Count total numbers
count += 1;
// Calculate sum
sum += i;
}
}
double result = sum / count;
System.out.println("Average: " + result);
输出:
解释:
- 删除
num = in.nextInt();
为i
infor (double i=a; i<=b; i++)
将获得 和 之间的所有a
数字b
。 - 替换
sum += num;
为sum += i;
。
推荐阅读
- python - 计算列表 2 中列表 1 中的项目的次数
- angular - 如何使用angularFire从firebase数据库中检索用户列表并且没有“密钥”?
- java - ConstraintLayout 以编程方式设置 constraintHeight_default
- file - 读取 Haskell 中的值和列表列表
- c# - If (Integer Console.Readline "" or null) 不起作用
- upgrade - 升级到 SugarCRM ver 8.0.0 Pro 后无法登录
- html - Angular Sticky Header 重叠内容
- python - 嵌入pytorch
- angular - 仅清除单个输入字段 angular6 模板驱动表单
- excel - Excel - 在 sumif 中用间接代替动态列名