I have a dice class that rolls random numbers from 1-6. I want to create another class that implements checking of all numbers and stops rolling when all unique numbers are rolled once. Not sure how I would use the getFace and boolean method. Thinking of every number starting at false and outcomes true once number appears.
public class Die {
public final int MAX = 6; //max 6
private int faceValue; //current value showing on die
//constructor
public Die() {
faceValue = 1;
}
public int roll(){
faceValue = (int)(Math.random()*MAX)+1;
return faceValue;
}
public void setFaceValue(int value){
if(value> 0 && value <=MAX)
faceValue=value;
}
public int getFaceValue(){
return faceValue;
}
public String toString(){
String result = Integer.toString(faceValue);
return result;
}
}
ArrayList<Integer> numList = new ArrayList<Integer>();
//Add 1-6
for(int i = 1;i < 7;i++){
numList.Add(i);
}
Die dice = new Die();
While(numList.size() != 0){
int rolled = dice.roll();
ArrayList.remove(rolled);
}
I assume the code goes something like that. Haven't touch java for a bit.
Logic:
Create a set S. Keep rolling and adding the outcome to that set. Stop when the size of the set is 6. (Set contains unique elements only.)
import java.util.HashSet;
import java.util.Set;
public class Play {
public static void main(String[] args) {
Die die = new Die();
Set<Integer> set = new HashSet<>();
int outcome = 0;
//Keep rolling until set size is 6.
while(set.size() != 6) {
outcome = die.roll();
set.add(outcome);
}
System.out.println(set);
}
}
class Die {
public final int MAX = 6; //max 6
private int faceValue; //current value showing on die
//constructor
public Die() {
faceValue = 1;
}
public int roll(){
faceValue = (int)(Math.random()*MAX)+1;
return faceValue;
}
public void setFaceValue(int value){
if(value> 0 && value <=MAX)
faceValue=value;
}
public int getFaceValue(){
return faceValue;
}
public String toString(){
String result = Integer.toString(faceValue);
return result;
}
}
Related
I am working on a lab that requires me to return the number it flips it requires to get heads. I used a for loop, and a while loop but it appears that returning the method values along with the loops is not making the code runnable. I would appreciate the assistance. There are two pieces of codes, each different classes calling upon another class.
import java.util.*;
public class GVCoin {
// true for heads, false for tails
private boolean isHeads;
private int flips, heads;
private Random r;
public GVCoin() {
r = new Random();
heads = 0;
flips = 0;
isHeads = true;
}
public void flip() {
isHeads = r.nextBoolean(); // Flip the coin by randomly choosing true / false
flips++; // Increment flip count
if(isHeads){
heads++; // Increment heads count if current flip results in heads
}
}
public boolean isHeads() {
return isHeads; // Return true if coin is currently heads
}
public String toString() {
String str;
str = "Flips: " + flips + " Heads: " + heads + " isHeads: " + isHeads;
return str; // Return String representation of important values
}
public int numFlips() {
return flips; // Return number of total flips
}
public int numHeads() {
return heads; // Return number of total heads
}
public int numTails() {
return flips - heads; // Return number of total tails
}
public void setToHeads(boolean h) {
isHeads = h;
}
public GVCoin(int seed) { // Create the coin with a random seed
this();
r = new Random(seed);
}
}
public class TossingCoins {
public int flipForHeads(GVCoin coin, int goal) {
int i = 0;
do {
coin.flip();
i++;
} while (i < goal);
return i;
}
public static void main(String[] args) {
TossingCoins game = new TossingCoins();
GVCoin coin = new GVCoin(15); // Create a GVCoin object with seed value 15
int numHeads = 100; // Desire 100 heads
int totalFlips;
totalFlips = game.flipForHeads(coin, numHeads);
System.out.println("Total number of flips for 100 heads: " + totalFlips);
}
}
I suggest you not to use seed when you create Random. If you do, the outcome will be always the same.
Here some working code. I removed some code you wrote which I thought not actually needed. Cheers!
class GVCoin {
private Random r;
public GVCoin() {
r = new Random();
}
public GVCoin(int seed) {
this();
r = new Random(seed);
}
public boolean flip() {
return r.nextBoolean();
}
}
public class TossingCoins {
public int flipForHeads(GVCoin coin, int goal) {
int count = 0;
int numberOfHeads = 0;
while (numberOfHeads < goal) {
count++;
boolean isHead = coin.flip();
if (isHead) {
numberOfHeads++;
}
}
return count;
}
public static void main(String[] args) {
TossingCoins game = new TossingCoins();
GVCoin coin = new GVCoin();
int numberOfHeads = 5;
int totalFlips;
totalFlips = game.flipForHeads(coin, numberOfHeads);
System.out.println("Total number of flips for "+ numberOfHeads + " heads: " + totalFlips);
}
}
I managed to figure out the code. On the method call I simply formatted the code as follows:
int flips = 0;
while (coin.numHeads() < goal) {
coin.flip();
flips++ ;
}
return flips;
Suppose given a class Die and it contains a random value for a six sided die.
Another class PairOfDice needs to access getvalue in Die and store two die values.
An error: cannot find symbol occurs when PairOfDice is executed.
How can this problem be fixed? And are there any other suggestions for the java code?
public class Die {
public static Random rand = new Random();
private int sides; // Number of sides
private int value; // Die's value
public Die() {
sides = 6;
roll();
}
public void roll() {
value = rand.nextInt(sides) + 1;
}
public int getSides() {
return sides;
}
public int getValue() {
return value;
}
The second class given is:
public class PairOfDice {
private int dieOne;
private int dieTwo;
public void main(String[] args){
Die die;
die = new Die();
}
private void dieOne(int value){
dieOne = die.getValue();
}
private void dieTwo(int value){
dieTwo = die.getValue();
}
public int getDieOneValue(){
return dieOne;
}
public int getDieTwoValue(){
return dieTwo;
}
}
This quest should be generalized:
I wrote the Die class with two public constructors. If the constructor is without the parameter, default size of die is six, else you can have any number of sides.
Then, I wrote the Dices class with two constructors. First one have the number of dices (with 6 sides), and second one have the List of dices with preferred sides.
If you want to learn how to generalize the problem (any problem) you can check my code. (Of course, it can be done more efficiently and with more elegance, but here is the simple code):
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
class Die {
private Random RAND = new Random();
private int noOfSides;
private int value;
// Default constructor without the parameter of sides gives the six sized die
public Die() {
this.noOfSides = 6;
}
// The constructor WITH number of sides
public Die(int noOfSides) {
this.noOfSides = noOfSides;
}
// rolling the die
public void roll() {
this.value = RAND.nextInt(noOfSides) + 1;
}
public int getValue() {
if (value == 0) roll(); // if the die is never rolled -> roll it!
// else return the rolled value
return value;
}
// just for curiosities
public int getNoOfSides() {
return noOfSides;
}
public String toString() {
return "Die has the " + noOfSides + " sides, and the last roll value was " + getValue();
}
}
class Dices {
private int noOfDices;
private List<Die> myDices = new ArrayList<Die>();
// NO constructor without the number of dices
private Dices() {
}
public Dices(int noOfDices) {
this.noOfDices = noOfDices;
// example is for 6 sided dices
for (int i = 0; i < noOfDices; i++) {
getMyDices().add(new Die());
}
}
// example with the list of dices with predefined sizes
public Dices(List<Die> myDices){
this.myDices = myDices;
}
public List<Die> getMyDices() {
return myDices;
}
public String toString() {
String s = "";
for (Die die : getMyDices()) {
s = s + die + "\n";
}
return s;
}
}
public class Answer {
public static void main(String[] args) {
//test with two dices (6 size):
Dices twoDices = new Dices(2);
System.out.println(twoDices);
//test with 4 dices size 3, 7, 9, 22
Dices fourDices = new Dices
(List.of(new Die(3),
new Die(7),
new Die(9),
new Die(22)));
System.out.println(fourDices);
}
}
You can see, if the die is never rolled, getValue first roll the die, then return the value. Otherwise you can roll the die and the value will be stored into the private field value...
We will presume that the Die class works as expected.
So, one could think of these changes to PairOfDice that likely resolve the immediate issue.
public class PairOfDice {
private Die dieOne = new Die();
private Die dieTwo = new Die();
public static void main(String[] args) {
PairOfDice pair = new PairOfDice();
System.out.printf("Pair: %d - %d%n", pair.getDieOneValue(), pair.getDieTwoValue());
}
public int getDieOneValue() {
dieOne.roll();
return dieOne.getValue();
}
public int getDieTwoValue() {
dieTwo.roll();
return dieTwo.getValue();
}
}
The PairOfDice class should hold references to two dice (in the private Die instance variables).
The getDieXValue() methods work with the instance variables, and return a value, after generating a roll().
Now, the question is whether the requirement is to store the values of two dice, or just access to the ability to get the values. If truly the need is to store the values, then one could do:
public class PairOfDice {
private int dieOneValue;
private int dieTwoValue;
public PairOfDice {
Die die = new Die();
// get a value for the first die
die.roll();
dieOneValue = die.getValue();
// get a value for the 2nd die
die.roll();
dieTwoValue = die.getValue();
}
public int getDieOneValue() {
return dieOneValue;
}
...
Personally, if one is going to create objects, then store and use the objects.
OK so I have recently got my program to the point where it is allmost working, however I cant seem to figure out how to make my bug object move.
I have a class called AWorld that is populated with instances of a class method Randfood (ints between 0 and 9) in randomly placed possitions within the grid. It is also passed and instance of my class ABug as an attribute that is placed into the grip according to user input. my problem is I wish to make it move towards the food objects (my ints between 0-9) and when its next to them to have its energy level increased accordingly. it needs to only move towards an object when its within a set distance from it. i.e. 3 spaces in any direction, else just move randomly. my issue is i cant seem to figure out how to do that with my current code setup.
AWorld Class:
package finalversion2;
import java.util.Arrays;
import java.util.Random;
public class AWorld {
int x[] = new int[10], y[] = new int[10];
int row = 25;
int column = 25;
char[][] map;
public static int RandFood(int min, int max) {
Random rand = new Random(); // Initializes the random function.
int RandNum = rand.nextInt((max - min) + 1) + min; //generates a random number within the max and min ranges
return RandNum; //returns the random number
}
//Constructor
//Sets up map array for the AWorld object
//uses a bug that is passed to it
public AWorld(ABug bug) {
ABug bug1 = bug;
map = new char[row][column];
for (int i = 0; i < row; i++) {
for (int x1 = 0; x1 < column; x1++) {
map[i][x1] = ' ';
}
}
for (int i = 0; i < column; i++) {
Random rand = new Random();
int x = rand.nextInt(row);
int y = rand.nextInt(column);
map[x][y] = (char) RandFood(48, 57);
map[bug1.getHPossistion()][bug1.getVPossistion()] = bug1.getSymbol(); // gets the bugs x and y possistion in the array (user defined) and puts it into the symbol variable
}
}
public void PrintWorld() {
for (int i = 0; i < row; i++) //these next two for loops print the array to the screen
{
System.out.print("|");
for (int x1 = 0; x1 < column; x1++) {
System.out.print(map[i][x1]);
}
System.out.println("|");
}
}
}
ABug:
package finalversion2;
public class ABug
{
public static void main(){
}
private String species = new String(); //instance variables (defines data of object)
private String name = new String();
private String description = new String();
private char symbol;
private int hPossistion, vPossistion, energy, iD;
public ABug(){
}
public ABug (String s, String n, String d, int h, int v, int e, int i){
this.species = s;
this.name = n;
this.description = d;
this.symbol = s.charAt(0);
this.hPossistion = h;
this.vPossistion = v;
this.energy = e;
this.iD = i;
}
//setters
public void setSpecies(String s){
this.species = s;
}
public void setName(String n){
this.name = n;
}
public void setSymbol(char symbol){
this.symbol = symbol;
}
public void setHPossistion(int x){
this.hPossistion = x;
}
public void setVPossistion(int y){
this.vPossistion = y;
}
public void setEnergy(int energy){
this.energy = energy;
}
public void setID(int i){
this.iD = i;
}
public void setDescription(String d){
this.description = d;
}
//getters
public String getSpecies(){
return this.species;
}
public String getName(){
return this.name;
}
public char getSymbol(){
return this.symbol;
}
public int getHPossistion(){
return this.hPossistion;
}
public int getVPossistion(){
return this.vPossistion;
}
public int getEnergy(){
return this.energy;
}
public int getID(){
return this.iD;
}
public String getDescription(){
return this.description;
}
public String toString(){
String BugData;
BugData = name + " " + symbol + "\n" + species + "\n" + description;
return BugData;
}
}
enum Direction:
package finalversion2;
public enum Direction {
NORTH, EAST, SOUTH, WEST;
}
now im guessing I need to redraw my map each time i wish it to move using my enum based on a boolean response, i.e. call the printworld method but randomly move the bug. but wont that reprint my random ints?
please help. im very new to java.
Cheers in advance.
I have been stuck on this for sometime now, the objective is to create an array to hold the cards in, once I do create the array print them out the only card that is printing is king of hearts. Why is it not iterating?
public class Card
{
// Card suits (provided for your convenience - use is optional)
public static final int SPADES = 0;
public static final int HEARTS = 1;
public static final int CLUBS = 2;
public static final int DIAMONDS = 3;
// Card faces (provided for your convenience - use is optional)
public static final int ACE = 1;
public static final int TWO = 2;
public static final int THREE = 3;
public static final int FOUR = 4;
public static final int FIVE = 5;
public static final int SIX = 6;
public static final int SEVEN = 7;
public static final int EIGHT = 8;
public static final int NINE = 9;
public static final int TEN = 10;
public static final int JACK = 11;
public static final int QUEEN = 12;
public static final int KING = 13;
// define fields here
private static int suit;
private static int val;
private String[] suits = {"Clubs", "Spades", "Diamonds", "Hearts"};
private String[] vals = {"Ace","2", "3", "4", "5", "6", "7",
"8", "9", "10", "Jack", "Queen", "King" };
// This constructor builds a card with the given suit and face, turned face down.
public Card(int suit, int val)
{
this.val = val;
this.suit = suit;
}
public #Override String toString()
{
return vals[val] + " Of " + suits[suit];
}
// This method retrieves the suit (spades, hearts, etc.) of this card.
public int getSuit()
{
return this.suit;
}
// This method retrieves the face (ace through king) of this card.
public int getFace()
{
// return this.val;
switch(val)
{
case 0 : return 1;
case 1 : return 2;
case 2 : return 3;
case 3 : return 4;
case 5 : return 6;
case 6 : return 7;
case 7 : return 8;
case 8 : return 9;
case 9 : return 10;
case 10 : return 10;
case 12 : return 10;
default : return 0;
}
}
}`
import java.util.ArrayList;
import java.util.Random;
// This class represents the deck of cards from which cards are dealt to players.
public class Deck
{
//array
public static Card[] cards;
// private static ArrayList<Card> cards;
int i;
int counter;
// This constructor builds a deck of 52 cards.
Deck()
{
i = 51;
//array implementation
cards = new Card[52];
int x = 0;
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 13;j++)
{
//Array implementation
cards[x] = new Card(i,j);
x++;
}
}
}
// This method takes the top card off the deck and returns it.
public Card deal()
{
//Array implementation
int index = 0;
Card temp = cards[index];
return temp;
}
// this method returns true if there are no more cards to deal, false otherwise
public boolean isEmpty()
{
if(cards.length == 0)
{
return true;
}
return false;
}
//this method puts the deck int some random order
// public void shuffle()
// {
// for(int i = 51; i > 0; i--)
// {
// int rand = (int) (Math.random() * (i+1));
// Card temp = this.cards[i];
// this.cards[i] = cards[rand];
// cards[rand] = temp;
// }
//
// }
}
public class BlackJack extends Deck
{
public static void main(String []args)
{
System.out.println("Ready to play a game of BlackJack?");
Deck deck = new Deck();
for(int i = 0; i < cards.length;i++)
{
System.out.println(cards[i]);
}
Problem is caused by the following:
// define fields here
private static int suit;
private static int val;
because they are static, all Card instances share these, so they will all have the last value they were set to. Remove the static.
To give you a little hint how you might make the code even easier to read/maintain:
use enums instead of constants. You can give them constructors/member variables just like classes
use for-each-loops, it's way easier to read and prevents the usual off-by-1 problems
type 'static' BEFORE all other modifiers and keep all static variables and members separate from any non-static content. this way you can never mix them up by accident
Bad / unusual sides of this code are:
I use static nested enums and classes. Usually each of those should go into its own file and be non-static
I like to prefix my variables according to their scope so I cannot mess em up: pXxx for Parameter, sXxx for static variables, mXxxx for members, no prefix for method variables
public class CardGame {
static public enum SuitType {
SPADES, HEARTS, CLUBS, DIAMONDS
}
static public enum FaceType {
ACE("Ace", 1), //
TWO("2", 2), //
THREE("3", 3), //
FOUR("4", 4), //
FIVE("5", 5), //
SIX("6", 6), //
SEVEN("7", 7), //
EIGHT("8", 8), //
NINE("9", 9), //
TEN("10", 10), //
JACK("Jack", 11), //
QUEEN("Queen", 12), //
KING("King", 13), //
;
private final String mName;
private final int mValue;
private FaceType(final String pName, final int pValue) {
mName = pName;
mValue = pValue;
}
public String getName() {
return mName;
}
public int getValue() {
return mValue;
}
public int getValue_alternative() {
return ordinal() + 1; // ordinal is the index of the enum, starting at ace=0 ... king=12
// sorting and comparing of suits could also be done by .ordinal() if need be
}
}
static public class Card {
private final SuitType mSuit;
private final FaceType mFace;
public Card(final SuitType pSuit, final FaceType pFace) {
mSuit = pSuit;
mFace = pFace;
}
public SuitType getSuit() {
return mSuit;
}
public FaceType getFace() {
return mFace;
}
#Override public String toString() {
return mFace.getName() + " of " + mSuit + " - " + mFace.getValue() + (mFace.getValue() > 1 ? " points" : " point");
}
}
static public class Deck {
private final ArrayList<Card> mCards;
public Deck() {
mCards = createFullDeck();
}
private ArrayList<Card> createFullDeck() { // can also be static as it dowes not use member cariables => potential factory method
final ArrayList<Card> ret = new ArrayList<>();
for (final SuitType suit : SuitType.values()) {
for (final FaceType face : FaceType.values()) {
final Card c = new Card(suit, face);
ret.add(c);
}
}
return ret;
}
public void shuffleRandomly() {
final ArrayList<Card> tempList = new ArrayList<>();
tempList.addAll(mCards);
mCards.clear();
while (tempList.size() > 0) {
final int index = (int) (Math.random() * tempList.size());
final Card card = tempList.remove(index);
mCards.add(card);
}
}
public void print() {
System.out.println(" - - - DECK BEGINS - - - ");
int counter = 0;
for (final Card c : mCards) {
System.out.println("\t" + c);
++counter;
}
System.out.println("> Printed " + counter + " cards.");
System.out.println(" - - - DECK ENDS - - - ");
}
}
public static void main(final String[] args) {
final Deck d = new Deck();
d.print();
d.shuffleRandomly();
d.print();
}
}
I am trying to learn OOP, starting with Java as I have read and been told it's the best place to start. With that said, I am trying to create a game for fun to help my learning, but I also know game programming and design can be more challenging.
So my goal here is to generate a new value from the RollDice D20 without having to reset or restart the program. You'll notice when I print out the values I print the same instance twice to demonstrate what I am avoiding, and a new instance to show that the new instance does indeed generate a new value. Perhaps, I am not approaching this in the right way, but this is a hurdle I am hoping to overcome with some help!
What I ultimately want is to figure out how to generate a new instance or at least a new roll value as many times as I want. Any and all help is greatly appreciated! I have added the code below as an example. Also any other feedback is appreciated.
import java.util.Random;
class RollDice
{// Begin RollDice Class
// Initiate method rollDice
public static int rollDice(int number, int nSides)
{
// System.out.println( "--- Welcome to the Dice Game v2! ---" ); //
// welcomes player
Random r = new Random();
// Declare class variables
int num = 0;
int roll = 0;
if (nSides >= 3)
{
for (int i = 0; i < number; i++)
{
roll = r.nextInt(nSides) + 1;
// System.out.println("Roll is: " + roll);
num = num + roll;
}
}
else
{
System.out.println("Error num needs to be from 3");
}
return num;
} // end method rollDice
int d4 = rollDice(1, 4);
int d6 = rollDice(1, 6);
int d8 = rollDice(1, 8);
int d10 = rollDice(1, 10);
int d12 = rollDice(1, 12);
int d20 = rollDice(1, 20);
public RollDice()
{
this.d4 = d4;
}
public void setD4(int D4)
{
this.d4 = D4;
}
public int getD4()
{
return d4;
}
// ////////////////
{
this.d6 = d6;
}
public void setD6(int D6)
{
this.d6 = D6;
}
public int getD6()
{
return d6;
}
// ////////////////
{
this.d8 = d8;
}
public void setD8(int D8)
{
this.d8 = D8;
}
public int getD8()
{
return d8;
}
// ////////////////
{
this.d10 = d10;
}
public void setD10(int D10)
{
this.d10 = D10;
}
public int getD10()
{
return d10;
}
// ////////////////
{
this.d12 = d12;
}
public void setD12(int D12)
{
this.d12 = D12;
}
public int getD12()
{
return d12;
}
// ////////////////
{
this.d20 = d20;
}
public void setD20(int D20)
{
this.d20 = D20;
}
public int getD20()
{
return d20;
}
// ////////////////
}// End RollDice Class
class Champion
{// Begin Champion Class
RollDice champDice = new RollDice();
int champroll = champDice.getD20();
public Champion()
{
this.champroll = champroll;
}
public void setChampRoll(int ChampRoll)
{
this.champroll = ChampRoll;
}
public int getChampRoll()
{
return champroll;
}
}// End Champion Class
public class DiceRollTest
{
public static void main(String ars[])
{
Champion tChampion = new Champion();
Champion pChampion = new Champion();
System.out.println("Your Champion defends with a " + tChampion.getChampRoll() + "\n");
System.out.println("Your Champion defends with a " + tChampion.getChampRoll() + "\n");
System.out.println("Your Champion defends with a " + pChampion.getChampRoll() + "\n");
}
}
Your RollDice class is not accomplishing what you want. All it's doing is storing a single dice roll result for each type of dice you have. Therefore, when you go an call getChampRoll() on your Champion object, all it's doing is returning the roll that already took place when you constructed your RollDice class.
Instead, you should make rollDice() a member function of your RollDice class. RollDice should then take in its constructor an argument indicating which dice should be rolled when rollDice() is called. That way, when you call getD20(), it will roll the D20 and give you the result.
I'll leave you with this as a starting point:
import java.util.Random;
public class Die {
private int mSides;
private Random mRandom;
public Die(int sides) {
this.mSides = sides;
mRandom = new Random(System.currentTimeMillis());
}
public int roll() {
return mRandom.nextInt(mSides + 1);
}
public int roll(int times) {
int sum = 0;
for (int i = 0; i < times; i++) {
sum += roll();
}
return sum;
}
}
This class can be inherited/subclassed for each dice you want to create. Then you can toss a few of these in your champion's pockets :)
First, you should create new Constructor. In this constructor you should inicialize Random object, and probably how many sides will dice have
class RollDice{
Random rand;
int sides;
public RollDice(int x){
sides = x;
rand = new Random()
}
}
then, in that class you can add method which will generate new value
public int roll(){
return rand.nextInt(x);
}
you may as well don,t generate RollDice object with fixed value of dice's sides and make the method like:
public int roll(int x){
return rand.nextInt(x);
}
if you want java to generate new value after you enter something on console just use loop with System.in.read() and if or switch statement (for example if someone enters 1 - generate new value, if 0, end program)