嵌套控件结构,平均脚本

时间:2014-02-10 15:59:29

标签: java

使用嵌套控制结构制作脚本,将任意数字从0到100平均,如果任何数字大于100或低于0,则会产生错误。

import java.util.Scanner;

public class ExerciseSix
{
public static void main( String[] args )
{

    Scanner dylan = new Scanner(System.in);

    int gradeCounter;
    int total;
    int grade;
    double average;

    total = 0;
    gradeCounter = 0;

    System.out.println( "Enter a grade or -1 to quit: " );
    grade = dylan.nextInt();

    while ( grade != -1 )
    {

        total = total + grade;
        gradeCounter = gradeCounter + 1;





        System.out.println( "Enter grade or -1 to quit: ");
        grade = dylan.nextInt();


        if ( grade > 100 );
        System.out.println( "Number too large");            

        if ( grade < 0 );
        System.out.println( "Number too small");
    }


    if ( gradeCounter != 0 )

    {

        average = (double) total / gradeCounter;


        System.out.printf( "Class average is %.2f", average );



    }

    else
        System.out.println( "No grades were entered" );

}

我没有得到任何编译错误,但是当我键入数字时,第一个数字正确进入。那么无论我在0到100之间键入什么数字,它都会说

“5  数字太大了  数字太小了  输入成绩或-1退出:“

我认为大数字也被添加到平均水平

1 个答案:

答案 0 :(得分:2)

删除if语句中的分号

变化

if ( grade > 100 );
    System.out.println( "Number too large");            

if ( grade < 0 );
    System.out.println( "Number too small");

if ( grade > 100 )
    System.out.println( "Number too large");            

if ( grade < 0 )
    System.out.println( "Number too small");

最佳做法是用花括号括起所有if语句,这样就不会出现任何意外行为

if ( grade > 100 ){
    System.out.println( "Number too large");  
}          

至于要添加到总数中的大数字,您需要在计算之前进行数据验证,即

while(grade != -1){
    if( grade > 100 || grade < 0) {
    //Message
    }
    else{
    //Total calculation
    }
}