首页 > 解决方案 > 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.

标签: java

解决方案


尝试:

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);

输出:

在此处输入图像描述

解释:

  1. 删除num = in.nextInt();iinfor (double i=a; i<=b; i++)将获得 和 之间的所有a数字b
  2. 替换sum += num;sum += i;

推荐阅读