I am creating a dice rolling application with java. I have a "Die" class that rolls a single die, and a "Dice" class that uses multiple instance variable of "die". However, it only returns 0 for my values. The Die class on its own works and will roll a random number, but I can not figure out how to get multiple rolls in my "Dice" class. Any help is appreciated.
Dice Class
public class Dice {
Die die1=new Die();
Die die2=new Die();
private int die1Value;
private int die2Value;
private int sum;
public Dice() {
die1Value=0;
die2Value=0;
}
public int getDie1Value() {
return die1Value;
}
public int getDie2Value() {
return die2Value;
}
public int getSum() {
return sum;
}
public void roll() {
die1Value=die1.getValue();
die2Value=die2.getValue();
sum=die1Value+die2Value;
}
public void printRoll() {
System.out.println("Die 1: "+die1Value);
System.out.println("Die 2: "+die2Value);
System.out.println("Total: "+sum);
if (sum==7) {
System.out.println("Craps!");
} else if (die1Value==1 && die2Value==1) {
System.out.println("Snake Eyes!");
} else if (die1Value==6 && die2Value==6) {
System.out.println("Box Cars!");
} else {
System.out.println();
}
}
}
Die Class
package a3.ben;
public class Die {
private int value;
public Die() {
}
public void roll() {
value=(int) (Math.random()*6)+1;
}
public int getValue() {
return value;
}
}
You never call die.roll. Try changing the roll method in Dice to include rolling both dice before getting their values.
public void roll() {
die1.roll(); // change the value of both dice
die2.roll();
die1Value = die1.getValue();
die2Value = die2.getValue();
sum = die1Value + die2Value;
}
Also added some spaces around operators like = and + for readability
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am writing this basic program with 3 classes in 3 separate files. It is supposed to be a program consisting of a class called PairOfDice, composed of two Die objects. Included methods to set and get the individual die values, a method to roll the dice,and a method that returns the current sum of the two die values. A driver class called RollingDice to instantiate and use a PairOfDice object.
It compiles without problems but when I try to run it results in a run-time error as follows:
Exception in thread "main" java.lang.NullPointerException at
PairOfDice.rollDice(PairOfDice.java:42) at
RollingDice.main(RollingDice2.java:16)
public class RollingDice
{
public static void main(String[] args)
{
PairOfDice pairofdice=new PairOfDice();
pairofdice.rollDice();
System.out.println(pairofdice.getDie1() +"\t" +pairofdice.getDie2());
}
}
public class PairOfDice
{
private Die die1, die2;
public PairOfDice()
{
Die die1=new Die();
Die die2=new Die();
}
public int getDie1()
{
return die1.getFaceValue();
}
public int getDie2()
{
return die2.getFaceValue();
}
public void setDie1(int dieValue)
{
die1.setFaceValue(dieValue);
}
public void setDie2(int dieValue)
{
die2.setFaceValue(dieValue);
}
public void rollDice()
{
die1.roll();
die2.roll();
}
public int sum()
{
return die1.getFaceValue()+die2.getFaceValue();
}
}
public class Die
{
private final int MAX = 6;
private int faceValue;
public Die()
{
faceValue = 1;
}
public void roll()
{
faceValue = (int)(Math.random() * MAX) + 1;
}
public void setFaceValue(int value)
{
faceValue = value;
}
public int getFaceValue()
{
return faceValue;
}
public String toString()
{
String result = Integer.toString(faceValue);
return result;
}
}
use
public PairOfDice()
{
die1=new Die();
die2=new Die();
}
You are trying to declare die1 and die2 in constructor. Thus the local variables were not initializing.
The goal of this code is to have a lockable interface for my main class, Coin, that makes the user input a key to access the main code. However, I have no idea on how to write the driver class in a way where the lockable object protects the regular methods (setKey, lock, and unlock) and when this object is locked, the methods cannot be invoked if it is unlocked it can be invoked. I have attempted a driver but it doesn't work.
package coins;
import java.util.Scanner;
public class Coins {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int guess;
System.out.println("Enter key: ");
guess = scan.nextInt();
Coin key = new Coin();
System.out.println(key);
final int flips = 1000;
int heads = 0, tails=0;
Coin myCoin = new Coin ();
for (int count =1; count <= flips; count++) {
myCoin.flip();
if (myCoin.isHeads())
heads++;
else
tails++;
}
System.out.println ("The number flips: " + flips);
System.out.println ("The number of heads: " + heads);
System.out.println ("The number of tails: " + tails);
}
}
Coin Class
package coins;
class Coin implements Lockable {
private final int HEADS = 0;
private final int TAILS = 1;
private boolean locked;
private int key;
private int face;
public Coin () {
flip();
locked = false;
key = 123;
}
public void flip() {
face = (int) (Math.random()*2);
}
public boolean isHeads() {
return (face == HEADS);
}
public String toString() {
String faceName;
if (face == HEADS)
faceName = "Heads";
else
faceName = "Tails";
return faceName;
}
public boolean locked(){
return locked;
}
public void setKey(int key){
this.key = key;
}
public void unlock(int key){
if(this.key == key){
locked = false ;
}
}
public void lock(int key){
if(this.key == key){
locked = true;
}
}
public void messageReturn(){
if(locked == false)
System.out.println("unlocked") ;
}
}
Lockable Interface
public interface Lockable {
public void setKey (int key);
public void lock (int key);
public void unlock (int key);
public boolean locked();
}
What Itamar Green is saying is true. However, to me, it appears that the real problem you are describing is in your Coins class, and not the Coin class. You aren't actually doing anything with the guess key that the user enters. You need to call setKey() on the Coin using that key. Then, your Coin will invoke or not invoke methods as per your code and Itamar's answer, by first checking to see whether it is in the locked state.
Firstly, you should check if the guess is correct via: (in main)
key.unlock(guess);//and you might want to set the default of locked to true, and remove the flip() in the constructor
You need to add a check in each method:
public void flip()
{
if(!locked)
face = (int) (Math.random()*2);
}
similarly with other methods.
I'm building an application and i am trying to find a way to get data from one class to another class.
in my main class called Driver, i have a function which throws two dices and then i get a sum of them. This function is created in a class called Dices.
I have a new class called Players, where i need to get the data from the dice throw from my main class.
The code is the following
public class Player {
public String spillernavn;
public int pos;
public String SpillerNavn() {
return spillernavn;
}
public int move(int steps){
move=??;
pos=steps+pos;
return ??;
}
public int SpillerPos() {
return pos;
}
}
The Methode public int move(int steps){} is where i need to use the data from the dice throw and then make the addition with the pos, which stands for position.
The main function is the following
public static void main(String[] args) {
//Intializing dices
Dice die1 = new Dice();
Dice die2 = new Dice();
//Summ of dice
int sum = die1.throwDice() + die2.throwDice();
File name: Dice.java
import java.util.Random;
public class Dice {
private Random random;
public Dice() {
random = new Random();
}
public int throwDice() {
int num = 0;
while(num == 0) // Dice doesn't have a zero, so keep looping unless dice has a zero.
num = random.nextInt(7); // returns a random number between 0 - 6
return num;
}
}
File name: Players.java
public class Players {
private int sum;
public Players(int sum) {
this.sum = sum; // You got the data from `Driver class` here.
// You got the sum of two dice. Now do whatever you want to.
}
}
public class Driver {
public static void main(String[] args) {
Dice dye1 = new Dice();
Dice dye2 = new Dice();
int sum = dye1.throwDice() + dye2.throwDice();
Players player = new Player(sum); // Passing the data to Class Players
}
}
To send data, you need to pass the argument in the ()
You could do something like this.
public class Player {
public String spillernavn;
public int pos;
public String SpillerNavn() {
return spillernavn;
}
public int move(int steps, int move){
move=move;
pos=steps+pos;
return ??;
}
public int SpillerPos() {
return pos;
}
}
Then in main:
public static void main(String[] args) {
//Intializing dices
Dice die1 = new Dice();
Dice die2 = new Dice();
//Summ of dice
int sum = die1.throwDice() + die2.throwDice();
player.move(steps, move);
For future reference. You should probably create an instance of your dice in your player class. It's simple passing data between classes. Getters and setters.
I'm trying to make a card game, and have my card class and my deck class sort of ready, it compiles ok, but when I try to run deck's method makeDeckFull, i get the output: invalidnumberinvalidnumber...
when I use the showDeck method I then see this instead of "hearts", 1
Cards#597f13c5 (i do not know what it means, or how to fix it)
Any help would be kindly appreciated: code below.
Deck Class:
import java.util.ArrayList;
public class Deck
{
private ArrayList<Cards> deck;
private int index;
public Deck()
{
deck = new ArrayList<Cards>();
}
public void makeDeckFull()
{
Cards h1 = new Cards("Hearts", 1);
Cards h2 = new Cards("Hearts", 2);
Cards h3 = new Cards("Hearts", 3);
deck.add(h1);
index ++;
deck.add(h2);
index ++;
deck.add(h3);
index ++;
//Rest of these is left out to conserve space
}
public void showDeck()
{
System.out.println(deck);
}
Card class:
public class Cards
{
private String HEARTS = "Hearts";
private String CLUBS = "Clubs";
private String DIAMONDS = "Diamonds";
private String SPADES = "Spades";
public int number;
public String suit;
public Cards()
{
suit = "unknown suit";
number = 0;
}
public Cards(String suit, int number)
{
setSuit(suit);
setNumber(number);
}
public void setCard(String suit, int number2)
{
setSuit(suit);
setNumber(number2);
}
public void setSuit(String newSuit)
{
if(
(newSuit.equalsIgnoreCase(HEARTS)) ||
(newSuit.equalsIgnoreCase(DIAMONDS)) ||
(newSuit.equalsIgnoreCase(CLUBS)) ||
(newSuit.equalsIgnoreCase(SPADES)))
{
suit = newSuit;
}
else
{
newSuit = "invalid";
System.out.print("Invalid");
}
}
public int getNumber()
{
return number;
}
public String getSuit()
{
return suit;
}
public void setNumber(int newNumber)
{
if(newNumber >0 && newNumber <=10)
{
number = newNumber;
}
else
{
number = 0;
System.out.print("invalid number");
}
}
}
1) You need to override toString() in the Cards class. As is, you are printing out the reference of the object(the gibberish) instead of the "data." You should also override the toString() method of Deck to only print out the list.
2) I'm stepping through your code snippet of makeDeckFull(), and it seems to work fine. Are you sure those three inserts are where you are getting the invalid print statements?
Ok, so for my java class's final project we're supposed to implement a simplified version of craps that runs for 10 rounds. Whenever I run this, I get the NoSuchElementsException for the line "int b=std.nextInt()". Why is that? I opened a scanner object and whatnot, but it wont let me enter the data to proceed with the game, throwing the exception instead. I also get the same exception for the "System.out.println(now.toString());" line in the main method. How could that not have any elements?
public class Player {
private int bet;//how much was bet
private boolean Pass;//they chose pass
private boolean DPass;//they chose dont pass
private boolean win;//did they win?
private int money=20;//how much they have
//private String continuity="initial";
//Modifier methods
public void newBet(int x){this.bet=x;}
public void Pass(boolean x){this.Pass=x;}
public void DPass(boolean x){this.DPass=x;}
public void didYouWin(boolean x){this.win=x;}
public void newMoney(int x){this.money+=x;}
//public void keepPlaying(String s){this.continuity=s;}
//Accessor methods
public int getBet(){return this.bet;}
public boolean getPass(){return this.Pass;}
public boolean getDPass(){return DPass;}
public boolean getResult(){return this.win;}
public int getMoney(){return this.money;}
public boolean isWinning(){return this.win;}
//public String playing(){return continuity;}
public String toString(){
return "Bet: $"+this.bet+"\nBet on Pass: "+this.Pass+"\nBet on Don't Pass: "+this.DPass+"\nMoney:S"+this.money;
}
//Constructor method
public Player(int bet, boolean pass, boolean dpass){
this.bet=bet;
this.Pass=pass;
this.DPass=dpass;
}
}
Actual game play code<<<<<<<<<<<<<<<<<<<<<<<<<<
import java.util.*;
public class trial1 {
public static int RollDice(){ //Method for Dice Roll
int[] die1={1, 2, 3, 4, 5, 6};
int[] die2={1, 2, 3, 4, 5, 6};
Random r=new Random();
int i1=r.nextInt(6-0);
int i2=r.nextInt(6-0);
int sum=die1[i1]+die2[i2];
System.out.println("\nDie 1: "+die1[i1]+"\nDie 2: "+die2[i2]+"\nTotal Sum: "+sum);
return sum;
}
public static int Roll7(){//roll for 7
if (RollDice()==7){
return 2;
}
else return Roll7();
}
public static int PointRoll(int x){//If person rolled 4,5,6,8,9,10...
int a=RollDice();
if (a==x){
return Roll7();
}
else if (a==7){
return 1;
}
else return PointRoll(x);
}
public static int ComeOutRoll(){//1 = pass loses, 2 = pass wins, 3 = pass loses and dont pass gets nothing
int x=RollDice();
if ((x==2)||(x==3)) {
return 1;
}
else if ((x==7)||(x==11)){
return 2;
}
else if (x==12){
return 3;
}
else return PointRoll(x);
}
public static Player InitializeGame(){
//initialize stats and player
System.out.println("Please enter how much you'd like to bet (max is $5)");
Scanner std=new Scanner(System.in);
int b=std.nextInt();
System.out.println("Please enter 1 if you bet PASS or 2 if you bet DON'T PASS");
int p=std.nextInt();
boolean betpass, betdpass;
if (p==1){
betpass=true;
betdpass=false;
}
else {
betpass=false;
betdpass=true;
}
Player name=new Player(b, betpass, betdpass);
System.out.print(name.toString());
std.close();
return name;
}
public static Player BeginGame(Player name){
//Start actual game process without the betting ie all the dice rolling and stat changing -->will return player's status
//boolean pass=name.getPass();
//boolean neutral=false;
int result=ComeOutRoll();
//find out if player won money or lost money
if (name.getPass()){//if player bet on pass
if (result==1){
name.newMoney(name.getMoney()-name.getBet());
}
else if (result==2){
name.newMoney(name.getMoney()+name.getBet());
}
else {
name.newMoney(name.getMoney()-name.getBet());
}
}
else {//if player bet dont pass
if (result==1){
name.newMoney(name.getMoney()+name.getBet());
}
else if (result==2){
name.newMoney(name.getMoney()-name.getBet());
}
else {
name.didYouWin(false);
}
}
if (name.getMoney()<=0){name.didYouWin(false);}//setting win data for yes or no. IF no money, u lose
else {name.didYouWin(true);}
public static Player Continue(Player name){//just like begin game, but adding the new bet
System.out.println("\nPlease enter how much you'd like to bet (max is $5)");
Scanner std=new Scanner(System.in);
int b=std.nextInt();
System.out.println("Please enter 1 if you bet PASS or 2 if you bet DON'T PASS");
int p=std.nextInt();
boolean betpass, betdpass;
if (p==1){
betpass=true;
betdpass=false;
}
else {
betpass=false;
betdpass=true;
}
name.Pass(betpass);
name.DPass(betdpass);
name.newBet(b);
System.out.println(name.toString());
return BeginGame(name);
}
public static void Loss(Player name){//losing message
System.out.println("YOU LOSE!!!!!!!! HAHAHAHAHAHA!!!!!\n"+name.toString());
}
public static void End(Player name){//End game message
System.out.println("Thank you for playing!");
}
public static Player Run(){
Player name = InitializeGame();
return BeginGame(name);
}
public static void main(String[] args){
System.out.println("Welcome to my version of craps!");
Player now=Run();
for (int i=1;i<=10;i++){
if (now.isWinning()){
System.out.println("ROUND "+i);
System.out.println(now.toString());
now=Continue(now);
i++;
}
else {
Loss(now);
System.out.print(now.toString());
End(now);
i=11;
}
}
}
}
The NoSuchElementsException means that you tried to get an int from the scanner, std, but there was no next int. So it throws this error to let you know your input was bad.
It would seem from the NoSuchElementException that you're not reading an int from the Scanner. It is interpreting your input as some other data type.