Do not why Array not storing numbers in java - java

hi im a beginner in java i am trying to write a program that records the value of three dice rolls in a game between two players. i have to utilise arrays. the problem is that when i print out to screen for some reason the value of each dice is 0 and it is not printing the randomly generated roll. the idea is when we print to screen it should say round 1 player 1: and display each number rolled on the three dice and then do a calculation and output the points dependant on weather they are three the same or all different etc.
This is what i have so far any help would be appreciated as i am a beginner and have been trying to figure this out for hours.
This is the first class
// Description: program to simulate two players each rolling three dice for a number of rounds
import java.util.Arrays;
import java.util.Scanner;
public class Dicegame {
static Scanner read = new Scanner (System.in);
public static void main(String[] args) {
int[] num = new int[3];
int numberOfRounds;
numberOfRounds = 0;
do {
//This will print out a request for the user
System.out.println("Please enter the number of rounds: \n");
//This will ensure the input value will remain above 0
numberOfRounds = read.nextInt(); } while (numberOfRounds < 1);
Dicegame2 Dicegame2Object = new Dicegame2(numberOfRounds);
//This is instantiating the scanner object
Dicegame1 Dicegame1Object = new Dicegame1(num[0], num[1], num[2]);
Dicegame1Object.order();
Dicegame2Object.diceValue();
for(int round=0;round<numberOfRounds;round++){
System.out.println("Round "+ (round+1)
+" Player1: "+ num[0]+num[1]+num[2]+
" Points: "); }
if(Dicegame1Object.threeAllTheSame()){
System.out.print(Dicegame2Object.sumOfDiceSame());;
}else{
if(Dicegame1Object.alInOrder()){
System.out.print(Dicegame2Object.sumOfDiceRun());
}else{
if(Dicegame1Object.twoSameOneDifferent()){
System.out.print(Dicegame2Object.sumOfDiceDifferent());
}else{
System.out.print(Dicegame2Object.sumOfDicePair());
}
}
}
}
}
This is the second class
// Description: program to simulate two players each rolling three dice for a number of rounds
import java.util.Arrays;
public class Dicegame1 {
//variables
private int Dice1;
private int Dice2;
private int Dice3;
int[] num = new int[3];
private final int numberOfThrows = 3;
//Constructor
public Dicegame1 (int D1, int D2, int D3)
//This is assigning local variables to class variables
{ num[0] = D1;
num[1] = D2;
num[2] = D3;
}
//This will calculate to see if the dice are all the same
//This is a boolean method which contains an if statement
public boolean threeAllTheSame(){
boolean trueOrNot;
if((num[0] == num[1])&&(num[1]==num[2])){
trueOrNot = true;
}else{
trueOrNot = false;
}
return trueOrNot;
}
//This will calculate to see if the dice are a pair
//This is a boolean method which contains an if statement
public boolean twoSameOneDifferent(){
boolean trueOrNot;
if (((num[0] == num[1])&&(num[1]!=num[2]))||
((num[1] == num[2])&&(num[2]!=num[0]))||
((num[0] == num[2])&&(num[0]!=num[1]))){
trueOrNot = true;
}else{
trueOrNot = false;
}
return trueOrNot;
}
//This will calculate to see if the roll is a run
//This is a boolean method which contains an if statement
public boolean alInOrder(){
boolean trueOrNot;
if ((num[1] == (num[0]+1))&&
(num[2] == (num[1]+1))){
trueOrNot = true;
}else{
trueOrNot = false;
}
return trueOrNot;
}
//This will calculate to see if the dice are all different
//This is a boolean method which contains an if statement
public boolean allDifferent(){
boolean trueOrNot;
if ((num[0] != (num[1]))&&(num[1] != (num[2]))&&(num[2] != (num[0]))){
trueOrNot = true;
}else{
trueOrNot = false;
}
return trueOrNot;
}
//This will sort out the numbers of the array in order
public void order(){
Arrays.sort(num);
}
}
This is the third and final class
// Description: program to simulate two players each rolling three dice for a number of rounds
import java.util.Arrays;
import java.util.Random;
public class Dicegame2 {
//variables
private int numberOfRounds;
private int Dice1;
private int Dice2;
private int Dice3;
private Dicegame1[] match;
//constructor
public Dicegame2(int nOfRounds) {
numberOfRounds = nOfRounds;
match = new Dicegame1 [numberOfRounds];
}
public void diceValue() {
int[] num = new int[3];
for(int i=1;i<numberOfRounds;i++){
Dice1 = 1+(int)(6*Math.random());
Dice2 = 1+(int)(6*Math.random());
Dice3 = 1+(int)(6*Math.random());
match [i] = new Dicegame1(num[0], num[1], num[2]);
}
}
//This will calculate the sum of dice if all the same
public int sumOfDiceSame(){
int calc1;
int[] num = new int[3];
calc1 =((num[0]+num[1]+num[2])+60);
return calc1;
}
//This will calculate the sum of dice if its a pair
public int sumOfDicePair(){
int calc2;
int[] num = new int[3];
calc2 =((num[0]+num[1]+num[2])+20);
return calc2;
}
//This will calculate the sum of dice if its a run
public int sumOfDiceRun(){
int calc3;
int[] num = new int[3];
calc3 =((num[0]+num[1]+num[2])+40);
return calc3;
}
//This will calculate the sum of dice if all different
public int sumOfDiceDifferent(){
int calc4;
int[] num = new int[3];
calc4 =(num[0]+num[1]+num[2]);
return calc4;
}
}

