My program keeps adding up the score for each player, rather than keeping it separate for example if first player gets 3/5 and the second gets 2/5 the score display for the second player will be 5. I know the answer is probably very simple however I'm not able to find it within the code.
public static void questions(String[] question, String[] answer, int n) {
String[] name = new String[n]; // Player Names
int[] playerscore = new int[n]; // Argument for Score
String[] que = new String[question.length]; //Questions for Loops
int score = 0; // Declare the score
/* --------------------------- For loop for number of players --------------------------- */
for (int i = 0; i < n; i++) {
name[i] = JOptionPane.showInputDialog("What is your name player" + (i + 1) + "?");
JOptionPane.showMessageDialog(null, "Hello :" + name[i] + " Player number " + (i + 1) + ". I hope your ready to start!");
/* --------------------------- Loop in Loop for questions --------------------------- */
for (int x = 0; x < question.length; x++) {
que[x] = JOptionPane.showInputDialog(question[x]);
if (que[x].equals(answer[x])) {
score = score + 1;
} else {
JOptionPane.showMessageDialog(null, "Wrong!");
}
} // End for loop for Question
playerscore[i] = score;
System.out.println("\nPlayer" + (i) + "Name:" + name[i] + "\tScore" + score);
}
}
You will need to reset the score to 0 before each player starts.
Add this after the loop for each player:
score = 0;
Alternatively you could increment the score directly in the array. Just change:
score = score + 1;
to:
playerscore[i] = playerscore[i] + 1;
or simply:
playerscore[i]++;
Assign score=0 after the line
playerscore[i] = score;
Every each and every player is assigned with his score in inner loop. Since score is declared as instance variable it will not differentiate between two different players. In order to have each and every individual player with his own scores, assign score with zero as soon as questions exceeds.
Related
I am learning how to code and my teacher gave me an exercise to create a lottery program that generates 6 random numbers between 1 and 49 with no duplicates and one bonus number that could be a duplicate. My program generates all the numbers fine, but for some reason duplicates still appear. Could someone please explain why the code that checks for duplicates doesn't work, as I have been struggling to understand why it doesn't work. Please bear in mind that I'm a new programmer so try and keep explanations beginner friendly. Thanks in advance.
int[] lottonums = new int[6];
//Generates 6 random numbers between 1-49
for(int i = 0; i < lottonums.length; i++){
lottonums[i] = (int)(Math.random()* 49 +1);
}
//Checks for duplicates
for(int x = 0; x < 6; x ++){
for(int y = x + 1; y < 6; y ++){
while(lottonums[x] == lottonums[y]){
lottonums[y] = (int)(Math.floor(Math.random() * 49 + 1));
}
}
}
//Bonus ball, no checks for duplicates
int bonusBall = (int)(Math.random() * 49 + 1);
Arrays.sort(lottonums);
System.out.println("\nThe lottery numbers are: ");
for( int nu = 0; nu < lottonums.length; nu ++){
System.out.print(lottonums[nu] + " " );
}
System.out.println("\nThe bonus number is: " + bonusBall + "\n");
Best Way to have unique number is by using Set instead of array.
if you are not aware much about set have a look into it set TreeSet
Basically if you look at your code
//Checks for duplicates
for(int x = 0; x < 6; x ++){
for(int y = x + 1; y < 6; y ++){
while(lottonums[x] == lottonums[y]){
//below line does not gurrantee its going to insert unique number
//example [1,2,6,6] here at index 2 and 3 6 is there
//now you got this while checking duplicate
//after you are generating new random suppose new generated number is 2
// as you are not going back to check duplicate so it will be inserted
lottonums[y] = (int)(Math.floor(Math.random() * 49 + 1));
}
}
}
you can try the below solution using set
which fits yous requirement
// TreeSet will have unique element in sorted manner no need to sort again
TreeSet<Integer> set=new TreeSet<>();
int n=6;
while(set.size()<n-1)
{
set.add((int)(Math.random()* 49 +1));
}
//Bonus ball, no checks for duplicates
int bonusBall = (int)(Math.random() * 49 + 1);
System.out.println("\nThe lottery numbers are: ");
for( int nu :set){
System.out.print(nu + " " );
}
System.out.println("\nThe bonus number is: " + bonusBall + "\n");
}
So this is what I'm trying to do.
The program should have a loop that iterates 10 times. Each time the loop iterates, it should roll both dice. The die with the highest value wins. In the case of a tie, there is no winner for that particular roll of the dice.
As the loop iterates, the program should:
Ask the user if they are ready to roll.
Display the result of the roll
The number of User’s roll, Computer’s roll, and the result (who win, lose or
tie).
Keep count of the number of times the computer wins.
Keep count of the number of times that the user wins
The Die object code:
import java.util.Random;
/**
The Die class simulates a six-sided die.
*/
public class Die
{
private int sides; // Number of sides
private int value; // The die's value
/**
The constructor performs an initial
roll of the die.
#param numSides The number of sides for this die.
*/
public Die(int numSides)
{
sides = numSides;
roll();
}
/**
The roll method simulates the rolling of
the die.
*/
public void roll()
{
// Create a Random object.
Random rand = new Random();
// Get a random value for the die.
value = rand.nextInt(sides) + 1;
}
/**
getSides method
#return The number of sides for this die.
*/
public int getSides()
{
return sides;
}
/**
getValue method
#return The value of the die.
*/
public int getValue()
{
return value;
}
}
This is the code that uses the object code, for the dice and their movement.
public class MitchellLab06
{
public static void main(String[] args)
{
final int DIE1_SIDES = 6; //Number of sides for die #1
final int DIE2_SIDES = 6; //Number of sides for die #1
final int MAX_ROLLS = 10; //Number of ties to roll
// Create two instances of the Die class.
Die die1 = new Die(DIE1_SIDES);
Die die2 = new Die(DIE2_SIDES);
//Display the initial value of the dice.
System.out.println("This program simulates the rolling of a " +
DIE1_SIDES + " sided die and another " +
DIE2_SIDES + " sided die.");
System.out.println("The initial value of the dice:");
System.out.println(die1.getValue() + " " + die2.getValue());
//Roll the dice 10 times.
System.out.println("Rolling the dice " + MAX_ROLLS + " times");
for(int i = 0; i < MAX_ROLLS; i++)
{
//Roll the dice.
die1.roll();
die2.roll();
//Display the value of the dice.
System.out.println(die1.getValue() + " " + die2.getValue());
}
}
}
I need help keeping track of which die wins, out of the 10 rolls and determine if the user wins, the computer wins, or if it's a tie.
One example solution is to initialize two arrays one for the computer one for the user.
Each time you throw a dice you increment the array on position throwing turn number with dice.
int [] computer = new int[10];
int [] user = new int [10];
for (int i=0;i<10; ++i) {
int diceUser = throwDice();
int diceComputer = throwDice();
if (diceUser> diceComputer) {
user[i] = diceUser;
}
else if (diceUSer<diceComputer) {
computer[i]= diceComputer;
}
else {
computer[i] = diceComputer;
user[i] = diceUser;
}
}
Every time computer or user has lost, they will have 0 in the array. When it is a draw both arrays will contain the same value at the same index.
The index of the array is following the turn.
A simple, yet elegant solution that uses a simple while loop and a couple variables to hold the user score, comp score and the total number of wins for each of them.
int userWin = 0, compWin = 0;
int MAX_ATTEMPTS = 10;
while(MAX_ATTEMPTS > 0) {
int userScore = 0, compScore = 0;
//Roll the dice for user
die1.roll();
die2.roll();
userScore = die1.getValue() + die2.getValue();
//Roll the dice for comp
die1.roll();
die2.roll();
compScore = die1.getValue() + die2.getValue();
// determine winner
if (userScore > compScore) {
System.out.println("User wins! \nUser score = " + userScore + ", Comp score = " + compScore);
userWin++;
}
else if (userScore < compScore) {
System.out.println("Comp wins! \nUser score = " + userScore + ", Comp score = " + compScore);
compWin++;
} else {
System.out.println("Draw!\nUser score = " + userScore + ", Comp score = " + compScore);
}
MAX_ATTEMPTS --;
}
System.out.println("User won = " + userWin + " times! ");
System.out.println("Comp won = " + compWin + " times! ");
I'm designing a program that simulates a game of dice. The code calculates the total points get each round and the player that wins each round.
I am trying to get the overall number of wins and the total points. I tried using a for loop in the main class but I wasn't sure how to implement it in this problem.
Round 1:
player 1 3 1 5 points: 9
player 2 2 6 6 points: 14
Winner is player 2
Round 2:
player 1 3 6 5 points: 14
player 2 2 3 2 points: 7
Winner is player 1
Round 3:
player 1 3 3 6 points: 12
player 2 5 4 6 points: 15
Winner is player 2
.
Total wins: player 1-->1/ player 2-->2
Total points: player 1-->35/ player 2-->36
Main class
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 players (grater or equal than 2) --> ");
players = input.nextInt();
System.out.print("\n");
for (int r = 0; r < rounds; r++) { // loop for number of rounds
int max = 0;
int max_p = 0;
System.out.println("Round " + (r+1) + ": ");
for (int p = 0; p < players; p++) { //loop for players
int diceArray[] = new int[3];
for (int i = 0; i < diceArray.length; i++) { // loop for dice Array (data of 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.calcTotalPoints();
thrdiesc.printResult(p, r);
if (thrdiesc.total > max) {
max = thrdiesc.total;
max_p = p;
}
}
System.out.println("Winner is player " + (max_p + 1) + "\n");
}
System.out.println("Total wins: " );
System.out.println("Total points: " );
}//end Main Method
} // end Class
Calculation class
public class ThreeDiceScorer {
public static int total;
public int die1;
public int die2;
public int die3;
public ThreeDiceScorer(int s1, int s2, int s3) {
die1 = s1;
die2 = s2;
die3 = s3;
}
public void calcTotalPoints() {
int sumOfDice = die1 + die2 + die3;
total= sumOfDice;
}
public void printResult(int p, int r) {
System.out.println("player " + (p + 1) + " " + die1 + " " + die2 + " " + die3 + " " + "points: " + total);
}
}
I tried using a for loop in the main class but I wasn't sure how to implement it in this problem.
I would say, do one thing at a time. Test your implementation and once you confirmed that it is working, then move on. The sequential steps to reach your goal would be:
Steps
Implement dice rolling for one player first. (Can do it in a method)
Call the above implemented method for 2nd player's dice roll.
Decide winner
Once steps 1-3 were implemented correctly, enclose steps 1-3 within a loop (preferable a for-loop for this particular case)
//Example:
int numOfRounds = 3; //can receive this from user input
for(int x=0; x<numOfRounds; x++){
rollDice(playerOne);
rollDice(playerTwo);
decideWinner(playerOne, playerTwo);
}
Once steps 1-4 is tested and working fine. Implement the display of total score:
//Example:
int numOfRounds = 3; //can receive this from user input
for(int x=0; x<numOfRounds; x++){
rollDice(playerOne);
rollDice(playerTwo);
decideWinner(playerOne, playerTwo);
}
displayFinalScore();
Total score and total wins can be stored in a very simple Player class which looked like this:
public class Player{
private String name;
private int totalScore;
private int totalWins;
}
Dynamic Multi-player
I tried to keep the solution as short and simple as possible for your understanding. But if you want the program to dynamically take in n number of players. The same program flow still applies.
In step 4, you can do it as:
int numOfPlayers = 2; //can receive this from user input
ArrayList<Player> players = new ArrayList<Player>();
for(int x=0; x<numOfPlayers; x++)
numOfPlayers.add(new Player("Player " + (x+1)));
for(int x=0; x<numOfRounds; x++){
for(int y=0; y<players.size(); y++) //iterate through all players
rollDice(players.get(y));
decideWinner(players); //decide the winner from all the players
}
There are many ways to solve this, I would add two counters like int count = 0 and increment them: one every time there is a victory (for ex.: if(victory) { c++ })and the other through the expression count = count + points.
Remember to implement these ints at the beginning or the for loop will reset count1 and count2 to 0.
I want the program to keep incrementing the innings for each iteration of the loop.
When I run the program it's doing that, however it's showing me incorrect values.
For example:
You rolled...4
Your total for this innings so far is 6
The second line should be showing, "... so far is 4"
This is the code that I have at the moment:
import java.util.Random;
import javax.swing.*;
public class shortSix {
public static void main(String[] args) {
diceGame();
}//ENDS MAIN
public static void diceGame()
{
final int[] innings = new int[1];
innings[0] = 0;
Random dice = new Random();
int diceRoll = dice.nextInt(6) + 1;
while (diceRoll != 5)
{
System.out.println("You rolled..." + diceRoll);
diceRoll = dice.nextInt(6) + 1;
innings[0] =+ diceRoll;
System.out.println("Your total for this innings so far is " + innings[0]);
String userDeclare = JOptionPane.showInputDialog(null, "Do you wish to declare?");
if (userDeclare.equals("yes"))
{
System.exit(0);
}
}
}//ENDS diceGame
}//ENDS class shortSix
The problem is that you aren't updating the array record after the first roll. You've got int diceRoll = ..., then you assign random value to the variable again and add the score after the second roll. The first result is ignored. All you have to do is change
diceRoll = dice.nextInt(6) + 1;
innings[0] =+ diceRoll;
to
innings[0] =+ diceRoll;
diceRoll = dice.nextInt(6) + 1;
There are two problems:
=+ instead of += before the second println
Order of operations is strange. You first print the current value, then update it and only then increases counter and prints summary. Probably you wanna move diceRoll = dice... after the second println
You call
diceRoll = dice.nextInt(6) + 1;
before printing
System.out.println("Your total for this innings so far is " + innings[0]);
which causes making a new random number, and it is the problem.
UPDATE: Figured it out, code has been fixed below. Added a while loop to confirm values 0 or above are entered too.
So I'm doing an assignment where the user enters 8 scores and you must find the highest and lowest scores and their position in the order they were given. I have been able to find the highest and lowest scores but I can't figure out how to find their position. Please help me. Here is my code so far.
import java.util.Scanner;
public class HighestLowestPoints {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int largest = -1;
int smallest = 0;
int highGame = 1;
int lowGame = 1;
for(int games = 1; games <= 8; games++) {
System.out.println("Please enter the Texans' score in game " + games);
int points = keyboard.nextInt();
while(points < 0) {
System.out.println("Please enter a value 0 or above");
points = keyboard.nextInt();
}
if(games == 1) {
smallest = points;
}
if(points > largest) {
largest = points;
highGame = games;
}
if(points < smallest) {
smallest = points;
lowGame = games;
}
if(games == 8){
System.out.println(largest + " in game " + highGame + "\n"
+ smallest + " in game " + lowGame);
}
}
}
}
Your almost there. You need to add to variables to save the hightGame and lowestGame and just assign them when you set the highest and the lowest score respectively.
Ex:
if(points < smallest) {
smallest = points;
lowestGame = games;
}
You could use the game counter variable in your for loop it contains your position :-)
Add another 2 variables, maxIndex and minIndex and when setting smallest or largest, set the appropriate variable as well with "games" variable (contains the position).
create two new variables:
int highPos = -1;
int lowPos = -1;
Every time you assign smallest, assign games to lowPos
Every time you assign highest, assign games to highPos.
add
int lPos = 0, sPos = 0;
before your for loop.
add this lPos = games to your if-block where your find largest number and sPos = games to if-block with lowest.
Also why do you assign the lowest to the first game, but not the highest?
if(games == 1) {
smallest = points;
}
Just for your information. You could also avoid all these different if's and making the code more readable if you would you would store all your games in an ArrayList. And then use the method Collections.max to get the maximum game and Collections.min to get your minimum game. Then with the method list.indexOfyou could find the position where the value is added to the list.
Scanner keyboard = new Scanner(System.in);
List<Integer> numbers = new ArrayList<Integer>();
for(int games = 1; games <= 8; games++) {
System.out.println("Please enter the Texans' score in game " + games);
int points = keyboard.nextInt();
while(points < 0) {
System.out.println("Please enter a value 0 or above");
points = keyboard.nextInt();
}
numbers.add(points);
}
StringBuilder output = new StringBuilder();
output.append("Maximum points: " + Collections.max(numbers));
output.append(" in game: " + (numbers.indexOf(Collections.max(numbers)) + 1));
output.append(" minimum points: " + Collections.min(numbers));
output.append(" in game: " + (numbers.indexOf(Collections.min(numbers)) + 1));
System.out.println(output.toString());