案件中的成绩册循环

时间:2014-02-12 15:09:03

标签: java

我正在编写一个程序询问用户是否想要平均成绩或退出,然后要求学生姓名,然后它将允许用户将成绩输入3个不同的类别,它将循环直到他准备好退出并按-1。

我创建了我的开关,一切都工作得很好,但是如何在第1,2或3个案例中循环?案例1将是平均作业成绩,它将平均那些作业成绩并显示它们,然后它将转移到案例2,平均那些成绩和显示,这是测验成绩。然后它将移动到测试成绩,用户输入成绩,按-1,平均他们,然后在第三个案例之后它将使用这个公式平均所有学生的成绩:

Final Average = 0.25*HomeworkAvg + 0.25*QuizAvg + 0.50*TestAvg = 64

如何添加循环以继续询问成绩,然后继续?我觉得我有点走上正轨。谢谢!

import java.util.Scanner;

public class Assignment3 {

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

        double homework;
        double quiz;
        double test;
        int choice;
        int choiceTwo;
        String name;

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

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

            name = dylan.next();

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

            switch (choiceTwo) {
                case 1:
                    System.out.println("Enter Homework Grades");
                    break;
                case 2:
                    break;
                case 3:
                    break;
                default:
                    if (choiceTwo == -1 || choiceTwo != 1 || choiceTwo != 2 || choiceTwo != 3) ;
                    System.out.println("Exiting program");
                    break;
            }

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

    }

}

2 个答案:

答案 0 :(得分:1)

你需要添加一些东西:

boolean complete = false;

while(!complete) {

    //Put your switch stuff here.
    if(choice == -1) complete = true;

}

答案 1 :(得分:0)

您需要添加一个循环。只要满足某些条件,while循环就非常适合循环。在您的情况下,只要choice不是-1,就应该循环播放。

就像将(if choice == 1)更改为while (choice != -1)一样简单,删除else ifelse;您还应该继续将用户输入的内容分配给choice,而不是创建choiceTwo

您也可以继续在同一while上使用嵌套的choice循环!

while ( choice != -1 ) {
    switch (choice) {
        case 1:
            System.out.println("Enter Homework Grades");
            // add grades to a list until -1 is typed
            List<Integer> grades = new ArrayList<Integer>();
            while (choice != -1) {
                System.out.println("Enter a grade, or -1 to stop entering grades: ");
                choice = dylan.nextInt();
                if (choice > -1) {
                    grades.add(choice);
                }
            }
            // now calculate your average and do whatever else
            break;
        // more cases
    }
    choice = dylan.nextInt();
}

System.out.println( "Exiting program." );

您的代码在初始菜单中说明您必须键入2才能退出,但是一旦循环开始,您必须输入-1才能退出。我可以建议你改变吗?否则,你将不得不做像Pete所建议的那样,这不太优雅。

相关问题