如何在封闭开关中从 Do While 中返回 Integer ArrayList 的平均值

How to return mean from Integer ArrayList in Do While enclosed switch

提问人:Hack-R 提问时间:10/4/2015 更新时间:10/4/2015 访问量:185

问:

我正在尝试编写一个脚本来记录保龄球得分,并部分使用 Java 集合框架来汇总存储的记录。

这是一项正在进行的工作,但到目前为止,我所拥有的是:

package mod6;
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
//import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;

/**
 * @author Jason
 *Use the collections framework and generic types to create a bowling score tracker collection. 
 *Design a data structure that will be used as elements in a collection. 
 *Each element should contain a unique name of the bowler and a list of scores and dates of the games they have played.

Then print to the screen each:

    Bowler name
    Number of games
    Average score of all of the games
    Score of their last game
    Date of their last game

 */



public class Bowling {
    // Function from StackOverflow to get mean
    private static double calculateAverage(List <Integer> marks) {
          Integer sum = 0;
          if(!marks.isEmpty()) {
            for (Integer mark : marks) {
                sum += mark;
            }
            return sum.doubleValue() / marks.size();
          }
          return sum;
        }

          public static void main(String[] args) throws IOException {
                BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in), 1);

                // Local variables
                int swValue;
                int gameUID = 1;

                do{
                // Display menu graphics
                System.out.println("============================");
                System.out.println("|   BOWLING SCORE TRACKER  |");
                System.out.println("============================");
                System.out.println("| Options:                 |");
                System.out.println("|        1. Enter a Game   |");
                System.out.println("|        2. Summarize Games|");
                System.out.println("|        3. Exit           |");
                System.out.println("============================");
                swValue = Keyin.inInt(" Select option: ");
                ArrayList<String> names = new ArrayList<String>();  // Use Java Collections Framework for bowling player names
                ArrayList<Integer> uid  = new ArrayList<Integer>(); // Use Java Collections Framework for bowling game UID
                ArrayList<Integer> scores=new ArrayList<Integer>(); // Use Java Collections Framework for bowling game scores

                // Switch construct
                switch (swValue) {
                case 1:                                               // Accept user input to record a game
                  System.out.println("Let's add a game!");


                  // Add game ID
                  uid.add(gameUID);
                  gameUID++;                                          // Increment the bowling game UID to prepare for additional game records

                  // Add names
                  System.out.println("");
                  System.out.println("Please Bowler 1's name then press ENTER");
                  String a = stdin.readLine();                        // get a line of user input as a String player name
                  names.add(a);                                       // add it to the names collection/ArrayList
                  System.out.println("Please Bowler 2's name then press ENTER");
                  String b = stdin.readLine();                        // get a line of user input as a String player name
                  names.add(b);                                       // add it to the names collection/ArrayList

                  // Add scores
                  System.out.println("Please Bowler 1's score then press ENTER");
                  Scanner in = new Scanner(System.in);
                  int num = in.nextInt();                             // get a line of user input for player's score
                  scores.add(num);                                    // add it to the names collection/ArrayList

                  System.out.println("Please Bowler 2's score then press ENTER");
                      num = in.nextInt();                             // get a line of user input for player's score
                  scores.add(num);                                    // add it to the names collection/ArrayList

                    // Print Game UID
                    System.out.println("Game ID:" + (gameUID - 1));   // The - 1 is because I incremented gameUID already
                    // Print players' names
                    names.stream().forEach((string) -> {
                        System.out.println("Player: " + string);
                    });

                    // Print players' scores
                    scores.stream().forEach((int1) -> {
                        System.out.println("Player Score: " + int1);
                    });
                  break;
                case 2:
                  System.out.println("Allow me to summarize your game(s):");
                  System.out.println("The average score from all of your games is:");
                  double mean = calculateAverage(scores);
                  System.out.print(mean);
                  System.out.println("");
                  break;
                case 3:
                  System.out.println("Exit selected");
                  break;
                default:
                  System.out.println("Invalid selection");
                }
        }             while(swValue != 3);
    }
}