As I was able to see into your code, you are printing the array of nums into your main, that are not set.
Second that array is not needed at all.
You have something like Dicegame2. From what I am seeing I would create additional method here that will return the array match.
Also I do not understand summing into this class. I would sum into Dicegame1 BUT I would remove new int[3] from there.
This are only guide lines. read variables scope, and for loops.

Related

Vector in java always overwriting everything with the last value

I'm a beginner in java and I have the following exercise to solve:
Read a set of sports lottery bets to an unspecified number of players. After that, read the template, compare the result and display a message.
Bet Class: must contain the player's name and an integer vector with thirteen positions to store the bet: 1 – winner of team A, 2 – winner of team B, and 0 for draw. Create the necessary constructor methods and the toString method.
ReadBets Class: This class must have an attribute that is a vector of objects of the Bet class. In addition, this class must have a method to read the person's name and their sports lottery game. Create the necessary constructor methods and the toString method.
ReadTemplate Class: This class should read the correct answers from the sports lottery game and store the result in an integer vector. Create the necessary constructor methods and the toString method.
GenerateResult Class: this class must compare the players' bets with the result of the template and, if you have 6 correct answers, show the winner's name, his game and the message: “WINNER, CONGRATULATIONS”. Otherwise, show the player name and the message “Try again, this time you didn't win”.
Main Class: implement in this class the control and execution flow for this problem creating the necessary objects to solve this class.
There is a complicating factor for me which is that each object bet is composed of a string name with a vector with the bets.
I made a solution to the problem that already reads validating only the allowed values (0,1,2), reads the template and compares.
However, I noticed that the last name typed and the last bets are always being recorded in the vector. In all positions.
I'm hours assembling and disassembling the code and I can't find a way to solve it.
I read that it may have to do with the new but I didn't understand how to solve it because at each position of the vector of objects I need to give a new to create the object with the internal vector that will store that player's bets.
Below are my classes:
MAIN:
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Main {
public void execute(){}
static Scanner input = new Scanner (System.in);
public static void main(String[] args) {
//ReadBet a = new ReadBet();
V_Bets a = new V_Bets();
System.out.println("Enter the total bets that will be placed");
a.totalBets(input.nextInt());
a.Data entry();
a.Data output();
ReadTemplate g = new ReadTemplate();
g.getTemplate();
GenerateResult gr = new GenerateResult();
gr.generateResult();
}
}
BETS:
import java.util.Arrays;
public class Bet {
private static String name;
public static int[] Bet vector =new int [6];
/*public String getName(){
return this.name;
}*/
public static String getName() {
return name;
}
public void setName(String name){
this.name=name;
}
#Override
public String toString() {
return "Bet [name=" + name + ",Betvector=" + Arrays.toString(Betvector) + "]";
}
public int getBet(int i) {
return this.vector Bets[i];
}
public void setBets(int[] bets) {
this.vector Bets = bets;
}
public int[] getCloneArray() {
returnVectorBets.clone();
}
}
V_BETS
import java.util.Scanner;
public class V_Bets {
Input Scanner = new Scanner (System.in);
private int size;
public static Total BetBets[] = new Bet[100];
//total Bets[j] = new Bet(); //Creating a bet object for each registration - bet object contains name and bet vector of that bettor
private Bet bets = new Bet();
int i=0;
int j=0;
public void dataentry() {
for(j=0;j<size;j++) { //for external - from J that controls the total bets that will be registered
totalBets[j] = new Bet(); //Creating a bet object for each registration - bet object contains name and bet vector of that bettor
System.out.println("Enter the name of the Player:");
totalStakes[j].setName(input.next()); //setting the player's name
// loop to set the guesses
System.out.println("Please enter guesses for each Sports Lottery game");
System.out.println("1 - Winner Team A, 2 - Winner Team B and 0 - Tie");
for ( i=0;i<bets.vetorApostas.length;i++) // receive the bet until it reaches 6
{
System.out.println("Game "+i +":");
totalStakes[j].vectorStakes[i] = input.nextInt(); // receive the user's bets
while (totalApostas[j].vectorApostas[i] < 0 ) // if the user enters a negative number it says to try again
{
System.err.println("Negative Number, try again:");
totalBets[j].vectorBets[i]= entry.nextInt();
}
if (totalApostas[j].vetorApostas[i] > 2) // if the number is greater than 2 it says to try again
{
while (totalBets[j].vectorBets[i] > 2 ) {
System.err.println("Please enter numbers between 0 and 2");
totalBets[j].vectorBets[i]= entry.nextInt();
}
}
}
}
}
/*public void dataoutput() {
//System.out.println("The player's name is:"+total Bets[i].getName());
System.out.println("Your Bet:");
for ( i=0;i < Bet.vectorBeats.length; i++){
System.out.print(+TotalStakes[i].vectorStakes[i].getStakes(i)+ " ");
}
}
public void dataoutput() {
System.out.println("Your Bet::");
for (j=0; j<totalBets[i].vectorBets.length; j++) {
System.err.print("Player "+Total Bets[j].getName()+" ");
for (i = 0; i < totalBets[i].vectorBets.length; i++) {
System.err.print(total Bets[j].vector Bets[i] + " ");
}
}
}*/
public void totalOfBets(int size) {
this.size = size;
}
public int getSize() {
return size;
}
}
TEMPLATE:
public class Template {
//private String name;
public static int[]vectorTemplate =new int [6];
public int getBet(int i) {
return this.vectorTemplate[i];
}
public void setBets(int[] bets) {
this.vectorTemplate = bets;
}
public int getTemplate(int i) {
return this.vectorTemplate[i];
}
public void setTemplate(int[] bets) {
this.vectorTemplate = bets;
}
}
READ TEMPLATE:
import java.util.Arrays;
import java.util.Scanner;
public class ReadTemplate {
private Template template = new Template();
Input Scanner = new Scanner (System.in);
int guesses;
int counter=0;
int j;
int x;
int i;
public void getTemplate() {
System.out.println(" ");
for ( j=0;j<6;j++) // Receive numbers until it reaches 6
{
System.out.println("Now Enter Game Template: "+j);
template.vectorTemplate[j]= entry.nextInt(); // Receive user numbers
while (template.vetorTemplate[j] < 0 ) // If you enter a negative number, ask the user to type again
{
System.err.println("Negative Number, try again:");
template.vectorTemplate[j]=input.nextInt();
}
if (template.vectorTemplate[j] > 2) // if the number is greater than 2 ask again
{
while (template.vectorTemplate[j] > 2 )
{
System.err.println("Please enter numbers between 0 and 2");
template.vectorTemplate[j]=input.nextInt();
}
}
}
//printing the template
System.out.println("Template:");
for (i = 0; i < template.vectorTemplate.length; i++) {
System.out.print(template.vectorTemplate[i] + " ");
}
}
}
GENERATE RESULTS:
public class GenerateResult extends ReadTemplate {
private Bet bets = new Bet();
private Template template = new Template();
//private v_bets v_bets = new v_bets();
private int size;
public void generateResult() {
//Checking if it's right
int x;
V_Bets a = new V_Bets();
for(j=0;j<2;j++) {
int i=0;
int counter=0;
for (x = 0; x < template.vectorTemplate.length; x++) {
if (a.totalStakes[j].vectorStakes[i] == template.vectorTemplate[x]) {
counter++;
}
i++;
}
System.out.println(" ");
System.out.println("Counter of Equals! "+counter);
if (counter <= 5){
System.out.println("Player "+a.Total Bets[j].getName());
System.out.println("Try again, this time you won");
}
else if (counter == 6){
System.out.println("Player "+a.Total Bets[j].getName());
System.out.println("WINNER,CONGRATULATIONS!");
}
}
}
public void totalOfBets(int size) {
this.size = size;
}
}
I am immensely grateful to anyone who can help understand where I went wrong and how to evolve.

