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.
Related
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
I would like to know if Java allows you to call a constructor from a different class, and perform mathematical operations on it. And return its results in the Main class.
For example, I have
public class Wallet {
private int dollar;
public Wallet(int dollar){
this.dollar = dollar;
}
I also have
public class Count {
private int counter;
private ArrayList<Wallet> wallet;
public Count(){
this.wallet = new ArrayList<Wallet>();
}
public void addWallets(Wallet dollar) {
this.wallet.add(dollar);
}
public int sum(){
return 0;}
Now, my goal is to add the amount of money in each wallet, and print the results. This is the main class.
public class Main {
public static void main(String[] args) {
Count count = new Count();
Wallet wallet1 = new Wallet(34);
Waller wallet2 = new Wallet(26);
count.addWallets(wallet1);
count.addWallets(wallet2);
System.out.println( "Total is: " + count.sum() );
}
}
Thank you for your help!
The question you asked is quite unclear. But I will try to help you.
goal is to add the amount of money in each wallet, and print the
results.
Have a getter and setter methods for dollar in your Wallet class. So that you can use them later in the program.
In sum method sum of the dollars from each Wallet.
Here is the solution:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
Count count = new Count();
Wallet wallet1 = new Wallet(34);
Wallet wallet2 = new Wallet(26);
count.addWallets(wallet1);
count.addWallets(wallet2);
System.out.println("Total is: " + count.sum());
}
}
class Count {
private int counter;
private ArrayList<Wallet> wallet;
public Count() {
this.wallet = new ArrayList<Wallet>();
}
public void addWallets(Wallet dollar) {
this.wallet.add(dollar);
}
public int sum() {
int sum = 0;
for(Wallet w : wallet) {
sum += w.getDollar();
}
return sum;
}
}
class Wallet {
private int dollar;
Wallet(int dollar){
this.dollar = dollar;
}
public int getDollar() {
return dollar;
}
public void setDollar(int dollar) {
this.dollar = dollar;
}
}
In sum() method you can create object of Wallet class like Wallet wt=new Wallet(10) it will internally call the constructor of Wallet but not possible to call explicitly.You can call in super class and same class using this and super keyword.
I think you misunderstood the working of a list.
When you are running below code,
count.addWallets(wallet1);
count.addWallets(wallet2);
It adds wallet1 and wallet2 to ArrayList<Wallet> wallet of count as two separate elements.
When you are callingcount.sum(), that method will always return 0 based on your method declaration. If you want to get the sum of all elements when you are calling that method, try declaring the method as below:
public int sum(){
int total =0;
for(int i=0;i< wallet.size();i++){
total = total + wallet.get(i).getDollar();
}
return total;
}
And add setters and getters in your Wallet class for Dollar as
public int getDollar() {
return dollar;
}
public void setDollar(int dollar) {
this.dollar = dollar;
}
That way when you call the method, it gets the sum of dollars in all wallets and returns you.
I'm not sure how eloquently I can really explain what I don't understand/need help with, I'm still Very new to Object Oriented Programming. This is regarding my coursework and I don't expect anyone to do it for me, I just need help understanding how to move on, and if I'm even on the right track.
Ok, so on to my question. Basically, I am attempting to create an arraylist which will hold a few objects which themselves has a bunch of information(obviously), my spec said to create an abstract class, which will be extended by my constructor class, which I did. The abstract class has a few variables (decided by spec) But I dont know how to move them over to my extended class.
I'll post my code below, and I hope it makes sense. I'd be very thankful for any help you all could provide. I'm very confused right now.
Basically, I would love to know, A) How do I create an object in my arraylist which will be able to contain everything in SportsClub and FootballClub, and preferably all the variables user inputted.
And B) I don't know how to print The object, When I print right now I get coursework.FootballClub#49233bdc, Which I'm sure there's a reason for but I need the information in the objects to display, E.g. name. And if possible to sort the results by alphabetical order with respect to name? I hope this is all written ok. Sorry and Thank you in advance.
package coursework;
import java.util.*;
/**
*
* #author w1469384
*/
public class PremierLeagueManager implements LeagueManager{
public static void main(String[] args) {
Scanner c1 = new Scanner(System.in);
Scanner c2 = new Scanner(System.in);
ArrayList<FootballClub> PL = new ArrayList<FootballClub>();
int choice;
System.out.println("Enter 1; To create a club, 2; To Delete a Club, 3; To display all clubs and 99 to close the program");
choice = c1.nextInt();
//Creates and adds a new FootballClub Object
while (choice != 99){
if (choice == 1){
System.out.println("Please Enter The games played for the club");
int played = c1.nextInt();
System.out.println("Please enter the number of wins");
int wins = c1.nextInt();
System.out.println("please enter the number of losses");
int losses = c1.nextInt();
System.out.println("please enter the number of draws");
int draws = c1.nextInt();
System.out.println("please enter the number of goals for");
int goalsFor = c1.nextInt();
System.out.println("please enter the number of goals against");
int goalsAgainst = c1.nextInt();
FootballClub club = new FootballClub(played, wins, losses, draws, goalsFor, goalsAgainst);
PL.add(club);
System.out.println("check");
}
//Deletes a FootballClub Object
if (choice == 2){
}
//Displays all Football Clubs in the PremierLeague array
if (choice == 3){
System.out.println(PL);
}
//Closes the Program 1
choice = c1.nextInt();
}
}
}
public abstract class SportsClub {
public String name;
public String location;
public int capacity;
public void setName(String Name){
name = Name;
}
public void setLocation(String Location){
location = Location;
}
public void setCapacity(int Capacity){
capacity = Capacity;
}
public String getName(){
return name;
}
public String getLocation(){
return location;
}
public int getCapacity(){
return capacity;
}
}
public class FootballClub extends SportsClub {
//Statistics for the club.
int played;
int wins;
int losses;
int draws;
int goalsFor;
int goalsAgainst;
public FootballClub(int gPlayed, int gWins, int gLosses, int gDraws, int gFor, int gAgainst){
played = gPlayed;
wins = gWins;
losses = gLosses;
draws = gDraws;
goalsFor = gFor;
goalsAgainst = gAgainst;
}
public void setPlayed(int newPlayed){
played = newPlayed;
}
public void setWins(int newWins){
wins = newWins;
}
public void setLosses(int newLosses){
losses = newLosses;
}
public void setDraws(int newDraws){
draws = newDraws;
}
public void setGoalsFor(int newGoalsFor){
goalsFor = newGoalsFor;
}
public void setGoalsAgainst(int newGoalsAgainst){
goalsAgainst = newGoalsAgainst;
}
public int getPlayed(){
return played;
}
public int getWins(){
return wins;
}
public int getLosses(){
return losses;
}
public int getDraws(){
return draws;
}
public int getGoalsFor(){
return goalsFor;
}
public int getGoalsAgainst(){
return goalsAgainst;
}
}
FootballClub inherits the variables declared in SportsClub so you can set them as you please.
public FootballClub(
int gPlayed, int gWins, int gLosses, int gDraws, int gFor, int gAgainst,
String inName, String inLocation, int inCapacity
) {
played = gPlayed;
wins = gWins;
losses = gLosses;
draws = gDraws;
goalsFor = gFor;
goalsAgainst = gAgainst;
// set the variables from the superclass
name = inName;
location = inLocation;
capacity = inCapacity;
}
FootballClub also inherits the methods declared in SportsClub so you can use the setters and getters too.
Normally you would create a constructor for SportsClub that sets these and then call that constructor from the FootballClub constructor.
// in SportsClub
protected SportsClub(
String inName, String inLocation, int inCapacity
) {
name = inName;
location = inLocation;
capacity = inCapacity;
}
// in FootballClub
public FootballClub(
int gPlayed, int gWins, int gLosses, int gDraws, int gFor, int gAgainst,
String inName, String inLocation, int inCapacity
) {
super(inName, inLocation, inCapacity);
played = gPlayed;
wins = gWins;
losses = gLosses;
draws = gDraws;
goalsFor = gFor;
goalsAgainst = gAgainst;
}
You should also make your member variables protected or private if you are using setters and getters.
I don't know how to print The object
You need to override toString. There is a short tutorial here.
Also unrelated side note: all Java variable identifiers should start with a lowercase letter.
When you have a method like this:
public void setName(String Name) { name = Name; }
It should be:
public void setName(String inName) { name = inName; }
Or:
public void setName(String name){ this.name = name; }
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.
I'm a newbie java programer and I'm trying to make my first project.
I need to pass a variable between 2 classes, which is going fine. The problem is that the variable has a changing value and i cannot pass the actual value. Here is an example:
public class A{
private int counter = 0;
public int getCounter(){
return counter;
}
//here some code which will increase or decrease the value of the counter variable
//lets say for the sake of the example that at this point the value of the variable is 1.
//counter = 1;
}
public class B{
public static void main(String[] args) {
A a = new A();
System.out.println(a.getCounter());// here I need the actual counter variable value which is currently: 1
}
}
My problem is that i always receive 0. How can i pass the actual value of the variable.
Any help or advice is greatly appreciated.
A a = new A();
After instantiation (above statement) you need to call the method which will increment the counter here.
Example:
a.incrementCounter();
Then below statement will get counter value.
System.out.println(a.getCounter());
lets say for the sake of the example that at this point the value of the variable is 1.
No, by the time that code is read, the value did not change. All you do inside a class-block is to define a class, the “template” for an object. At that time, no values are set though.
The a.getCounter() you use already does the correct job: It returns the current value of a’s counter variable. If it does not return 1, then obviously the value hasn’t changed yet.
public class A {
private int counter = 0;
public int getCounter() {
return counter;
}
public void increaseCounter() {
counter++;
}
}
public class B {
public static void main() {
A a = new A();
System.out.println(a.getCounter());
a.increaseCounter();
System.out.println(a.getCounter());
}
}
Make variable static so that it will be associated with class.
public class A{
private static int counter = 0;
public int getCounter(){
counter++;
return counter;
}
public static void main(String[] args) {
A a = new A();
a.setCounter(5);
System.out.println(a.getCounter());
}
public class A{
private int counter = 0;
public int getCounter(){
return counter;
}
public void setCounter(int count ){
this.counter=count;
}
}
Use constructors/setter...
public class A{
private int counter = 0;
public A(int c){
counter = c
}
public int getCounter(){
return counter;
}
public void setCounter(int c){
counter = c;
}
public void incCounter(){
counter++;
}
}
public class B{
public static void main(String[] args) {
A a = new A(123);
System.out.println(a.getCounter());
a.setCounter(456);
System.out.println(a.getCounter());
a.incCounter();
System.out.println(a.getCounter());
}
}
class A {
private int counter = 0;
public int getCounter() {
return counter;
}
public int increment() {//////////create increment Method which will increase the counter , or do any function you want
return counter++;
}
public void setCounter(int c) {///////////this method will allow you to set the counter
counter=c;
}
}
class B {
public static void main(String[] args) {
A a = new A();
a.increment();///////if you call this function will change your counter , if not , you will get it = 0
System.out.println(a.getCounter());
}
}
A a = new A();
System.out.println(a.getCounter());
The Output = 0
A a = new A();
a.increment();
System.out.println(a.getCounter());
The Output =1
a = new A();
a.setCounter(10);//////////here you set the `counter` by 10
System.out.println(a.getCounter());
The Output =10;
You have one class (Counter) which manages the counter int variable.
You would like for one or more other classes to be able to increment and/or get the counter value.
In that case, each instance of those classes should have a reference to the same instance of Counter (stored as member variable, passed to their constructor or a setter method).
class Counter {
private int counter = 0;
public int getValue() { return counter; }
public void increment() { counter++; }
public String toString() { return Integer.toString(counter); }
}
class CounterUser {
private final Counter counter;
public CounterUser(Counter counter) { this.counter = counter; }
public String toString() { return Integer.toString(counter.getValue()); }
}
class Test {
public static void main(String[] args) throws Exception {
Counter counter = new Counter();
CounterUser a = new CounterUser(counter);
CounterUser b = new CounterUser(counter);
System.out.printf("%s %s %s\n", counter, a, b);
counter.increment();
System.out.printf("%s %s %s\n", counter, a, b);
b.increment();
System.out.printf("%s %s %s\n", counter, a, b); }
}
Output:
0 0 0
1 1 1
2 2 2
You can do it from the constructor and/or create method that changes the value.
public class A
{
private int counter = 0;
public A()
{
// value is set first time you create an instance of A. (e.g when you do A a = new A();
counter = 1;
}
public int getCounter()
{
return counter;
}
public void incrementCounter()
{
counter++;
}
}
public class B
{
public static void main(String[] args)
{
A a = new A();
System.out.println(a.getCounter());// Output : 1
a.incrementCounter();
System.out.println(a.getCounter());// Output : 2
a.incrementCounter();
a.incrementCounter();
a.incrementCounter();
System.out.println(a.getCounter());// Output : 5
}
}