//**********************************************************
//**********************************************************
//Program: Keyin
//Citation: I got this from 
//http://www.java2s.com/Code/Java/Development-Class/Javaprogramtodemonstratemenuselection.htm
//Topics:
//1. Using the read() method of the ImputStream class
//  in the java.io package
//2. Developing a class for performing basic console
//  input of character and numeric types
//**********************************************************
//**********************************************************
class Keyin {

//*******************************
//   support methods
//*******************************
//Method to display the user's prompt string
public static void printPrompt(String prompt) {
  System.out.print(prompt + " ");
  System.out.flush();
}

//Method to make sure no data is available in the
//input stream
public static void inputFlush() {
  int dummy;
  int bAvail;

  try {
    while ((System.in.available()) != 0)
      dummy = System.in.read();
  } catch (java.io.IOException e) {
    System.out.println("Input error");
  }
}

//********************************
//  data input methods for
//string, int, char, and double
//********************************
public static String inString(String prompt) {
  inputFlush();
  printPrompt(prompt);
  return inString();
}

public static String inString() {
  int aChar;
  String s = "";
  boolean finished = false;

  while (!finished) {
    try {
      aChar = System.in.read();
      if (aChar < 0 || (char) aChar == '\n')
        finished = true;
      else if ((char) aChar != '\r')
        s = s + (char) aChar; // Enter into string
    }

    catch (java.io.IOException e) {
      System.out.println("Input error");
      finished = true;
    }
  }
  return s;
}

public static int inInt(String prompt) {
  while (true) {
    inputFlush();
    printPrompt(prompt);
    try {
      return Integer.valueOf(inString().trim()).intValue();
    }

    catch (NumberFormatException e) {
      System.out.println("Invalid input. Not an integer");
    }
  }
}

public static char inChar(String prompt) {
  int aChar = 0;

  inputFlush();
  printPrompt(prompt);

  try {
    aChar = System.in.read();
  }

  catch (java.io.IOException e) {
    System.out.println("Input error");
  }
  inputFlush();
  return (char) aChar;
}

public static double inDouble(String prompt) {
  while (true) {
    inputFlush();
    printPrompt(prompt);
    try {
      return Double.valueOf(inString().trim()).doubleValue();
    }

    catch (NumberFormatException e) {
      System.out
          .println("Invalid input. Not a floating point number");
    }
  }
}
}

结果是:

============================
|   BOWLING SCORE TRACKER  |
============================
| Options:                 |
|        1. Enter a Game   |
|        2. Summarize Games|
|        3. Exit           |
============================
 Select option:  1
Let's add a game!

Please Bowler 1's name then press ENTER
Marky
Please Bowler 2's name then press ENTER
Mark
Please Bowler 1's score then press ENTER
10
Please Bowler 2's score then press ENTER
20
Game ID:1
Player: Marky
Player: Mark
Player Score: 10
Player Score: 20
============================
|   BOWLING SCORE TRACKER  |
============================
| Options:                 |
|        1. Enter a Game   |
|        2. Summarize Games|
|        3. Exit           |
============================
 Select option:  2
Allow me to summarize your game(s):
The average score from all of your games is:
0.0
============================
|   BOWLING SCORE TRACKER  |
============================
| Options:                 |
|        1. Enter a Game   |
|        2. Summarize Games|
|        3. Exit           |
============================
 Select option:  3
Exit selected

而我想要的结果是:

============================
|   BOWLING SCORE TRACKER  |
============================
| Options:                 |
|        1. Enter a Game   |
|        2. Summarize Games|
|        3. Exit           |
============================
 Select option:  1
Let's add a game!

Please Bowler 1's name then press ENTER
Marky
Please Bowler 2's name then press ENTER
Mark
Please Bowler 1's score then press ENTER
10
Please Bowler 2's score then press ENTER
20
Game ID:1
Player: Marky
Player: Mark
Player Score: 10
Player Score: 20
============================
|   BOWLING SCORE TRACKER  |
============================
| Options:                 |
|        1. Enter a Game   |
|        2. Summarize Games|
|        3. Exit           |
============================
 Select option:  2
Allow me to summarize your game(s):
The average score from all of your games is:
**15.0**
============================
|   BOWLING SCORE TRACKER  |
============================
| Options:                 |
|        1. Enter a Game   |
|        2. Summarize Games|
|        3. Exit           |
============================
 Select option:  3
Exit selected
爪哇岛

评论

0赞 Yassin Hajaj 10/4/2015
两者之间有什么区别?平均数?
0赞 Hack-R 10/4/2015
平均得分 -- 0 对 15.0

答:

3赞 Yassin Hajaj 10/4/2015 #1

你必须把这条线

ArrayList<Integer> scores=new ArrayList<Integer>();

在 do while 循环之外

ArrayList<Integer> scores=new ArrayList<Integer>();
    do{

    // Switch and so on

    }while (test);

因为您在每个循环中重新初始化它并删除以前的值

评论

1赞 Yassin Hajaj 10/4/2015
@Hack-R不客气:)别忘了接受答案
1赞 Hack-R 10/4/2015
我不会的。SO 让我再等 5 分钟,然后再将其标记为答案。
0赞 Yassin Hajaj 10/4/2015
@Hack-R哈哈。好的,谢谢你,祝你周末愉快