Add a highscore to a simple maths game - java

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

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.

Java using multiple methods in the program

I have the following code on Java which works fine now but I'm wondering how to make the same program but with multiple methods (object oriented programming). Right now all the code is in the main method and I'd like to make it so it has at least one other method where the calculations are made and that method would be called in the main method.
The program asks the user different kinds of multiplication questions like 2*3, 9*5 and so on
import java.util.Random;
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
Random number = new Random();
while (true) {
int nmb1 = number.nextInt(10) + 1;
int nmb2 = number.nextInt(10) + 1;
int multi = nmb1 * nmb2;
int question;
// read the user's input ...
do {
question = Integer.parseInt(JOptionPane.showInputDialog("How much is" + nmb1 + "*" + nmb2));
if (question != multi) {
JOptionPane.showMessageDialog(null, "Wrong, try again");
}
}
while (question != multi);
// .. and repeat until the user types the correct answer
JOptionPane.showMessageDialog(null, "Right");
}
}
}
If anyone can offer any help I would appreciate it.
You can simply wrap up your calculation and user input in a method call multiplication() as shown in the code below. The method will return a boolean value to identify if the user has answer the question correctly. HTH.
import java.util.Random;
import javax.swing.JOptionPane;
public class Main{
public static void main(String[] args) {
boolean correctAnswer;
Random number = new Random();
int nmb1;
int nmb2;
int multi;
while (true) {
nmb1 = number.nextInt(10) + 1;
nmb2 = number.nextInt(10) + 1;
multi = nmb1 * nmb2;
// read the user's input ...
do {
correctAnswer = multiplication(nmb1,nmb2,multi);
}
while (correctAnswer != true);
// .. and repeat until the user types the correct answer
JOptionPane.showMessageDialog(null, "Right");
}
}
public static boolean multiplication(int number1,int number2,int answer)
{
int question;
question = Integer.parseInt(JOptionPane.showInputDialog("How much is" + number1 + "*" + number2));
if (question != answer) {
JOptionPane.showMessageDialog(null, "Wrong, try again");
return false;
}
return true;
}
}

What is the best method to get the index of a String or Char Array?

