我不知道在哪里放一个循环

时间:2015-06-05 03:49:48

标签: java

我尝试了do循环和while循环。我似乎无法弄清楚在哪里放置一个循环所以一旦程序完全运行我想让它问用户“是的我想继续”或“否”它结束。这是一个课程作业,我正在使用eclipse,它正确地解决了一些真正让我自己循环的事情。

代码

import java.util.Scanner;

public class studentgpa {
    public static void main(String[] args) {
        Scanner consoleInput = extracted();
        printGPA(consoleInput);     
    }
    public static void printGPA(Scanner input) {
        System.out.println("Enter a student record: ");
        String name = extracted().next();
        System.out.print("Enter Number of grades you will be entering: ");
        int count = extracted().nextInt();
        int sum = 0;
        System.out.println("Enter Grades: 95 enter 98 enter and so on ");
        for (int i = 1; i <= count; i++) {
            sum += extracted().nextInt();
        }
        double average = (double) sum / count;

        System.out.println(name + "'s grade is " + average);
    }
    private static Scanner extracted() {
        return new Scanner(System.in);
    }
}

3 个答案:

答案 0 :(得分:1)

你需要像这样在do while循环中包含main中的内容,并提示用户询问是否要继续

do {
    Scanner consoleInput = extracted();
    printGPA(consoleInput);
    System.out.println("Do you want to add another student? (Yes/No)");
    String continue = consoleInput.nextLine(); // storing the user's response
} while (continue.equals("Yes"));

答案 1 :(得分:0)

使用像这样的字符串

开始你的函数printGPA
String continueLoop="Yes";
while("Yes".equals(continueLoop)){
 ///put the code you already have
 continueLoop=extracted().next();
}

上面的代码将循环,直到您输入“是”以外的其他内容。

答案 2 :(得分:0)

如果您需要询问用户,则需要在loop begining添加printGPA

String ans="yes";
while(ans.equalsIgnoreCase("Yes")){//checks  the user input is yes or no
      //your code
      System.out.println("Do you want to continue?");
      ans=extracted().next();
 }

更改后,pringtGPA应如下所示

public static void printGPA(Scanner input)
{
        String ans="yes";
        while(ans.equalsIgnoreCase("Yes")){
            System.out.println("Enter a student record: ");
            String name = extracted().next();
            System.out.print("Enter Number of grades you will be entering: ");
            int count = extracted().nextInt();
            int sum = 0;
            System.out.println("Enter Grades: 95 enter 98 enter and so on ");
            for (int i = 1; i <= count; i++) {
                sum += extracted().nextInt();
            }
           double average = (double) sum / count;

           System.out.println(name + "'s grade is " + average);

           System.out.println("Do you want to continue?");
           ans=extracted().next();
        }//end of while loop
}

希望它有所帮助。快乐编码!!