Java program to keep track of team score - java

Edit: I updated the below code from before and am able to get the individual quarter amounts. I'm not sure why my "teamTotal" method is not adding together all four quarters. I figured it was supposed to iterate over all of the team 1 and 2 scores and add them together to get the separate totals. However, when I run it I am only getting zero returned back to me.
public class Offical4 {
static int team1[] = new int[4];
static int team2[] = new int[4];
static int teamOneScore = 0;
static int teamTwoScore = 0;
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
for (int Quarter = 1; Quarter <= 4; Quarter++) {
System.out.println("Quarter " + Quarter);
for (int qtr = 0; qtr < 4; qtr++) {
quarterScoring(team1, team2, qtr);
}
System.out.println("Q"+ (Quarter) + " score for team 1 is " + teamOneScore);
System.out.println("Q"+ (Quarter) + " score for team 2 is " + teamTwoScore);
System.out.println("\n");
}
int team1Total = teamTotal(team1);
int team2Total = teamTotal(team2);
displayGameResults(team1, team2);
System.out.println("Team one total is " + team1Total);
}
static int pointsScored;
static int teamTotal(int[] team) {
int sum = 0;
for(int i =0; i < team.length; i++)
sum += team[i];
return sum;
}
static void quarterScoring(int[] team1, int[] team2, int qtr) {
System.out.println("What team scored?(1 or 2)");
int scoreResult = keyboard.nextInt();
System.out.println("How many points did they score (1,2, or 3)");
int pointsScored = keyboard.nextInt();
if (scoreResult == 1) {
teamOneScore += pointsScored;
} else if (scoreResult == 2) {
teamTwoScore += pointsScored;
}
if (scoreResult > 2) {
System.out.println("Invalid team - quarter has ended.");
}
}
static void displayGameResults(int[] team1, int[] team2) {
System.out.println("Team 1 score is " + teamOneScore);
System.out.println("Team 2 score is " + teamTwoScore);
if(teamOneScore > teamTwoScore){
System.out.println("Team one is the winner");
}
else{
System.out.println("Team two Two wins");
}
}
}

Use the two arrays at the top of your code to keep track of the score for each team in each quarter. Then to get their totals add the values of the array up. You can use an enhanced for loop for that.

