循环不会添加总数

时间:2014-02-12 17:52:42

标签: java

制作适合一名学生的成绩簿,以学生的名字作为输入。然后他们被要求将成绩分为三类:家庭作业,测验和考试。每个类别中的等级将被平均,最后,公式“最终平均值= 0.25 * HomeworkAvg + 0.25QuizAvg + 0.50TestAvg = 65

一切正常但但-1没有结束这个过程!这令人沮丧!

import java.util.Scanner; 

public class Assignment3

{
public static void main( String[] args ) 
{ 
    Scanner input = new Scanner( System.in );

    int homeworkGrades;
    int quizGrades;
    int testGrades;
    int choice;
    int total;
    double average;
    String name;

    total = 0;
    homeworkGrades = 0;

        System.out.println( "Enter 1 or 2: \n 1 - Average grades \n 2 - Quit" ); 
        choice = input.nextInt();

        if ( choice == 1 ) {
            System.out.println( "Enter the students name" );
            name = input.next();



            System.out.println( " What would you like to do? \n 1 - Homework grades \n 2 - Quiz grades \n 3 - Test grades " );
            choice = input.nextInt();

            {

                while ( choice == 1 ) {
                    System.out.println( "Enter a homework grade. Press -1 when finished" );
                    homeworkGrades += input.nextInt();

                    if ( homeworkGrades != -1 ) //it's something going on right here :s

                    if ( homeworkGrades == -1 )
                        System.out.println("Total for homework grades is " + homeworkGrades );      
                }
            }
        }

    else if ( choice == 2 ) {
        System.out.println( "Exiting program" );
    }

    else {
        System.out.println( "Invalid response, exiting program." ); 
    }       
}

}

3 个答案:

答案 0 :(得分:1)

您的代码if ( homeworkGrades != -1 )紧跟if ( homeworkGrades == -1 )后面 - 这可能不会按照您的意愿执行。

我建议始终在if语句周围添加大括号并使用正确的代码缩进来避免这样的错误 - 在阅读中检测它们会变得容易得多。

答案 1 :(得分:0)

( homeworkGrades == -1 )永远都是假的。这就是你的代码无效的原因。

将您的代码更改为:

while ( choice == 1 ) {
    int val = -2;
    System.out.println( "Enter a homework grade. Press -1 when finished" );
    while (val != -1) {
        val = input.nextInt();
        homeworkGrades += val;
    }
    System.out.println("Total for homework grades is " + homeworkGrades );
}

答案 2 :(得分:0)

代码包含循环条件:

while ( choice == 1 ) - >如果选择值为1,那么thr将是无限循环。

首先更新此内容并在

中添加括号
if ( homeworkGrades != -1 )
{
 // Add ..
}
if ( homeworkGrades == -1 )
{
   System.out.println("Total for homework grades is " + homeworkGrades );   
}