问题与java代码的else语句。我在第 17 行不断收到错误

该行有多个标记

  • 赋值的左侧必须是变量

  • 语法错误,插入AssignmentOperator Expression以完成作业

  • 语法错误,请插入“;” 完成声明

public class TestClass {

    public static void main(String [] args) {

        int n;

        int numberofInputs;

        int Sum;     


        Scanner input = new Scanner(System.in);


            while ((n = input.nextInt()) !=0) {

                if(n>0) {

                    Sum +=n;

                    numberofInputs++;

                }

                else (n<0) {         //line 17 errors

                    System.out.print("error");

                }


            }

            //avg = sum/n

        System.out.print(Sum/numberofInputs); 

    }

}


jeck猫
浏览 145回答 3
3回答

噜噜哒

你不应该对其他人施加条件else (n<0)&nbsp;只需使用if (n>0) {…} else {…}

海绵宝宝撒

您不能将条件与 else 一起使用。尝试删除条件或使用 else if。正确且受控的代码是:&nbsp; &nbsp;public static void main(String [] args) {&nbsp; &nbsp; &nbsp; &nbsp; int n;&nbsp; &nbsp; &nbsp; &nbsp; int numberofInputs;&nbsp; &nbsp; &nbsp; &nbsp; int Sum;&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; Scanner input = new Scanner(System.in);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; while ((n = input.nextInt()) !=0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(n>0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Sum +=n;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; numberofInputs++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else if (n<0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//Use 'else if' not 'else'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print("error");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //avg = sum/n&nbsp; &nbsp; &nbsp; &nbsp; System.out.print(Sum/numberofInputs);&nbsp;&nbsp; &nbsp; }

回首忆惘然

在java中一个额外的if条件语法是...else&nbsp;if(n&nbsp;>&nbsp;0)...所以你需要添加它
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java