Add a highscore to a simple maths game

I am making a simple maths game, with 20 addition, subtraction and multiplication questions. I am trying to add a highscore functionality that appears at the end with the score that shows the user if they have beaten the highscore, and if they havent what the highscore currently is.
Below is the code i have so far for the game.
package au.edu.usc.mathgame;
import java.util.Random;
import java.util.Scanner;
/**
* A simple console-based maths quiz for primary school children.
*
*
public class Main {
public static void main(String[] args) {
Random rand = new Random();
Scanner input = new Scanner(System.in);
int score = 0;
// now ask some random addition questions.
for (int i = 0; i < 10; i++) {
int a = rand.nextInt(20);
int b = rand.nextInt(20);
int questionType = rand.nextInt(3);
Question q = new Question(a, b, questionType);
q.showQuestion();
// Code to print test results
int response = input.nextInt();
boolean result = q.checkAnswer(response);
if (result) {
score = score + 1;
}
}
System.out.printf("Your Total Score is %2d ",score);
}
}
package au.edu.usc.mathgame;
import java.util.Random;
public class Question {
private int value1;
private int value2;
private int answer;
private int questionType;
private String operator;
public Question(int a, int b, int questionType) {
value1 = a;
value2 = b;
Random rand = new Random();
// Sets the operator based on the question type and calculates the answer
if (questionType == 0) {
operator = "+";
answer = a + b;
}
else if (questionType == 1) {
operator = "-";
answer = a - b;
}
else if (questionType == 2) {
operator = "*";
answer = a * b;
}
}
/**
* Selects operator and prints question.
*
*
*/
public void showQuestion() {
System.out.printf("What is %2d %s %2d? ", value1, operator, value2);
}
// checks and prints answers
public boolean checkAnswer(int response) {
if (response == answer) {
System.out.printf(" Yes!\n");
return true;
} else {
System.out.printf(" No, the answer is %d.\n", answer);
return false;
}
}
}
This is a very simple game and i just want to add a highscore functionality
You can maintain a text file which contains the high score. Whenever your game is finished you should read that file and compare it with the current player score. If its less than the high score, Display the high score on screen else replace the value inside the file with the current player score.
For how to read and write the file in java, you can reference the below link:
Java - Files and I/O