I would like to know what is the best way to get the index of a specific letter in a word. The reason i am doing this, is because i am making and modifying a Hangman game. I am already done with the game and it works good, however i want to implement a score based system. I created a method called keepScore() that takes a boolean value to see if the answer is right or wrong. If it is right, i am going to add 10 points for each letter found. If its wrong, i will deduct 10 points. My method keepScore() is implemented incorrectly any help?
Hangman.java
import Game.Game;
import Prompter.Prompter;
/* This class is the main class that starts the game.
* It instantiates the Game and Prompter objects.
*/
public class Hangman {
public static void main(String[] args) {
//Check if an argument has been passed, we expect the answer to be passed
if(args.length == 0) {
System.out.println("Expected: Java Hangman <answer>");
System.err.println("Answer is required!");
System.exit(1);
}
System.out.println("Welcome to Hangman!");
//Create an instance of our game
Game game = new Game(args[0]);
//Create an instance of our prompter
Prompter prompter = new Prompter(game);
//Starts the game
while (game.getRemainingTries() > 0 && !game.isWon()) {
prompter.displayProgress();
prompter.promptForGuess();
}
//Displays the outcome of the game
prompter.displayOutcome();
}
}
Game.java
package Game;
/* This class is responsible for implementing the game
* logic.
*/
public class Game {
//Declare our member variables
public final static int TOTAL_TRIES = 3;
public final static int MAX_SCORE_POINTS = 10;
private String mAnswer;
private String lettersHit;
private String lettersMissed;
private int score;
//Default constructor
public Game(String answer) {
//Initialize our member variables
mAnswer = answer.toLowerCase();
lettersHit = "";
lettersMissed = "";
}
//This method checks to see if the letter was a hit or a miss
public boolean checkLetter(char letter){
letter = validateGuess(letter);
boolean isHit = mAnswer.indexOf(letter) != -1;
//If correct
if (isHit) {
//Add the letter to the lettersHit pool
lettersHit += letter;
keepScore(isHit);
System.out.println("Hit! Score: " + score);
}else {
//Add the letter to the lettersMissed pool
lettersMissed += letter;
keepScore(isHit);
System.out.println("Missed! Score: " + score);
}
return isHit;
}
private void keepScore(boolean isHit) {
if(isHit) {
for (int i = 0; i < lettersHit.length(); i++) {
score += MAX_SCORE_POINTS;
}
} else {
for (int i = 0; i < lettersMissed.length(); i++ ) {
score -= MAX_SCORE_POINTS;
}
}
}
/*
This method handles an empty string input. For example,
if the user were to press enter on input a 0 length String
will cause the program to crash.
*/
public boolean checkLetter(String letters) {
if (letters.length() == 0) {
throw new IllegalArgumentException("No letter entered");
}
return checkLetter(letters.charAt(0));
}
//This method validates the user guess
private char validateGuess(char letter) {
//If the character is not a letter
if (!Character.isLetter(letter)) {
//Ask user for a valid letter
throw new IllegalArgumentException("A letter is required!");
}
//If entry was valid, convert character to lowercase
letter = Character.toLowerCase(letter);
//Check if the letter has been guessed already
if (lettersHit.indexOf(letter) != -1 || lettersMissed.indexOf(letter) != -1) {
throw new IllegalArgumentException("The letter " + letter + " has already been guessed");
}
return letter;
}
//This method keeps track of the user's game progress
public String getCurrentProgress() {
String progress = "";
//For each character in the array of strings of mAnswer
for (char letter : mAnswer.toCharArray()) {
char display = '-';
if (lettersHit.indexOf(letter) != -1){
display = letter;
}
progress += display;
}
return progress;
}
//Get the current remaining tries
public int getRemainingTries() {
return TOTAL_TRIES - lettersMissed.length();
}
//Get the current answer
public String getAnswer() {
return mAnswer;
}
//This method checks if the game is won.
public boolean isWon() {
return getCurrentProgress().indexOf('-') == -1;
}
public int getScore(){
return score;
}
}
Prompter.java
package Prompter;
import Game.Game;
import java.util.Scanner;
/* This class is responsible for displaying instructions and information to the user
* regarding the game.
*/
public class Prompter {
//The game object
private Game mGame;
private boolean isHit;
private boolean acceptable;
//Default constructor
public Prompter(Game game) {
//Get the instance of our game
mGame = game;
isHit = false;
acceptable = false;
}
//This method prompts the user for a guess
public boolean promptForGuess() {
//Create an instance of scanner
Scanner scanner = new Scanner(System.in);
//Loop for input
do {
System.out.println("Please enter a letter: ");
String guess = scanner.nextLine();
try {
isHit = mGame.checkLetter(guess);
acceptable = true;
}catch (IllegalArgumentException iae) {
System.out.printf("%s. Please try again!%n", iae.getMessage());
}
} while (!acceptable);
return isHit;
}
//This method displays the progress
public void displayProgress() {
System.out.printf("You have %d tries to guess the answer" +
" before you are taken to the gallows. Try to solve: %s%n", mGame.getRemainingTries(),
mGame.getCurrentProgress());
}
//This method displays the outcome of the game
public void displayOutcome() {
if( mGame.isWon()) {
System.out.printf("Congratulations! you won with %d tries remaining.%n" +
"Your total score: %d%n", mGame.getRemainingTries(), mGame.getScore());
}else {
System.out.printf("Bummer! The answer was: %s", mGame.getAnswer());
}
}
}
Look at this method of yours:
private void keepScore(boolean isHit) {
if(isHit) {
for (int i = 0; i < lettersHit.length(); i++) {
score += MAX_SCORE_POINTS;
}
} else {
for (int i = 0; i < lettersMissed.length(); i++ ) {
score -= MAX_SCORE_POINTS;
}
}
}
It doesn't add MAX_SCORE_POINTS times the number of good letters you just found, it does so with the number of good letters in lettersHit. Now, what is in lettersHit ? Well, there is all the letters you found since the start.
So you'll have :
word to guess: anaconda
letter: a
lettersHit = "a", score += (lettersHit.length * 10) = 10
letter: c
lettersHit = "ac", score += (lettersHit.length * 10) = 30
You could just use StringUtils.countMatches(mAnswer, letter); to get the number of occurence, hence the score.