There are many way to keep track total point of each team, one idea as bellow
public class Main {
static int team1[] = new int[4]; // define here
static int team2[] = new int[4]; // define here
static int teamOneScore = 0; // define here
static int teamTwoScore = 0; // define here
static Scanner keyboard = new Scanner(System.in);
...
Then you can
System.out.println("What team scored?(1 or 2)");
int iTeam = keyboard.nextInt();
System.out.println("How many points did they score (1,2, or 3)");
int pointsScored = keyboard.nextInt();
if (iTeam == 1) {
teamOneScore += pointsScored; // Total score of Team 1
}
else if (iTeam == 2) {
teamTwoScore += pointsScored; // Total score of Team 2
}
And
System.out.println("Team 1 score is " + teamOneScore);
System.out.println("Team 2 score is " + teamTwoScore);
One more thing, I think you need to validate what input value is before do anything.

Related

How can I find the highest, lowest, and average value of all test scores within my loop?

Good afternoon, or whenever you are reading this. I am trying to figure out how I can find the minimum, highest, and average of test scores that a user enters.
I have a loop that keeps track of a sentinel value, which in my case is 999. So when the user enters 999 it quits the loop. I also have some level of data validation by checking if the user entered over 100 or under 0 as their input. However, my question is, how can I implement a way to get this code to find the values I need for my user inputs. My code is as follows:
import java.util.Scanner;
public class TestScoreStatistics
{
public static void main(String[] args)
{
Scanner scn = new Scanner(System.in);
int testScore;
double totalScore = 0;
final int QUIT = 999;
final String PROMPT = "Enter a test score >>> ";
int lowScore;
int highScore;
String scoreString = "";
int counter = 0;
System.out.print(PROMPT);
testScore = scn.nextInt();
while (testScore != QUIT)
{
if (testScore < 0 || testScore > 100 )
{
System.out.println("Incorect input field");
}
else
{
scoreString += testScore + " ";
counter++;
}
System.out.print(PROMPT);
testScore = scn.nextInt();
}
System.out.println(scoreString);
System.out.println(counter + " valid test score(s)");
}
}
While keeping your code pretty much the same, you could do it like this:
import java.util.Scanner;
public class TestScoreStatistics
{
public static void main(String[] args)
{
Scanner scn = new Scanner(System.in);
int testScore;
double totalScore = 0;
final int QUIT = 999;
final String PROMPT = "Enter a test score >>> ";
int lowScore = 100; //setting the low score to the highest score possible
int highScore = 0; //setting the high score to the lowest score possible
String scoreString = "";
int counter = 0;
System.out.print(PROMPT);
testScore = scn.nextInt();
while (testScore != QUIT)
{
if (testScore < 0 || testScore > 100 )
{
System.out.println("Incorect input field");
}
else
{
scoreString += testScore + " ";
counter++;
//getting the new lowest score if the testScore is lower than lowScore
if(testScore < lowScore){
lowScore = testScore;
}
//getting the new highest score if the testScore is higher than highScore
if(testScore > highScore){
highScore = testScore;
}
totalScore += testScore; //adding up all the scores
}
System.out.print(PROMPT);
testScore = scn.nextInt();
}
double averageScore = totalScore / counter; //getting the average
}
This will check if the testScore is higher or lower than the highest and lowest scores. This program will also add all the scores together and divide them by the counter (which is how many tests there are) to get the average.
This is how I would do this.
// defines your prompt
private static String PROMPT = "Please enter the next number> ";
// validation in a separate method
private static int asInteger(String s)
{
try{
return Integer.parseInt(s);
}catch(Exception ex){return -1;}
}
// main method
public static void main(String[] args)
{
Scanner scn = new Scanner(System.in);
System.out.print(PROMPT);
String line = scn.nextLine();
int N = 0;
double max = 0;
double min = Integer.MAX_VALUE;
double avg = 0;
while (line.length() == 0 || asInteger(line) != -1)
{
int i = asInteger(line);
max = java.lang.Math.max(max, i);
min = java.lang.Math.min(min, i);
avg += i;
N++;
// new prompt
System.out.print(PROMPT);
line = scn.nextLine();
}
System.out.println("max : " + max);
System.out.println("min : " + min);
System.out.println("avg : " + avg/N);
}
The validation method will (in its current implementation) allow any integer number to be entered. As soon as anything is entered that can not be converted into a number, it will return -1, which triggers a break from the main loop.
The main loop simply keeps track of the current running total (to calculate the average), and the maximum and minimum it has seen so far.
Once the loop is exited, these values are simply printed to System.out.
With minimal changes of your code:
public class Answer {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int testScore;
final int QUIT = 999;
final String PROMPT = "Enter a test score >>> ";
int maxScore = Integer.MIN_VALUE;
int minScore = Integer.MAX_VALUE;
double totalScore = 0;
double avgScore = 0.0;
int counter = 0;
System.out.print(PROMPT);
testScore = scn.nextInt();
while (testScore != QUIT) {
if (testScore < 0 || testScore > 100) {
System.out.println("Incorect input field");
} else {
counter++;
System.out.println("The number of scores you entered is " + counter);
//test for minimum
if(testScore < minScore) minScore = testScore;
System.out.println("Current minimum score = " + minScore);
//test for maximum
if(testScore > maxScore) maxScore = testScore;
System.out.println("Current maximum score = " + maxScore);
//calculate average
totalScore += testScore;
avgScore = totalScore / counter;
System.out.println("Current average score = " + avgScore);
}
System.out.print(PROMPT);
testScore = scn.nextInt();
}
}
}

problems with dice game

whenever the code goes through the compiler it prints out the same number an infinite amount of times, i need it to compile random numbers several times. I tried to use the while loop to print out more times. However it just prints out the same number. The purpose of the game is for two players (and AI and one person), to compete to first reach 100 points, whenever a player gets two 1's the points will reset.
class piggame {
public static void main(String[] args) {
Dice d1 = new Dice();
d1.rolls();
int dave = d1.rolls();
Dice d2 = new Dice();
d2.rolls();
int joe = d2.rolls();
Dice d3 = new Dice();
d3.rolls();
int kurt = d1.rolls() + d2.rolls();
int sum1 = d1.rolls() + d2.rolls();
sum1 += d1.rolls() + d2.rolls();
while (dave != 1 && joe != 1){
System.out.println("you have rolled " + kurt);
}
}
}
class Dice {
public int rolls() {
Random r = new Random();
return r.nextInt(6) +1;
}
}
You should call rolls() inside loop. At snippet you pasted rolls are made once before the loop and then inside it you just printing this one roll result (which indeed will be infinite loop OR won't execute in case of rolls being ones right away, as rolls are never made again when you inside this while).
This code is not perfect, but it should solve your problem.
public static void main(String[] args) {
int dave = 0;
int joe = 0;
int kurt = 0;
while (dave != 1 && joe != 1){
Dice d1 = new Dice();
d1.rolls();
dave = d1.rolls();
Dice d2 = new Dice();
d2.rolls();
joe = d2.rolls();
Dice d3 = new Dice();
d3.rolls();
kurt = d1.rolls() + d2.rolls();
int sum1 = d1.rolls() + d2.rolls();
sum1 += d1.rolls() + d2.rolls();
System.out.println("you have rolled " + kurt);
}
}
import java.util.Random;
class PigGame
{
public static void main(String[] args)
{
int dave = 0;
int joe = 0;
int kurt = 0;
int roll_count = 0;
while (dave != 1 && joe != 1)
{
System.out.println("-----------------------------------------------");
System.out.println("Roll number: " + roll_count++);
System.out.println("-----------------------------------------------");
dave = new Dice().roll();
joe = new Dice().roll();
kurt = new Dice().roll();
System.out.println("Dave rolled: " + dave);
System.out.println("Joe rolled: " + joe);
System.out.println("Kurt rolled: " + kurt);
System.out.println("");
}
}
}
class Dice {
public int roll() { return new Random().nextInt(6) + 1; }
}
I don't think you're providing a solution to the given requirement:
Two players (but you have included three players - Joe, Dave and Kurt).
If a player rolls two consecutive ones, that player's score is reset (e.g. if player Dave rolls a one and then rolls another one on his next turn, his score is reset to 0).
In my previous answer, I was only trying to tidy up your code. I wasn't looking at the actual requirement.
You haven't mentioned if a player gets a single point per roll of the dice, or if the value of what they roll is added to their score. I'm going to assume it's the latter.
You should include another class called "Player". The Player class would contain variables to store what the current roll was, what the previous roll was, and the player's current score. It should also include methods to roll the dice, check if the player has reached a score of 100, check if a player has rolled two consecutive ones.
Here's a very simple implementation (that will tell you which player wins at the end, and how many points the winner has won by):
import java.util.Random;
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
class PigGame
{
public static void main(String[] args)
{
Player player1 = new Player("Dave");
Player player2 = new Player("Joe");
int roll_count = 0;
while (!player1.reachedFinishingScore() && !player2.reachedFinishingScore())
{
int p1_roll = player1.roll();
int p2_roll = player2.roll();
System.out.println("-----------------------------------------------------");
System.out.println("Roll number: " + roll_count++);
System.out.println("-----------------------------------------------------");
System.out.println(player1.get_name() + " rolled: " + p1_roll + ". Total Score: " + player1.get_score());
System.out.println(player2.get_name() + " rolled: " + p2_roll + ". Total Score: " + player2.get_score());
System.out.println("");
}
if (player1.get_score() == player2.get_score())
System.out.println("It was a draw!");
else if (player1.get_score() > player2.get_score())
System.out.println(player1.get_name() + " wins by " + (player1.get_score() - player2.get_score()) + " points!");
else
System.out.println(player2.get_name() + " wins by " + (player2.get_score() - player1.get_score()) + " points!");
System.out.println("");
}
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
class Dice {
public int roll() { return new Random().nextInt(6) + 1; }
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
class Player
{
private String name; // Player's name.
private int prev_roll = 0; // Value of Player's previous roll.
private int curr_roll = 0; // Value of Player's current roll.
private int score = 0; // The Player's score.
public Player(String name) { this.name = name; }
public int roll()
{
int curr_roll = new Dice().roll();
this.prev_roll = this.curr_roll; // Make previous roll value of last current roll.
this.curr_roll = curr_roll; // Set value of current roll to what was just rolled.
this.score += curr_roll;
if (rolledTwoOnes()) this.score = 0;
return curr_roll;
}
private boolean rolledTwoOnes() { return (this.prev_roll == 1 && this.curr_roll == 1); }
public boolean reachedFinishingScore() { return this.score >= 100; }
public int get_score() { return score; }
public String get_name() { return this.name; }
}
The above implementation could be improved by not "hard-coding" player1 and player2. Instead, you could use an array of players, which would make it easier to not limit the number of players (i.e. you could have 100 players).
Okay, last one (I promise):
import java.util.Random;
import java.util.Arrays;
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
class Config
{
public static final int NUM_OF_PLAYERS = 10;
public static final int NUM_OF_DICE_FACES = 6;
public static final int WINNING_SCORE = 100;
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
class PigGame
{
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
public static void create_players(Player[] p, int num_players)
{
for (int i = 0; i < num_players; i++)
p[i] = new Player("Player " + String.format("%02d", i + 1));
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
public static void all_players_roll_dice(Player[] p)
{
for (int i = 0; i < p.length; i++)
p[i].roll();
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
public static boolean no_winners(Player[] p)
{
int i = 0;
boolean bWinner = false;
while (i < p.length && (bWinner = !p[i].reachedFinishingScore()))
i++;
return bWinner;
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
public static void display_roll_details(Player[] p, int current_roll)
{
System.out.println("\n--------------------------------------------------------");
System.out.println("CURRENT ROLL: " + (current_roll + 1));
System.out.println("--------------------------------------------------------");
for (int i = 0; i < p.length; i++)
System.out.println(p[i].get_name() + " rolled: " + p[i].get_roll() +
". Score: " + p[i].get_score());
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
public static void display_final_scores(Player[] p, int roll_count)
{
System.out.println("\n\n**********************************************************");
System.out.println("FINAL SCORES AFTER " + roll_count + " ROLLS (HIGHEST TO LOWEST):");
System.out.println("**********************************************************\n");
for (int i = 0; i < p.length; i++)
{
Arrays.sort(p);
System.out.println(p[i].get_name() + " scored: " + p[i].get_score());
}
System.out.println("\n\nDon't be a player hater!\n\n");
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
public static void main(String[] args)
{
Player[] players = new Player[Config.NUM_OF_PLAYERS];
create_players(players, Config.NUM_OF_PLAYERS);
int roll_count = 0;
while (no_winners(players))
{
all_players_roll_dice(players);
display_roll_details(players, roll_count++);
}
display_final_scores(players, roll_count);
}
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
class Dice {
public int roll() { return new Random().nextInt(Config.NUM_OF_DICE_FACES) + 1; }
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
class Player implements Comparable<Player>
{
private String name; // Player's name.
private int prev_roll = 0; // Value of Player's previous roll.
private int curr_roll = 0; // Value of Player's current roll.
private int score = 0; // The Player's score.
public Player(String name) { this.name = name; }
public int roll()
{
int curr_roll = new Dice().roll();
this.prev_roll = this.curr_roll; // Make previous roll value of last current roll.
this.curr_roll = curr_roll; // Set value of current roll to what was just rolled.
this.score += curr_roll;
if (rolledTwoOnes()) this.score = 0;
return curr_roll;
}
private boolean rolledTwoOnes() { return (this.prev_roll == 1 && this.curr_roll == 1); }
public boolean reachedFinishingScore() { return this.score >= Config.WINNING_SCORE; }
public int get_score() { return this.score; }
public int get_roll() { return this.curr_roll; }
public String get_name() { return this.name; }
// For sorting the array (from highest scores to lowest).
#Override
public int compareTo(Player p)
{
return ((Integer)p.get_score()).compareTo(((Integer)get_score()));
}
}
Using the above, you can easily alter the number of players, number of dice faces, and the score that needs to be reached for a win.

How to compare variables in a loop, java

I have to design a program to simulate players rolling three dice for a number of rounds. Each dice throw is given points. I have to diplay for each round the dice values, and number of points for each player for those values and the winner of each round (the player with the highest points for that round, or no-one if they are the same).
I have implemented the points calculator, but I dont know how to display the winner of each round. Also, I am displaying the output vertically when it is supposed to be horizontally.
I think maybe comparing the values inside the loop in the game class may work. P.S. I am new in java, please make any suggestions to change the code if there is a better solution.
This is waht my program is displaying
round 1--> player 1: 2 4 5 points: 11
round 2--> player 1: 2 3 5 points: 10
round 3--> player 1: 2 4 6 points: 12
round 4--> player 1: 4 4 6 points: 34
round 5--> player 1: 3 4 5 points: 52
.
round 1--> player 2: 3 5 5 points: 33
round 2--> player 2: 3 6 6 points: 35
round 3--> player 2: 2 3 4 points: 49
round 4--> player 2: 1 1 3 points: 25
round 5--> player 2: 1 2 4 points: 7
This is what it is supposed to display
Round 1 Player 1: 1 3 3 points: 27 Player 2: 1 4 5 points: 10 Round winner is player 1
Round 2 Player 1: 1 2 5 points: 8 Player 2: 1 3 6 points: 10 Round winner is player 2
Round 3 Player 1: 1 4 4 points: 29 Player 2: 4 5 6 points: 55 Round winner is player 2
Round 4 Player 1: 1 3 5 points: 9 Player 2: 1 5 5 points: 31 Round winner is player 2
Round 5 Player 1: 3 6 6 points: 35 Player 2: 2 2 4 points: 28 Round winner is player 1
Total wins: Player 1: 2/ Player 2: 3
Total points: Player 1: 108/ Player 2: 134
Average points per round: Player 1: 21.6/ Player 2: 26.8
Overall points winner is player 2.
Main code
import java.util.Scanner;
public class Game {
// ------------------- FIELDS ------------------------
// Create instance of Scanner class
public static Scanner input = new Scanner(System.in);
// variables
public static ThreeDiceScorer thrdiesc;
public static int diceArray [];
// ------------------ METHODS ------------------------
public static void main(String[] args) {
int rounds; // input by user
int players; // input by user
System.out.print("Please input number of rounds (grater or equal than 0) --> ");
rounds = input.nextInt();
System.out.print("\n");
System.out.print("Please input number of rounds (grater or equal than 0) --> ");
players = input.nextInt();
System.out.print("\n");
for (int p = 0; p < players; p++) { //loop for players
for (int r = 0; r < rounds; r++) { // loop for number of rounds
int diceArray [] = new int [3];
for (int i = 0; i < diceArray.length; i++) { // loop for random Array
diceArray [i] = 1 + (int)(6 * Math.random());
}
// Create new ThreeDice and calculator instances
thrdiesc = new ThreeDiceScorer(diceArray [0], diceArray [1], diceArray [2]);
//Calculate
thrdiesc.getDie1();
thrdiesc.getDie2();
thrdiesc.getDie3();
thrdiesc.threeSame();
thrdiesc.runOfThree();
thrdiesc.pair();
thrdiesc.allDifferent();
thrdiesc.calcTotalPoints();
thrdiesc.printResult(p,r);
}
System.out.print("\n");
}
}//end Main Method
}// end Class
ThreeDice class
public class ThreeDice {
// ---------------------- ATTRIBUTES ---------------------
protected int die1;
protected int die2;
protected int die3;
// ------------------ CONSTRUCTOR -------------------
public ThreeDice(int s1, int s2, int s3) {
// This puts the three dice values in ascending order.
int tmp;
if (s2 < s1) {
tmp = s2;
s2 = s1;
s1 = tmp;
}
if (s3 < s2) {
tmp = s3;
s3 = s2;
s2 = tmp;
}
if (s2 < s1) {
tmp = s2;
s2 = s1;
s1 = tmp;
}
die1 = s1;
die2 = s2;
die3 = s3;
}
// --------------------- METHODS ---------------------
// Accessor methods
public int getDie1() {
return die1;
}
public int getDie2() {
return die2;
}
public int getDie3() {
return die3;
}
public boolean threeSame() {
return (die1 == die3);
}
public boolean runOfThree() {
return (( (die1 + 1) == die2) && ( (die2 + 1) == die3));
}
public boolean pair() {
return (((die1 == die2) || (die2 == die3)) && (die1 != die3));
}
public boolean allDifferent() {
return (!runOfThree() && (die1 != die2) && (die2 != die3));
}
public void printResult() {
if (threeSame())
System.out.println("The roll is all the same.");
else if (runOfThree())
System.out.println("The roll is a run.");
else if (pair())
System.out.println("The roll is a pair.");
else if (allDifferent())
System.out.println("The roll is all different.");
}
}
ThreeDiceScorer (Calculator) Class
public class ThreeDiceScorer extends ThreeDice {
int total;
public ThreeDiceScorer(int s1, int s2, int s3) {
super(s1, s2, s3);
}
public void calcTotalPoints() {
int sumOfDice = die1 + die2 + die3;
if (threeSame()){
total= sumOfDice + 60;
}
else if (runOfThree()){
total= sumOfDice + 40;
}
else if (pair()){
total= sumOfDice + 20;
}
else if (allDifferent()){
total= sumOfDice;
}
}
public void printResult(int p,int r) {
System.out.println("round "+ (r+1)+ "--> " + "player "+ (p+1) + " "+ die1 + " " + die2 + " " + die3 + " " + "points: "+ total);
}
}
Sol
Switch player loop and rounds loop.
In each round loop maintain a max and update it with max value and player.
Modify printresult a little to remove round.
Loop and max:
for (int r = 0; r < rounds; r++) { // loop for number of rounds
int max = 0;
int max_p = 0;
System.out.println("Round " + r + ": ");
for (int p = 0; p < players; p++) { //loop for players
int diceArray[] = new int[3];
//...
thrdiesc.printResult(p, r);
if (thrdiesc.total > max) {
max = thrdiesc.total;
max_p = p;
}
}
System.out.println("Winner is player " + (max_p + 1) + "\n");
}
PrintResult Method:
public void printResult(int p, int r) {
System.out.println("player " + (p + 1) + " " + die1 + " " + die2 + " " + die3 + " " + "points: " + total);
}
Misc
Indent Code properly.
Be careful while copying. (See the prompt)
While looking at your code, I have a feeling you might be able to make this much easier for yourself by creating some simple classes, five or six to be exact.
First I would break up some parts into classes. The two main classes I am thinking of are a simple Die class that is simply an immutable Die that when created sets the die value to a random number between 1 and 6. Once you create the Die object it cannot be changed. Your ThreeDice class is narrow and is really unnecessary as the three dice should really be a part of the Player object (next class) as a simple array of 3 Die objects and as an array of Die objects we can sort the dice from low to high.
A sample of a “Die” class is below:
Public final class Die implements Comparable<Die>
{
private int dieNumber;
// default constructor
public Die()
{
RollDie();
}
public int GetDieNumber()
{
return dieNumber;
}
public int compareTo(Die otherDie)
{
return this.dieNumber - otherDie.dieNumber;
}
private void RollDie()
{
dieNumber = 1 + (int)(6 * Math.random());
}
}
The next class to help would be a Player class. The important parts of this class will be a player name, then a Die object array (of size 3 in your case) to hold the players random dice. In this class you could also have methods to get the total value of the 3 dice, along with a method/variable to get the extra points the user gets if the 3 dice are the same number, if there is a pair, etc. Here we can take advantage of the sorting of the dice array from low to high when the dice array is created. This will make checking for straights easier.
A Player class example is below.
public class Player implements Comparable<Player>
{
private String playerName;
private Die[] diceArray;
private int diceTotal = 0;
private int extraPoints = 0;
private int overallTotal = 0;
private String extraPointsString = "";
public Player(String inName, Die[] inDiceArray)
{
playerName = inName;
diceArray = inDiceArray;
SetDiceTotals();
}
public String GetPlayerName()
{
return playerName;
}
public int GetExtraPoints()
{
return extraPoints;
}
public int GetDiceTotal()
{
return diceTotal;
}
public int GetOverallTotal()
{
return overallTotal;
}
public String GetExtraPointsString()
{
return extraPointsString;
}
public Die[] GetDiceArray()
{
return diceArray;
}
public String toString()
{
String playerString = playerName + " Dice values: ";
for (int i = 0; i < diceArray.length; i++)
{
if (i < (diceArray.length - 1))
playerString = playerString + diceArray[i].GetDieNumber() + ", ";
else
playerString = playerString + diceArray[i].GetDieNumber();
}
playerString = playerString + " Total: " + GetDiceTotal();
playerString = playerString + " - Special Points added: " + GetExtraPoints() + " for having " + GetExtraPointsString();
return playerString + " Total Points: " + GetOverallTotal();
}
public int compareTo(Player otherPlayer)
{
int thisTotal = this.GetDiceTotal() + this.GetExtraPoints();
int otherTotal = otherPlayer.GetDiceTotal() + otherPlayer.GetExtraPoints();
return otherTotal - thisTotal;
}
// private internal method to set dice totals, extra points and extra points string
private void SetDiceTotals()
{
int total = 0;
for (int i = 0; i < diceArray.length; i++)
{
total = total + diceArray[i].GetDieNumber();
}
diceTotal = total;
if (is3OfAKind())
{
extraPoints = 60;
extraPointsString = "Three of a Kind";
}
else
{
if (isPair())
{
extraPoints = 40;
extraPointsString = "Pair";
}
else
{
if (isStraight())
{
extraPoints = 20;
extraPointsString = "Straight";
}
else
{
extraPoints = 0;
extraPointsString = "All die are different";
}
}
}
overallTotal = extraPoints + diceTotal;
}
private boolean is3OfAKind()
{
if (diceArray[0].GetDieNumber() == diceArray[1].GetDieNumber() &&
diceArray[0].GetDieNumber() == diceArray[2].GetDieNumber())
return true;
return false;
}
private boolean isPair()
{
if (diceArray[0].GetDieNumber() == diceArray[1].GetDieNumber() ||
diceArray[0].GetDieNumber() == diceArray[2].GetDieNumber() ||
diceArray[1].GetDieNumber() == diceArray[2].GetDieNumber() )
return true;
return false;
}
// this method needs to have the diceArray sorted from low to high
private boolean isStraight()
{
if (diceArray[1].GetDieNumber() == (diceArray[0].GetDieNumber() + 1) &&
diceArray[2].GetDieNumber() == (diceArray[1].GetDieNumber() + 1) )
return true;
return false;
}
}
Then, since you want to keep totals for all the rounds, I figure you may need a Round class. This class will consist of an array of Player objects for a round. Also a round number, total points of the round from all players, an average of points for the round and a string to indicate which player won the round.
A Round class example is below.
public class Round
{
private Player[] playerArray;
private int roundNumber = 0;
private int totalPointsForRound = 0;
private double roundAveragePoints = 0;
private String roundWinnerName = "";
public Round(int inRoundNumber, Player[] inPlayerArray)
{
playerArray = inPlayerArray;
roundNumber = inRoundNumber;
totalPointsForRound = SetAllPointsForRound();
roundAveragePoints = SetAveragePoints();
roundWinnerName = SetRoundWinnerName();
}
public int GetTotalPointsForRound()
{
return totalPointsForRound;
}
public double GetAveragePointsForRound()
{
return roundAveragePoints;
}
public String GetRoundWinnerName()
{
return roundWinnerName;
}
public Player[] GetPlayerArray()
{
return playerArray;
}
public int GetRoundNumber()
{
return roundNumber;
}
private String SetRoundWinnerName()
{
// sort the array from high to low - if the first two total are equal then its a tie
Player[] tempArray = playerArray;
Arrays.sort(tempArray);
if (tempArray[0].GetOverallTotal() == tempArray[1].GetOverallTotal())
return "Tie";
if (tempArray[0].GetOverallTotal() > tempArray[1].GetOverallTotal())
return tempArray[0].GetPlayerName();
return "Unknown Winner???";
}
private double SetAveragePoints()
{
double totalPoints = GetTotalPointsForRound();
double average = totalPoints/playerArray.length;
return Math.round(average*100.0)/100.0;
}
private int SetAllPointsForRound()
{
int allPoints = 0;
for (int i = 0; i < playerArray.length; i++)
{
allPoints = allPoints + playerArray[i].GetOverallTotal();
}
return allPoints;
}
}
Then since you want to keep totals for all the players, you may want to make a small PlayerTotals class. This class will simply consist of a player name, total wins for all rounds and total points for all rounds. Keep in mind these are totals for ALL rounds not for a single round as each Player object in the Round's playerArray will contain totals for that particular round.
A PlayerTotals class example is below
public class PlayerTotals implements Comparable<PlayerTotals>
{
String playerName;
int totalWins = 0;
int totalPoints = 0;
public PlayerTotals(String inPlayerName)
{
playerName = inPlayerName;
}
public int GetTotalPoints()
{
return totalPoints;
}
public void SetTotalPoints(int inPoints)
{
totalPoints = inPoints;
}
public int GetTotalWins()
{
return totalWins;
}
public void SetTotalWins(int inWins)
{
totalWins = inWins;
}
public int compareTo(PlayerTotals otherPlayerTotals)
{
int thisTotalPoints = this.GetTotalPoints();
int otherTotalPoints = otherPlayerTotals.GetTotalPoints();
return otherTotalPoints - thisTotalPoints;
}
}
Then two more classes which you could actually combine into one class. One is a static GameUtils class that helps do some global things like: GetPlayerArray, this method gets an array of Player objects. Each Player object will contain an array of the 3 dice each player rolled. This dice array will be sorted from low to high. This is the method that gets your initial random rolls for each player for each round. Also here we can GetPlayerOverallWins where we can loop through all rounds and total up how many wins each player had. A method called GetTotalTies to get the total number of ties from all the rounds. And a method GetPlayerOverallPoints to get a total of all players points from all rounds. Also here I placed your prompts for the user to enter the number of players and number of rounds with a check to make sure the user input is valid.
A GameUtils example is below:
public final class GameUtils
{
public static Player[] GetPlayerArray(int numOfPlayers, int numOfDice)
{
Player[] playerArray = new Player[numOfPlayers];
for (int i = 0; i < numOfPlayers; i++)
{
Die[] diceArray = new Die[numOfDice];
for (int j = 0; j < numOfDice; j++)
{
diceArray[j] = new Die();
}
Arrays.sort(diceArray);
playerArray[i] = new Player("Player " + (i + 1), diceArray);
}
return playerArray;
}
public static int GetNumberOfPlayers(Scanner input)
{
return GetValidInteger("Please input number of players (greater than 0) --> ", input);
}
public static int GetNumberOfRounds(Scanner input)
{
return GetValidInteger("Please input number of rounds (greater than 0) --> ", input);
}
private static int GetValidInteger(String prompt, Scanner input)
{
boolean done = false;
int validInt = -1;
String userInput = "";
while (!done)
{
System.out.print(prompt);
userInput = input.nextLine();
try
{
validInt = Integer.parseInt(userInput);
done = true;
}
catch (NumberFormatException e)
{
System.out.println("Invalid Input: " + userInput + " Try again!");
}
}
return validInt;
}
public static int GetPlayerOverallWins(String playerName, Round[] allRounds)
{
int totalWins = 0;
for (int i = 0; i < allRounds.length; i++)
{
Round curRound = allRounds[i];
String roundWinner = curRound.GetRoundWinnerName();
if (playerName.equals(roundWinner))
{
totalWins++;
}
}
return totalWins;
}
public static int GetTotalTies(Round[] allRounds)
{
int totalTies = 0;
for (int i = 0; i < allRounds.length; i++)
{
Round curRound = allRounds[i];
String roundWinner = curRound.GetRoundWinnerName();
if (roundWinner.equals("Tie"))
{
totalTies++;
}
}
return totalTies;
}
public static int GetPlayerOverallPoints(String player, Round[] allRounds)
{
int totalPoints = 0;
for (int i = 0; i < allRounds.length; i++)
{
Round curRound = allRounds[i];
for (int j = 0; j < curRound.GetPlayerArray().length; j++)
{
Player curPlayer = curRound.GetPlayerArray()[j];
if (player.equals(curPlayer.GetPlayerName()))
{
totalPoints = totalPoints + curPlayer.GetOverallTotal();
break;
}
}
}
return totalPoints;
}
}
Lastly a DiceGame class with a main entry to put it all together. A dice game class will consist of global variables numberOfPlayers. numberOfRounds, numberOfDice, and a playerArray to use for each round, then an array of Rounds to hold all the rounds for totaling after all the rounds have been run. The example below starts by setting a loop for the number of rounds, in this loop we create all the players and dice values for them then save the round information into a new Round object then place each new Round object into an array. Then the results from the current round is output to the user. Once the loop on the number of rounds finishes, we should then have an array of Round objects. Here is where the PlayerTotals class helps as we can create another array of PlayerTotals objects for all rounds. This uses some methods from GameUtils and these methods could just a well be placed into this main class. After all player totals for all rounds have been added up, the results are output to the user.
Main DiceGame class example:
public class DiceGame
{
public static Scanner input = new Scanner(System.in);
static int numberOfPlayers;
static int numberOfRounds;
static int numberOfDice = 3;
static Player[] playerArray;
static Round[] allRounds;
public static void main(String[] args)
{
numberOfPlayers = GameUtils.GetNumberOfPlayers(input);
numberOfRounds = GameUtils.GetNumberOfRounds(input);
System.out.println("");
allRounds = new Round[numberOfRounds];
// for each round - we want to create players with the proper number of random dice
for (int i = 0; i < numberOfRounds; i++)
{
// get an array of players with random dice
playerArray = GameUtils.GetPlayerArray(numberOfPlayers, numberOfDice);
Round currentRound = new Round(i, playerArray);
allRounds[i] = currentRound;
// print the results of this round
System.out.println("Round " + (i + 1) + " Results - Winner is: " + currentRound.GetRoundWinnerName()
+ " -- Average score for this round: " + currentRound.GetAveragePointsForRound());
for (int j = 0; j < playerArray.length; j++)
{
System.out.println(playerArray[j].toString());
}
System.out.println("---------------------------------------");
}
// now get totals for all rounds
// first create an array of PlayerTotals
PlayerTotals[] allPlayersTotals = new PlayerTotals[numberOfPlayers];
for (int i = 0; i < numberOfPlayers; i++)
{
PlayerTotals curPlayer = new PlayerTotals(playerArray[i].GetPlayerName());
curPlayer.SetTotalPoints(GameUtils.GetPlayerOverallPoints(curPlayer.playerName, allRounds));
curPlayer.SetTotalWins(GameUtils.GetPlayerOverallWins(curPlayer.playerName, allRounds));
allPlayersTotals[i] = curPlayer;
}
// print the overall results
System.out.println("");
System.out.println(" -- Overall Results --");
System.out.println("Ties: " + GameUtils.GetTotalTies(allRounds));
Arrays.sort(allPlayersTotals);
PlayerTotals curPlayer;
for (int i = 0; i < allPlayersTotals.length; i++)
{
curPlayer = allPlayersTotals[i];
System.out.println(curPlayer.playerName + " Won " + curPlayer.totalWins + " times - Total Points: " + curPlayer.totalPoints);
}
}
}
Hope these make things easier. Good Luck!

My program has no syntax error but I can't get the final avg # right

My program has no syntax error, I can input all the value, but I just can't get the final average number right. Can anyone help me find out the problem?
The following is what I input:
How many employees do you have? 4
How many days was Employee #1 absent? 4
How many days was Employee #2 absent? 2
How many days was Employee #3 absent? 1
How many days was Employee #4 absent? 3
Final answer should be: 2.5
This is the code I use:
import java.util.Scanner;
class Number {
public static void main(String[] args) {
int numEmployee = Number.workers();
int absentSum = Number.totaldays(numEmployee);
double averageAbsent = Number.average(numEmployee, absentSum);
}
public static int workers() {
int number = 0;
Scanner input = new Scanner(System.in);
while (number > 0 || number < 0 || number == 0) {
System.out.println("How many employees do you have?");
number = input.nextInt();
if (number >= 0) {
return number;
} else {
System.out
.println("You can not enter a negative number."
+ " Please enter another number.");
}
}
return number;
}
public static int totaldays(int numEmployee) {
int absentDays = 0;
int absentSum = 0;
for (int employName = 1; employName <= numEmployee; employName++) {
System.out.println("How many days was Employee #" + employName
+ " absent?");
Scanner input = new Scanner(System.in);
absentDays = input.nextInt();
while (absentDays < 0) {
System.out.println("You can not enter a negative number."
+ " Please enter another number.");
System.out.println("How many days was Employee #" + employName
+ " absent?");
absentDays = input.nextInt();
}
absentSum += absentDays;
}
return absentSum;
}
public static double average(int numEmployee, int absentSum) {
double averageAbsent = (double) absentSum / (double) numEmployee;
System.out.println("Your employees averaged " + averageAbsent
+ " days absent.");
return averageAbsent;
}
}
Move absentSum += absentDays; into the loop body in totaldays. If you restrict the visibility of absentSum then the compiler will tell you that you are accessing it out of scope. Something like
public static int totaldays(int numEmployee) {
int absentSum = 0;
for (int employName = 1; employName <= numEmployee; employName++) {
System.out.println("How many days was Employee #" + employName
+ " absent?");
Scanner input = new Scanner(System.in);
int absentDays = input.nextInt();
while (absentDays < 0) {
System.out.println("You can not enter a negative number."
+ " Please enter another number.");
System.out.println("How many days was Employee #" + employName
+ " absent?");
absentDays = input.nextInt();
}
absentSum += absentDays;
}
// absentSum += absentDays;
return absentSum;
}
With the above output (and your provided input) I get (the requested)
2.5

sorting, average and finding the lowest number from a static array Java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
i'm trying to input students and input their results for course work and exams and what i'm having trouble with is finding the average total score, the lowest total score and printing all students in order of total scores highest - lowest
import java.util.*;
import java.text.*;
public class Results
{
static String[] name = new String[100];
static int[] coursework = new int[100];
static int[] exam = new int[100];
static int[] totalScore = new int[100];
static String[] totalGrade = new String[100];
static String[]examGrade = new String[100];
static int count = 0;
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
boolean flag = true;
while(flag)
{
System.out.println(
"1. Add Student\n" +
"2. List All Students\n" +
"3. List Student Grades\n" +
"4. Total Score Average\n" +
"5. Highest Total Score\n" +
"6. Lowest Total Score\n" +
"7. List all Students and Total Scores\n" +
"8. Quit\n");
System.out.print("Enter choice (1 - 8): ");
int choice = input.nextInt();
switch(choice)
{
case 1:
add();
break;
case 2:
listAll();
break;
case 3:
listGrades();
break;
case 4:
average();
break;
case 5:
highestTotal();
break;
case 6:
lowestTotal();
break;
case 7:
order();
break;
case 8:
flag = false;
break;
default:
System.out.println("\nNot an option\n");
}
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));
}
System.out.println("\n\nHave a nice day");
}//end of main
static void add()
{
Scanner input = new Scanner(System.in);
System.out.println("Insert Name: ");
String names = input.nextLine();
System.out.println("Insert Coursework: ");
int courseworks = input.nextInt();
System.out.println("Insert Exam: ");
int exams = input.nextInt();
int totalscores = exams + courseworks;
name[count] = names;
coursework[count] = courseworks;
exam[count] = exams;
totalScore[count] = totalscores;
count++;
}
static void listAll()
{
for(int i=0;i<count;i++)
{
System.out.printf("%s %d %d\n", name[i], coursework[i], exam[i]);
}
}
static void listGrades()
{
for(int i=0;i<count;i++){
if(coursework[i] + exam[i] > 79)
{
System.out.println(name[i] + " HD");
}
else if(coursework[i] + exam[i] > 69)
{
System.out.println(name[i] + " DI");
}
else if(coursework[i] + exam[i] > 59)
{
System.out.println(name[i] + " CR");
}
else if(coursework[i] + exam[i] > 49)
{
System.out.println(name[i] + " PA");
}
else
{
System.out.println(name[i] + " NN");
}
}
}
static void average()
{
double sum = 0;
for(int i=0; i < count; i++)
{
sum += exam[i] + coursework[i];
}
sum = sum / count;
System.out.printf("Average Total Score : %.1f\n ", sum);
}
static void highestTotal()
{
int largest = totalScore[0];
String student = name[0];
for (int i = 0; i < exam.length; i++) {
if (totalScore[i] > largest) {
largest = totalScore[i];
student = name[i];
}
}
System.out.printf(student + ": " + largest + "\n");
}
static void lowestTotal()
{
int lowest = totalScore[0];
String student = name[0];
for (int i = 0; i > exam.length; i++) {
if (totalScore[i] < lowest) {
lowest = totalScore[i];
student = name[i];
}
}
System.out.printf(student + ": " + lowest + "\n");
}
static void order()
{
for (int i=0;i<count;i++)
{
Arrays.sort(totalScore);
System.out.printf(name[i] + "\t" + totalScore[count] + "\n");
}
}
}
static void average(){
int total = 0;
for(int i = 0; i < array.length; i++)
{
total += array[i];
}
int average = total / array.length
}
Above code you can get the Average. You did the kind of similar thing to find largest value.
to sort array just use that will solve your problem.
Arrays.sort(array);
For sorting, you can use Arrays.sort(array) (With a comparator if you need special ordering)
Once it's sorted, getting the lowest score should be easy. To get an average, add up each value and divide by the number of elements. To add them all up, use a for loop or for-each loop:
int sum = 0;
for(int i = 0; i < array.length; i++)
{
sum += array[i];
}
int average = sum / array.length
You may want to use a double instead of an int for sum.
For Average Total Score simply add the coursework and exam scores in avariable such as sum and divide by no. of students:
static void average() {
int sum = 0;
for(int i=0; i < count; i++)
{
sum += exam[i] + coursework[i];
}
sum = sum / count;
System.out.printf("Average Total Score = : " + sum + "\n");
}
For both lowest total score and largest total score your implementation of highest total is almost right. The problem is that you are not considering the coursework[i] in your largest variable. And on similar lines you can implement lowest total score
static void highestTotal() {
int largest = exam[0] + coursework[0];
String student = name[0];
for (int i = 0; i < exam.length; i++) {
if (exam[i]+coursework[i] > largest) {
largest = exam[i] + coursework[i];
student = name[i];
}
}
System.out.printf(student + ": " + largest + "\n");
}
For printing the scores in order i would suggest that you define another int array which has the sum of exam score and coursework score, sort it using any basic sorting technique and print the array. Remember while exchanging the sum during sorting also exchange the corresponding name..

Categories