Get int variables within a String method Java

This is homework. Just going to put that out there. I feel it is best to show my code first and explain what I'm attempting to do
import java.util.Scanner;
public class Question1 {
public static void main(String[] args){
int length, odd, even, largest;
int n = getNumber();
length=odd=even=largest=initialize();
String sequence=createSequence(n, largest, odd, even, length);
displaySequence(sequence);
displayStatistics(largest, length, odd, even);
}
private static int getNumber(){
Scanner kb = new Scanner(System.in);
System.out.println("Enter the value of the number: ");
int number = kb.nextInt();
return number;
}
private static int initialize(){
return 0;
}
public static String createSequence(int n, int largest, int odd, int even, int length){
String sequence="";
sequence+=n+" ";
while (n!=1){
n = (n%2==0) ? n/2 : 3*n+1;
System.out.print(", "+n);
sequence+=n+" ";
if(n%2==0){ even++;
}else{ odd++;}
if(n>=largest){ largest = n;
}
length++;
}
return sequence;
}
private static void displaySequence(String sequence){
System.out.println(sequence);
}
public static String displayStatistics(int length, int even, int odd, int largest){
String nil = "";
System.out.println("The largest number in the sequence was "+largest);
System.out.println("The length of the sequence was "+length);
System.out.println("There were "+odd+" odd numbers");
System.out.println("There were "+even+" even numbers");
return nil;
}
}
I need attempting to display the largest number in the sequence, the length of the sequence, how many even numbers there were in the sequence and how many odd numbers there were in the sequence. But since I cannot return an int value in the createSequence method, I cannot get the new values for each statistic. Preventing me from displaying said statistics. How would I access these new variables to be used in the final method?
Note:
Requirements:
Declare variables in main
Initialize variables in Initialize()
createSequence (Create the sequence)
displaySequence (Then display the sequence in a separate method)
finally displayStatistics i.e. length, evens, odds, largest (in its own method), this is the one that's troubling me
Try reimplementing your code off of my basecode
public class Question{
public class NumberStats {
int len;
boolean isOdd;
}
private ArrayList<NumberStats> stats = new ArrayList<>();
public static void main(String[] args){
Question q = new Question();
Scanner kb = new Scanner(System.in);
String number = "";
do {
System.out.println("Enter a series of numbers or q to quit: ");
number = kb.next();
q.stats.add(q.parseNumber(number));
} while (number.equals("q")==false);
q.printSummary();
}
private void printSummary(){
int oddCount = 0;
int evenCount = 0;
int longestNumber = 0;
for (NumberStats s : stats){
if (longestNumber<s.len){
longestNumber = s.len;
}
if (s.isOdd){
oddCount+=1;
} else {
evenCount+=1;
}
}
System.out.println(String.format("Longest number length was : %i, Odd Numbers: %i, Even Numbers: %i",longestNumber,oddCount,evenCount));
}
private NumberStats parseNumber(String number){
NumberStats stats = new NumberStats();
Integer lastNumber = Integer.parseInt(String.valueOf(number.charAt(number.length()));
stats.isOdd = true;
if (lastNumber%2==0){
stats.isOdd = false;
}
stats.len = number.length();
return stats;
}
}
Your teacher may be a bit more impressed if you created a Sequence class. The class attributes would be the stats (which could be accessed via getter methods). The createSequence method would become the constructor. And you could implement a toString method to return a string representation of the contents.

Reroll dices in yahtzee game

I´m trying to create a simple yahtzee game where an array is filled with 5 random numbers and where the player can choose to roll specific dices again. However I cant figure out how to write the method that is supposed to replace specific numbers in the array with new random numbers and return it. Any suggestions how to approach this?
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class YatzyGame {
private final Integer NBROFDICE = 5;
private final Integer DICEMAXVALUE = 6;
Random rnd = new Random();
Scanner keyboard = new Scanner(System.in);
public void startGame() {
int[] dice = new int[NBROFDICE];
rollDice(dice);
printDice(dice);
System.out.println("Do you want to reroll any dices? " + "Y/N");
String answer = keyboard.nextLine();
if (answer.equalsIgnoreCase("y")) {
rerollDice(dice);
} else if (answer.equalsIgnoreCase("n")) {
calculateSum(dice);
} else {
System.out.println("Wrong command!");
}
}
public int[] rollDice(int[] dice) {
for (int i = 0; i < dice.length; i++) {
dice[i] = rnd.nextInt(DICEMAXVALUE) + 1;
}
return dice;
}
public int[] rerollDice(int[] dice) {
System.out.println("What dices do you want to reroll? Dices index are 0-4");
int diceToReroll = keyboard.nextInt();
// Replace the numbers at the index the user specifies with new random numbers and return the array.
}
public void printDice(int[] dices) {
System.out.println("Your dices show: " + Arrays.toString(dices));
}
public void calculateSum(int[] dices) {
int sum = 0;
for (int i : dices) {
sum += i;
}
if (sum == 30) {
System.out.println("YAHTZEE! Your total score is 50! Congratulations!");
} else
System.out.println("Your total score is: " + sum);
}
public static void main(String[] args) {
new YatzyGame().startGame();
}
}
public int[] rollDice(int[] dice) {
System.out.println("What dice do you want to reroll? Dices index are 0-4");
int diceToRoll = keyboard.nextInt();
dice[diceToRoll] = rnd.nextInt(DICEMAXVALUE) + 1;
}
Like this you can make a function:
public int[] reroll(int amountOfRerolls, int[] dices){
for(int i =0;i<dicesToReroll;i++){
this.rollDice(dices);
}
return dices;
}
This makes the programm a bit more modal since you can reuse your rollDice() method wherever you need it. Also you could expand it a bit by handing in the indexes that are allowed to be rerolled in case needed.
edit: style

How do I calculate and display win/loss for two different teams in Java using a boolean function and arrays

I am still new to Java and have an assignment that I am stuck on. I believe I got the boolean function correct, however I cannot figure out what to write in the main function.
This the assignment:
Write a public function (static method) winner(int points1,int points2) that takes two scores and returns a boolean. If points1 is greater than points2 the function returns true and if points1 is less than points2, the function returns false. Points should not be tied but return false if that ever happens. The function returns false if none of the conditions is true.
In your main function, create two arrays -the first array is team 1’s points and the second array is opponents’ points in corresponding games, i.e., the first items in the arrays are the scores for each team in the first game and so on. The arrays are the same length.
Using the function winner from above, calculate and print the win/loss record of team1. If all games were won, print out a message saying that team1 has a perfect record. Here are some examples:
Team1 Points
{23,45,65,20}
Opponent Points
{56,67,20,18}
This is what teamRecord should print:
Team1 Record
Win 2
Loss 2
My code so far
import java.util.*;
public class TeamScore {
public static boolean createWinner(int points1, int points2)
{
if (points1 > points2)
{
return true;
}
else
{
return false;
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] team1Array = new int[4];
int[] team2Array = new int[4];
int result1 = 0;
int result2 = 0;
int team1Score;
int team2Score;
int win;
int loss;
System.out.println("Enter Team 1 points: ");
team1Score = Integer.parseInt(in.nextLine());
System.out.println("Enter Team 2 points: ");
team2Score = Integer.parseInt (in.nextLine());
for (int i=0; i <team1Array.length; i++)
{
createWinner(points1);
}
System.out.println("Win"+ team1Score);
//System.out.println(result2+"");
}
}
There are a lot of issues in your code :
1) You declared a function createWinner(int points1, int points2) , but in your main you call createWinner(points1)
2) In your main, what's points1? You didn't declare it.
3) Before computing, you should populate your arrays
After this explanation, you can modify your code with following :
import java.util.*;
public class TeamScore {
public static boolean createWinner(int points1, int points2)
{
if (points1 > points2)
{
return true;
}
else
{
return false;
}
return false;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] team1Array = new int[4];
int[] team2Array = new int[4];
int team1Score = 0;
int team2Score = 0;
for (int i =0; i<4; i++) {
System.out.println("Enter Team 1 points: ");
team1Array[i]= Integer.parseInt(in.nextLine());
System.out.println("Enter Team 2 points: ");
team2Array[i] = Integer.parseInt(in.nextLine());
}
for (int i=0; i <4; i++)
{
if (createWinner(team1Array[i],team2Array[1])) {
team1Score+=1;
} else {
team2Score+=1;
}
}
if(team1Score>0 && team2Score == 0){
System.out.println("Team 1 has perfect record !");
}else{
System.out.println("Win "+ team1Score);
System.out.println("Loss "+ team2Score);
}
}
}
Less or more should work (I didn't try).
Take the input from user 4 times and store it in an array using for loop:
for (int i =0; i<4; i++) {
team1Array[i]= //take user input for team1
team2Array[i] = //take user input for team2
}
Then you could loop over array and increase individual score like:
for (int i=0; i <team1Array.length; i++) {
if (createWinner(points1)) {
//increment team1Score;
} else {
//increment team2Score;
}
}
Compare individual score using if and announce the winner by printing onto console.

Categories