I'm wanting to test which of two integers is closest to a third int in Java

I feel like this has an extremely obvious answer, so forgive me if I'm being stupid.
I'm creating a simple text-based game for elementary school kids in which the user, playing as a mage, needs to ward off mighty dragons by mixing together various spell cards (in my case, multiplying their values together to try and get the closest to the dragon's weakness number). This weakness number changes every turn, until the dragon hits an HP less than or equal too 0, at which point another dragon will spawn and the player will have to ward that one off too. The entire project takes up five classes, one for the player, another for the cards, another for the dragon, another for the game's play methods, and a fifth, the driver.
The first thing that comes to mind for me is to make a method in Player.java that goes something like this:
public int isClosestToo(int num, int max){
int counter = 0;
for(int i = num; i <= max; i++){
counter++
}
return counter;
}
followed by an if statement in my game class' play method:
if(isClosestToo(num1) > isClosestToo(num2){
/*do something*/
}
I realize that this would work, but I want to make sure I'm not missing something blatantly obvious and simpler that I could do. Some method in the Integer class maybe?
Please keep in mind this is a very early version of the project, and I hope to implement Slick2D graphics later.
Here's all of my code thus far:
From Game.java:
import java.util.Scanner;
public class Game {
Scanner scan = new Scanner(System.in);
public Game(){}
public void play(){
Player p = new Player();
while(p.getHP() > 0){
Dragon d = new Dragon();
System.out.println("You have " + p.getHP() + " HP");
System.out.println(d);
System.out.println(p.elementHandToString());
System.out.println(p.attackHandToString());
System.out.println("Choose the two cards that multiply to be closest too the weakness of the dragon for the most damage!");
int element = scan.nextInt();
int attack = scan.nextInt();
int damage = d.getWeakness() - (p.getElementCard(element - 1).getNum() * p.getAttackCard(attack - 1).getNum());
d.setHP(d.getHP() - damage);
p.afterTurn(element, attack);
d.newWeakness();
}
}
}
And Player.java:
import java.util.Random;
import java.util.ArrayList;
public class Player {
Random r = new Random();
int hp;
ArrayList<Card> attackHand;
ArrayList<Card> elementHand;
ArrayList<String> elements;
ArrayList<String> attacks;
public Player(){
this.hp = 100;
this.genHands();
attackHand = new ArrayList<Card>();
elementHand = new ArrayList<Card>();
//arraylist of types of elements, feel free to add more using the .add method
elements = new ArrayList<String>();
elements.add("Fire");
elements.add("Ice");
elements.add("Water");
elements.add("Air");
elements.add("Rock");
elements.add("Mana");
//arraylist of types of attacks, feel free to add more using the .add method
attacks = new ArrayList<String>();
attacks.add("Projectile");
attacks.add("Self");
attacks.add("Explosion");
attacks.add("Repeated");
attacks.add("Debuff");
attacks.add("Melee");
}
public Player(int hp){ this.hp = hp; }
public int getHP(){ return hp; }
public ArrayList<Card> getAttackHand(){ return attackHand; }
public ArrayList<Card> getElementHand(){ return elementHand; }
public Card getAttackCard(int whichCard){ return attackHand.get(whichCard); }
public Card getElementCard(int whichCard){ return elementHand.get(whichCard); }
public void afterTurn(int element, int attack){
attackHand.add(new Card(genRand(1, 12), attacks.get(genRand(1, 12))));
elementHand.add(new Card(genRand(1, 12), elements.get(genRand(1,12))));
attackHand.remove(attack - 1);
elementHand.remove(element - 1);
}
public String elementHandToString(){ return "Card 1: " + elementHand.get(0) + "/nCard 2: " + elementHand.get(1) + "/nCard 3: " + elementHand.get(2) + "/nCard 4: " + elementHand.get(3); }
public String attackHandToString(){ return "Card 1: " + attackHand.get(0) + "/nCard 2: " + attackHand.get(1) + "/nCard 3: " + attackHand.get(2) + "/nCard 4: " + attackHand.get(3); }
//generates the player's hands
public void genHands(){
//creates a deck of random elemental cards
for(int x = 0; x <= 4; x++){
elementHand.add(new Card(genRand(1, 12), elements.get(genRand(0, elements.size() - 1))));
}
//creates a deck of random attack cards
for(int i = 0; i <= 4; i++){
attackHand.add(new Card(genRand(1, 12), attacks.get(genRand(0, attacks.size() - 1))));
}
}
//returns a random integer between min and max
//#param1 minimum number for random to be
//#param2 maximum number for random to be
public int genRand(int min, int max){ return r.nextInt(max) + min; }
}
Dragon.java:
package alchemy;
import java.util.Random;
public class Dragon {
int hp;
int weakness;
Random r = new Random();
public Dragon(){
hp = genRand(1, 144);
weakness = genRand(1, hp);
}
public int getHP(){
return hp;
}
public void setHP(int newHP){
hp = newHP;
}
public String toString(){
return "A dragon with " + hp + "HP has appeared!" + "/nIts current weakness is " + weakness + "/nPlay two cards that multiply to a number close to its weakness for damage!";
}
public int getWeakness(){
return weakness;
}
public void newWeakness(){
weakness = genRand(1, hp);
}
public int genRand(int min, int max){
return r.nextInt(max) + min;
}
}
And lastly, Card.java:
import java.util.Random;
public class Card{
int num;
Random r = new Random();
String element;
public Card(){
num = 0;
element = "n/a";
}
public Card(int n, String e){
num = n;
element = e;
}
public int getNum(){
return num;
}
public String getElement(){
return element;
}
public String toString(){
return "This is a " + element + "card with a value of " + num + ".";
}
}
Primarily, the issue I'm running into is the play() loop of the Game class, where I need to calculate the damage that the player does. Obviously, (before I program in elemental logic), I want that damage to actually do damage instead of ending up as a negative number and making the dragon gain HP. Any and all help would be greatly appreciated. Thank you!
-Nick
In java, when a method starts with "is", it returns boolean. But your project probably maintained by you yourself, it can be whatever you want.
Your isClosestToo method, takes in 2 arguments, which is num and max, both integer, but when you call it, you only takes in one argument.
public int isClosestToo(int num, int max){
int counter = 0;
for(int i = num; i <= max; i++){
counter++
}
return counter;
}
if(isClosestToo(num1) > isClosestToo(num2){
/*do something*/
}
the method name itself is confusing, you can do public int ClosestTo(int[] num,int max) to take and a list of number and return the closest number or do DiffMax(int num) to take in a number and subtract it with the max, in which this case your max must be accessible in the method scope.
public int ClosestTo(int[] num,int max)
{
1.declare a variable to store the closest num
2.for every element in num, if Math.abs(max-num) < closestNum, store num to closestNum
3.return closestNum
}
or
public int DiffMax(int num)
{
1. return Math.abs(max-num) < closestNum
}
then you can do
if(DiffMax(num1) > DiffMax(num2){
/*do something*/
}
this is an option
if((max-int1)>(max-int2) && max-int2>=0){
//do something with int2
}
else if((max-int1)<(max-int2) && max-int1>=0){
//do something with int1
}
else if(max-int1>=0){
//do something with int1
}
else if(max-int2>=0){
//do something with int2
}
else{
//do something if conditions aren't met
}

Do not why Array not storing numbers in 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.

Categories