为什么IDEA运行时会有错误

请教一下,刚入门Java遇到的问题:一样的程序,记事本通过cmd指令编译可以运行但是IDEA显示编译错误

但是IDEA在编译前显示没有错误,在编译后才显示错误。

问题相关代码

import java.util.Scanner;
public class text{
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("please enter a number of :");
int number = input.nextInt();
int positive = 0, negetive = 0, count = 1, total = 0;
double average;
while (number != 0) {
if (number != 0) {
positive = (number > 0) ? (positive += 1) : (positive -= 1);
negetive = (number < 0) ? (negetive += 1) : (negetive -= 1);
} else if (number == 0)
break;
count++;
total += number;
number = input.nextInt();
}
average = total / count;
System.out.print("the amount of number is " + total + "and the average is " + average
+ "and count is " + count);
}}

运行结果及报错内容

please enter a number of :
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at text.main(text.java:10)

Process finished with exit code 1

我的解答思路和尝试过的方法

我看网上是把int number = input.nextInt();放到循环里,能解决是可以解决

我想要达到的结果

但是为啥会这样。就是记事本可以运行但是IDEA显示编译错误。请问是为什么?

img


运行之后,除了平均数计算错误外,其它都是没问题。解决平均数计算错误,只需要将count初始化值改为0即可。

编译器检查规则价格太高,建议调低就好了

帮你重构了下,你看下

public class Basic_11_text {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("please enter a number of :");
        int number = input.nextInt();
        int positive = 0, negetive = 0, count = 1, total = 0;
        double average;
        while (number != 0) {
            positive = (number > 0) ? positive + 1 : positive - 1;
            negetive = (number < 0) ? negetive + 1 : negetive - 1;
            count++;
            total += number;
            number = input.nextInt();
        }
        average = total / count;
        System.out.print("the amount of number is " + total);
        System.out.print("and the average is " + average);
        System.out.print("and count is " + count);
    }
}