2d Array containing objects - java

This is an assignment for class that involves creating a hotel guest service. I created the 2d array below with 8 "floors", 20 "rooms", and populated them with Room objects. I am currently trying to use nested for-loops to go through each Room object and assign it a room number. For example, floor 1 would contain rooms 101-120.
The class below is a test class that I am using.
public class Test {
public Test() {
}
public static void main(String[] args) {
/**
* Creates a two dimensional array with 8 rows and 20 columns
*/
Room [][] hotelBuild = new Room[8][20];
/**
* populates the 2d array with Room objects
*/
for (int floor=0; floor<hotelBuild.length; floor++) {
for (int room=0; room<hotelBuild[floor].length; room++) {
hotelBuild[floor][room] = new Room();
/**
* used to print out contents of 2d array
*/
//System.out.print(hotelBuild[floor][room]=new Room());
}
}
}
}
Below is class Room that contains the variables, setters, getters, as well as the toString() override method.
public class Room {
//Instance variables
/**
*the rooms number
*/
private int roomNumber;
/** is the room occupied or not
*
*/
private boolean isOccupied;
/** name of guest
*
*/
private String guest;
/** cost per day
*
*/
private double costPerDay;
/** number of days guest is staying
*
*/
int days;
//Constructors
public Room(){
}
/** Construct a room with values above
*
*/
public Room(int room, boolean nonVacant, String guestName, double cost, int day) {
roomNumber = room;
isOccupied = nonVacant;
guest = guestName;
costPerDay = cost;
days = day;
}
// getters
/** gets roomNumber
*
*/
public int getRoomNumber(){
return roomNumber;
}
/** gets isOccupied
*
*/
public boolean getIsOccupied(){
return isOccupied;
}
/** gets guest
*
*/
public String getGuest(){
return guest;
}
/** gets costPerDay
*
*/
public double getCostPerDay(){
return costPerDay;
}
/** gets days
*
*/
public int getDays(){
return days;
}
// setters
/** sets isOccupied
*
*/
public void setIsOccupied(boolean full){
this.isOccupied = full;
}
/** sets days
*
*/
public void setDays(int numDays){
this.days = numDays;
}
/** sets guest name
*
*/
public void setGuest(String name){
this.guest = name;
}
/** formats output depending if room is occupied or not
*
*/
public String toString(){
if(isOccupied == true){
return "Room number: " + roomNumber + "\n"+ "Guest name: "
+ guest + "\n"+ "Cost : " + costPerDay
+ "\n"+ "Days: " + days + "\n";
}
else{
return "Room number " + roomNumber
+ " costs " + costPerDay + "\n";
}
}
}
How do I assign each Room object in the array a unique room number?

You could do
for (int floor=0; floor<hotelBuild.length; floor++){
for (int room=0; room<hotelBuild[floor].length; room++){
Room r = new Room();
r.setRoomNumber(
cleverCalculationWithFloorAndRoomNr(floor, room));
hotelBuild[floor][room]= r;

If you want a way to put the numbers in the correct order then use the varables you alredady have. Use a count for know what floor it is (it will be increased at the end of the first loop). Then room number is Floor * 100 + another variable you reset to 1 at the begining of the first loop. Just a hint to help you. Fill the gaps ;)
int floorNumber = 1;
int roomNumber = 1;
for (int floor=0; floor<hotelBuild.length; floor++){
for (int room=0; room<hotelBuild[floor].length; room++){
hotelBuild[floor][room]=new Room();
/**
* used to print out contents of 2d array
*/
//System.out.print(hotelBuild[floor][room]=new Room());
//Add room number here.
//Increase room number
}
//floorNumber increase
//roomNumber reset
}
Once you have achieved this you could try to use the variables you have in the loops (room and floor) with a few minor changes.

for (int floor=0; floor<hotelBuild.length; floor++){
for (int room=0; room<hotelBuild[floor].length; room++){
hotelBuild[floor][room]=new Room();
// room number format: xxyy, x = floor, y = room
// this assumes maximum 99 rooms per floor, it should be enough
hotelBuild[floor][room].setNumber((floor + 1) * 100 + room + 1);
}
}

You can pass it through the contructor for example or set with a setter in your class Room (classroom ahahah)
for example:
for (int floor=0; floor<hotelBuild.length; floor++){
for (int room=0; room<hotelBuild[floor].length; room++){
hotelBuild[floor][room]=new Room((floor+1)*100+room+1);
}
}
And in your Room class, you can add a constructor with only the room number as parameter
class Room{
public Room(int roomNumber){
this.roomNumber = roomNumber;
}
...
}

Related

Is return a better alternative than Sys.out.print in this scenario

This is my tester class for my first programming assignment, which I believe tests the getters and setters correctly, but I was wondering if there is a better method using the return method instead. I'm still quite a novice, as this is my first programming assignment. It feels almost improper to have so many print lines, but is there a better way with return? (At least something not incredibly complex for a java beginner)
/**
A class to test the Assignment class
*/
public class AssignmentTester
{
/**
Main method used to start program
#param args the command line arguments for the program
*/
public static void main(String[] args)
{
System.out.println("TESTING NO-ARGUMENT CONSTRUCTOR AND GETTERS \n=========================================== \n");
Assignment noArgGetterTest = new Assignment();
System.out.println(noArgGetterTest.getTitle() + "\nExpected: Assignment 1 \n");
System.out.println(noArgGetterTest.getDueDate() + "\nExpected: 01/01/2019 \n");
System.out.println(noArgGetterTest.getMaxPoints() + "\nExpected: 10.0 \n");
System.out.println(noArgGetterTest.getCategory() + "\nExpected: Programming Assignments \n \n");
System.out.println("Testing Setters \n=============== \n");
Assignment setterTest = new Assignment();
setterTest.setTitle("CodeLab 1");
System.out.println(setterTest.getTitle() + "\nExpected: CodeLab 1 \n");
setterTest.setDueDate("02/09/2019");
System.out.println(setterTest.getDueDate() + "\nExpected: 02/09/2019 \n");
setterTest.setMaxPoints(5.0);
System.out.println(setterTest.getMaxPoints() + "\nExpected: 5.0 \n");
setterTest.setCategory("CodeLab, Quizzes, ICE");
System.out.println(setterTest.getCategory() + "\nExpected: CodeLab, Quizzes, ICE \n \n");
System.out.println("Testing Argument Constructor and Getters \n======================================== \n");
Assignment getterTest = new Assignment("Quiz 3.1", "03/13/2019", 2.0, "CodeLab, Quizzes, ICE");
System.out.println(getterTest.getTitle() + "\nExpected: Quiz 3.1 \n");
System.out.println(getterTest.getDueDate() + "\nExpected: 03/13/2019 \n");
System.out.println(getterTest.getMaxPoints() + "\nExpected: 2.0 \n");
System.out.println(getterTest.getCategory() + "\nExpected: CodeLab, Quizzes, ICE");
}
}
My first class file that creates the parameters and arguments for creating an assignment:
/**
Describes an assignment's title, due date, total points value, and category
*/
public class Assignment
{
private String title; //Title of assignment
private String dueDate; //Due date of assignment
private double maxPoints; //Max points of assignment
private String category; //Category of assignment
/**
Initialize instance variables for assignment project (no argument-constructor)
*/
public Assignment()
{
title = "Assignment 1";
dueDate = "01/01/2019";
maxPoints = 10.0;
category = "Programming Assignments";
}
/**
Initialize instance variables for the assignment project (argument constructor)
#param t title of assignment
#param d due date of assignment
#param m max points for the assignment
#param c category of assignment
*/
public Assignment(String t, String d, double m,String c)
{
title = t;
dueDate = d;
maxPoints = m;
category = c;
}
/**
Sets the value of title
#param t title of assignment
*/
public void setTitle(String t)
{
title = t;
}
/**
Sets the value of dueDate
#param d due date of assignment
*/
public void setDueDate(String d)
{
dueDate = d;
}
/**
Sets value of maxPoints
#param m max points of assignment
*/
public void setMaxPoints(double m)
{
maxPoints = m;
}
/**
Sets the value of category
#param c category of assignment
*/
public void setCategory(String c)
{
category = c;
}
/**
Returns the value of title
#return title of assingment
*/
public String getTitle()
{
return title;
}
/**
Returns the value of dueDate
#return due date of assignment
*/
public String getDueDate()
{
return dueDate;
}
/**
Returns the value of maxPoints
#return max points of assignment
*/
public double getMaxPoints()
{
return maxPoints;
}
/**
Returns the value of category
#return category of assingmen
*/
public String getCategory()
{
return category;
}
}
// I have done the same problem with using the return keyword, its awesome to use //return.
// but you should know "method" before using return keyword. Basically, you will know //later that the "method" helps you to save writing the same code. Cheers:)
public class AssignmentTester {
public static Assignment noArgumentConstructorAndGetters() {
System.out.println("TESTING NO-ARGUMENT CONSTRUCTOR AND GETTERS \n=========================================== \n");
Assignment noArgGetterTest = new Assignment();
return noArgGetterTest;
}
public static void printMethod(Assignment ass) {
System.out.println(ass.getTitle());
System.out.println(ass.getDueDate());
System.out.println(ass.getMaxPoints());
System.out.println(ass.getCategory());
}
public static Assignment testingSetters() {
System.out.println("Testing Setters \n=============== \n");
Assignment setterTest = new Assignment();
setterTest.setTitle("CodeLab 1");
setterTest.setDueDate("02/09/2019");
setterTest.setMaxPoints(5.0);
setterTest.setCategory("CodeLab, Quizzes, ICE");
return setterTest;
}
public static Assignment testingArgumentsAndConstructors() {
System.out.println("Testing Argument Constructor and Getters \n======================================== \n");
Assignment getterTest = new Assignment("Quiz 3.1", "03/13/2019", 2.0, "CodeLab, Quizzes, ICE");
return getterTest;
}
public static void main(String[] args) {
printMethod(noArgumentConstructorAndGetters());
printMethod(testingSetters());
printMethod(testingArgumentsAndConstructors());
}
}

How to create an ArrayList and initialize new Byte variables in it

I am currently enrolled in the Udacity Android Basics Nanodegree program.
One task now is to create a ReportCard Java Class which would allow a school to store a student’s grades for a particular year.
While I submitted my project and it successfully passed review, I was given the suggestion of using an ArrayList instead of hard-coding the subjects for which grades could be given.
While implementing this suggestion, I am extremely struggling. I already searched throught StackOverflow for hours and haven't yet found a problem-solving answer.
So, here is my code:
package com.example.android.reportcardclass;
/**
* Report Card class
* This class prepares a student report card.
*/
public class ReportCard {
/**
* Class Attributes
*/
private String mStudentName;
private int mYear;
private byte mGerman;
private byte mEnglish;
private byte mMathematics;
private byte mGeography;
private byte mSocialSciencesAndEconomics;
private byte mPhysics;
private byte mReligion;
private byte mPhysEd;
private byte mMusic;
/**
* Default Constructor for ReportCard class
*
* #param studentName Name of the student
* #param year Year in which the student is in
* #param german Mark in the subject German
* #param english Mark in the subject English
* #param mathematics Mark in the subject Mathematic
* #param geography Mark in the subject Geography
* #param socialSciencesAndEconomics Mark in the subject Social Sciences and Economics
* #param physics Mark in the subject Physcics
* #param religion Mark in the subject Religion
* #param physEd Mark in the subject Physical Education
* #param music Mark in the subject Music
*/
public ReportCard(String studentName, int year,
byte german, byte english, byte mathematics,
byte geography, byte socialSciencesAndEconomics,
byte physics, byte religion, byte physEd,
byte music) {
mGerman = german;
mEnglish = english;
mMathematics = mathematics;
mGeography = geography;
mSocialSciencesAndEconomics = socialSciencesAndEconomics;
mPhysics = physics;
mReligion = religion;
mPhysEd = physEd;
mMusic = music;
}
/**
* This method is to get Student Name
*
* #return Student Name
*/
public String getStudentName() {
return mStudentName;
}
/**
* This method is to set Student Name
*
* #param studentName Name of the student
*/
public void setStudentName(String studentName) {
mStudentName = studentName;
}
/**
* This method is to get the year in which the student is in
*
* #return Year in which the student is in
*/
public int getYear() {
return mYear;
}
/**
* This method is to set the year in which the student is in
*
* #param year Year in which the student is in
*/
public void setYear(int year) {
mYear = year;
}
/**
* These are the setter and getter methods for the marks of the student in the respective subject
*/
public byte getGerman() {
return mGerman;
}
public void setGerman(byte german) {
mGerman = german;
}
public byte getEnglish() {
return mEnglish;
}
public void setEnglish(byte english) {
mEnglish = english;
}
public byte getMathematics() {
return mMathematics;
}
public void setMathematics(byte mathematics) {
mMathematics = mathematics;
}
public byte getGeography() {
return mGeography;
}
public void setGeography(byte geography) {
mGeography = geography;
}
public byte getSocialSciencesAndEconomics() {
return mSocialSciencesAndEconomics;
}
public void setSocialSciencesAndEconomics(byte socialSciencesAndEconomics) {
mSocialSciencesAndEconomics = socialSciencesAndEconomics;
}
public byte getPhysics() {
return mPhysics;
}
public void setPhysics(byte physics) {
mPhysics = physics;
}
public byte getReligion() {
return mReligion;
}
public void setReligion(byte religion) {
mReligion = religion;
}
public byte getPhysEd() {
return mPhysEd;
}
public void setPhysEd(byte physEd) {
mPhysEd = physEd;
}
public byte getMusic() {
return mMusic;
}
public void setMusic(byte music) {
mMusic = music;
}
#Override
public String toString() {
return "Student Name: " + getStudentName() + "\nYear: " + getYear() + "German: "
+ getGerman() + "\nEnglish: " + getEnglish() + "\nMathematics: " +
getMathematics() + "\nGeography: " + getGeography() +
"\nSocialSciencesAndEconomics: " + getSocialSciencesAndEconomics() +
"\nPhysics: " + getPhysics() + "\nReligion: " + getReligion() +
"\nPhysical Education: " + getPhysEd() + "\nMusic: " + getMusic();
}
}
What I want to do now, is to store the class attributes initialized at the very beginning (mGerman, mEnglish, etc.) in an ArrayList. How do I do that?! I am extremely struggling as I don't want to set any values just yet, but simply initialize the byte values (grading system in Germany goes from 0 to 15 points).
Please help me, thank you very much in advance!
If you know how many grades there are going to be you can use the following to initialize an ArrayList with null values:
List<Byte> bytes = new ArrayList<Byte>(Arrays.asList(new Byte[9]));
To update values in the List you can use for example
bytes.set(3, (byte) 12);
Try this
ArrayList<ReportCard> mList=new ArrayList<>();
ReportCard reportCard=new ReportCard();
reportCard.setStudentName("student name");
//fill all the details like this
reportCard.setYear("2017");
.
.
mList.add(reportCard);
And when you want to get the details do like this
String studentName=mList.get(position).getStudentName();
I suggest you to use an EnumSet instead of a list to store the grades, for the following reasons:
It provides a more compact representation in memory
It only accepts values of well-defined grades thanks to enum
It prevents duplicates
It allows to check if a grade is present with O(1) complexity.
First define an enum with the grades:
public enum Grade {
GERMAN, ENGLISH, MATHEMATICS, GEOGRAPHIC, SOCIAL_SCIENCES_AND_ECONOMICS,
PHYSICS, RELIGION, PHYSICAL_EDUCATION, MUSIC
}
Then you can expose methods to add or remove a grade for example, that will delegate to the EnumSet methods:
private final EnumSet<Grade> grades = EnumSet.noneOf(Grade.class);
public boolean add(Grade grade) {
return grades.add(grade);
}
public boolean remove(Grade grade) {
return grades.remove(grade);
}

Need help using arraylists in program?

It seems that 20 regiments were in a continuous process of formation. The first had 1000 men, the second had 950, the third 900, and so on down to the twentieth regiment, which garrisoned only 50. During each week, 100 men were added to each regiment, and at week's end, the largest regiment was sent off to the front.This lasted for a total of 20 weeks.
For this program I have already managed to print out the original number of men for each regiment. But I am having difficult adding 100 men to each regiment.The adding men must be a method in the army class. I am getting the regiment objects using a .txt file. All this files contains is the names of regiments numbered 1-20.
public class Regiment {
private String name; //name of regiment
private int regNumber; //regiment number
private int men; // regiment men
/**
* Creates a Regiment object.
*
* #param regNumber the regiment number
* #param name the name of the regiment
* #param men the number of men in a regiment
*/
public Regiment(int regNumber, String name, int men) {
this.name = name;
this.regNumber = regNumber;
this.men = men;
}
/**
* Returns the name of the regiment.
*
* #return the regiment name
*/
public String getName() {
return name;
}
/**
* Returns the number of the regiment.
*
* #return regiment number
*/
public int getregNumber() {
return regNumber;
}
/**
* Returns the number of men in a regiment.
*
* #return men in regiment
*/
public int getMen() {
return men;
}
/**
* Computes the number of men in a regiment
*/
public int addMen2(int RegNumber) {
int men = 1050 - (regNumber * 50);
return men;
}
}
class ArmyDataList {
public ArrayList<Regiment> list; // list of regiment objects
/**
* Creates an empty list
*/
public ArmyDataList() {
list = new ArrayList<Regiment>();
}
/**
* Appends a regiment object to the list.
*
* #param current the object to be appended to the list
*/
public void AddToList(Regiment current) {
list.add(current);
}
/**
* Removes a regiment object to the list.
*
* #param current the object to be removed from the list
*/
public void RemoveFromList(Regiment current) {
list.remove(current);
}
/**
* Gets the largest regiment based on men.
*/
public Regiment getLargest() {
if (list.isEmpty()) {
return null;
}
Regiment Reg1 = list.get(0);
for (int i = 1; i < list.size(); i++) {
Regiment current = list.get(i); // get next regiment
// is current regiment > largest
if (current.getMen() > Reg1.getMen()) {
Reg1 = current;
}
}
return Reg1;
}
/**
* Adds men to each regiment.
*/
public void addMen() {
}
/**
* Converts the list to a multi-line string, with each line containing the
* data for one regiment.
*
* #return the String containing all the data on the list
*/
public String toString() {
String out
= String.format("%28s%12s%n", "Regiments", " Men")
+ String.format("%12s%n", "Number")
+ String.format("%12s%16s%14s%n", "=======", "===============",
"=========");
for (int i = 0; i < list.size(); i++) {
Regiment regim = list.get(i);
int regNumber = regim.getregNumber();
String name = regim.getName();
int men = regim.addMen2(regNumber);
out = out + String.format("%12s", regNumber)
+ String.format("%16s", name)
+ String.format("%10s", men)
+ "\n";
}
return out + "\n";
}
}
public class RegimentTest {
public static void main(String[] args) throws IOException
{
ArmyDataList army = new ArmyDataList();
// create Scanner object to read each line of file until eof
Scanner fileScan = new Scanner(new File("regiments.txt"));
System.out.println("Report Summary:\n");
while (fileScan.hasNext()) // while not eof...
{
// read next line
String line = fileScan.nextLine();
// "echo print" data entered
System.out.println(line);
// 1. create a Scanner object
Scanner in = new Scanner(line) ;
// 2. extract tokens from current line
int regNumber = in.nextInt();
String name = in.next();
int men = 0 ; //men is set to 0 only because I havent add the men yet
// 3. create Regiment object passing the tokens to the constructor
Regiment adder = new Regiment(regNumber, name, men );
// 4. add object to list
army.AddToList(adder) ;
}
System.out.println(army.toString());
}
You can write addNewMen() method in Regiment Class where you can add 100 more men as men is the property of regiment.

Dealing Cards Through a Single Array

I have to write a program to play a game of poker between two 'human' players. I have the main method (dealer) set up to ask for the first player's bet but I haven't been able to figure out how to call upon the Deck class to the deal method. I tried deck.deal(), etc. but nothing seems to go through. Ill post the classes that are involved below and I've taken note of where the code should call upon the deck in the Dealer class
public class Dealer
{
private Deck deck;
private Player[] players;
private String n;
Scanner scan = new Scanner(System.in);
public static final int NUMBER_OF_PLAYERS = 2;
/**
* Default constructor - creates and populates the Player array and the
* Deck object.
*/
public Dealer()
{
players = new Player[ NUMBER_OF_PLAYERS ]; //IMPORTANT players is the array
deck = new Deck();
// populate the array of players
} // constructor
/**
* Outermost level of abstraction for the poker game
*/
public void play()
{
System.out.println("Welcome to Poker!");
//Getting First Names
System.out.println("\nEnter first player's name: ");
String name = scan.nextLine();
players[0] = new Player(name);
players[0].getName(name);
//Getting Second Name
System.out.println("Enter second player's name: ");
name = scan.nextLine();
players[1] = new Player(name);
players[1].getName(name);
//First Player Goes
System.out.println(players[0].getName(n) + "'s Turn\n");
//Bet
System.out.println("Enter bet: ");
int bet = players[0].getBet(); //IMPORTANT players is the array and can call Player method as own
//Able to bet?
while(!players[0].bet(bet) || !players[1].bet(bet))
{
bet = 20;
if(!players[0].bet(bet) || !players[1].bet(bet))
{
bet = 1;
}
}
//Draw Cards/Deck
//*****NEED TO DEAL CARDS HERE*****
//*****DEAL AN ARRAY OF CARD[5] TO EACH PLAYERS[0] AND [1]******
//Compare
//Add to winner
//Add to loser
//Winner Goes ^^
} // method play
}
public class Deck
{
private int pointer = 0; // indicates the current position in the deck.
// This should begin with 0 (the first call)
// and increment every time a card is dealt.
private Card deck[] = new Card[CARDS_IN_DECK];
private Card tempDeck[] = new Card[CARDS_IN_DECK];
private Card Cards[] = new Card[5];
public static final int CARDS_IN_DECK = 52;
/**
* Instantiate an array of Cards and populate the array with 52 Card
* objects. The face values of the cards should be between 2 - 14.
* Values 2 - 10 represent the number cards. Values 11 - 14 represent
* Jack, Queen, King, and Ace, respectively. The suits should be as
* follows: 100 = Clubs, 200 = Diamonds, 300 = Hearts, and 400 = Spades.
* See the Card class for more information.
*
* You should both shuffle and cut the cards before this method
* concludes.
*/
public Deck()
{
int i = 0;
for(int a = 1; a <= 5; a++)
{
for(int b = 2; b <=14; b++)
{
deck[i] = new Card(a,b);
}
}
shuffle();
cut();
} // default constructor
/**
* Cut the deck. Choose a point in the deck (this can be either random
* or fixed) and re-arrange the cards. For example, if you choose to
* cut at position 26, then the 27th - 52nd cards will be placed in the
* 1st - 26th positions. The 1st - 26th cards will be placed in the
* 27th - 52nd positions.
*/
public void cut()
{
int cut = 26;
int a = 0;
int b = 0;
for(int i = 0 ; i<cut; i++)
{
tempDeck[i] = new Card(a,b);
tempDeck[i] = deck[i+26];
tempDeck[i+26] = deck[i];
}
deck = tempDeck;
}
// method cut
/**
* Deal 5 cards from the deck. Deal out the next 5 cards and return
* these in an array. You will need to maintain a pointer that lets
* you know where you are in the deck. You should make sure also
* to reshuffle and cut the deck and start over if there are not enough
* cards left to deal a hand.
*
* #return an array of 5 cards
*/
public Card[] deal(int[] args)
{
int i = 0;
int a = 0;
int b = 0;
Cards[i] = new Card(a,b);
for(i = 0; i < 1; i++)
{
Cards[pointer] = deck[pointer];
pointer++;
}
return Cards;
// this is a stub only - replace this!!!!
} // method deal
/**
* Get a card from the deck
*
* #param the position of the card you are retrieving
* #return the card object
*/
public Card getCard( int card )
{
Card oneCard = deck[pointer];
deck[pointer] = null;
pointer +=1;
return oneCard; // this is a stub only - replace this!!!
} // method getCard
/**
* Shuffle the deck. Randomly re-arrange the cards in the deck. There
* are plenty of algorithms for doing this - check out Google!!!
*/
public void shuffle()
{
int i, j, k;
int n = 15;
for ( k = 0; k < n; k++ )
{
i = (int) ( CARDS_IN_DECK * Math.random() ); // Pick 2 random cards
j = (int) ( CARDS_IN_DECK * Math.random() ); // in the deck
tempDeck[j] = deck[i];
tempDeck[i] = deck[j];
deck = tempDeck;
}
pointer = 0; // Reset current card to deal
} // end shuffle
} // class Deck
public class Player
{
private int bet;
private int chips;
private int totalChips = 0;
private Hand hand;
private String name;
public static final int START_CHIPS = 100;
public static final int WINNING_CHIPS = 200;
Scanner scan = new Scanner(System.in);
/**
* Sets the player's name and the starting number of chips.
*
* #param the player's name
*/
public Player( String n )
{
name = n;
totalChips = START_CHIPS;
} // constructor
/**
* Sets the amount of the bet and decreases the number of chips that
* the player has by the number of chips bet. Do not allow bets if
* there are not enough chips left.
*
* #param the number of chips bet
* #return true if the bet was successful (there were enough chips)
*/
public boolean bet( int bet )
{
int chipsAB;
boolean canBet;
//Get Bet
getBet();
//See if player has enough chips for bet
if(totalChips >= bet)
{
canBet = true;
}
else
{
canBet = false;
}
return canBet; // this is a stub only - replace this!!!!
} // method bet
/**
* Return the number of chips bet
*
* #return the number of chips bet
*/ //DONE
public int getBet()
{
int bet;
bet = scan.nextInt();
while (bet < 1 || bet > getChips())
{
System.out.println("Error. Re-enter bet: ");
bet = scan.nextInt();
}
return bet; // this is a stub only - replace this!!!!
} // method getBet
/**
* Return the number of chips currently held
*
* #return the number of chips held
*/
public int getChips()
{
for(int i = 0; i<1; )
{
totalChips = START_CHIPS;
}
return totalChips; // this is a stub only - replace this!!!!
} // method getChips
public int setChips()
{
int playersChips = getChips();
return playersChips;
}
/**
* Return the player's hand
*
* #return the player's hand object
*/
public Hand getHand()
{
return new Hand(); // this is a stub only - replace this!!!!
} // method getHand
/**
* Return the player's name
*
* #return the player's name
*/
public String getName(String name)
{
String n = name;
return n; // this is a stub only - replace this!!!!
} // method getName
/**
* Indicates whether this player has won
*
* #return true if the player has more than the number of winning points
*/
public boolean hasWon()
{
boolean won = false;
if(chips == 0)
{
won = true;
}
return won; // this is a stub - replace this!!!
} // method hasWon
/**
* Set the Hand object to the incoming Hand object (this comes from the
* Dealer)
*
* #param the hand dealt by the dealer
*/
public void setHand( Hand h )
{
} // method setHand
/**
* Return the player's name & the number of chips
*
* #return the players name & number of chips
*/
public String toString()
{
String nameChips;
nameChips = (name + totalChips);
return nameChips; // this is a stub only - replace this!!!
} // method toString
/**
* We won the hand, so increase chips
*
* #param the number of chips won
*/
public int winHand()
{
int chipsAB = 0;
//if(hand.beats(other))
{
chipsAB = getChips() + getBet();
}
//else
chipsAB = getChips() - getBet();
return chipsAB;
} // method winHand
} // class Player
The code compiles for me, but I had to
create a class called Card with a constructor Card(int a, int b)
create a class called Hand
ignore the Javadoc errors.
After #param you should have the name of the parameter not the ...
The main method wasn't included, but other than that it compiles with a few changes.
I think I can get you going in the right direction but I don't have time to do all the work. I went a bit further and used Java collections to clarify / ease some of the use. A bunch of code updates here. Key points are Suit enum, Collections.shuffle, use of ArrayLists for the deck and hands, and the changes in the cut function. There is also a lot of opportunity for more error and bounds checking.
Stylistically, I'd suggest thinking about your object layout. Dealer is a specialization of Player, shuffle and cut might better be methods on Dealer (a Deck doesn't do those things to itself). Anyhow, for this update I didn't touch those things, just something to be aware of.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Dealer {
public static final int NUMBER_OF_PLAYERS = 2;
private Deck deck;
private List<Player> players = new ArrayList<Player>(NUMBER_OF_PLAYERS);
Scanner scan = new Scanner(System.in);
/**
* Default constructor - creates and populates the Player array and the Deck object.
*/
public Dealer() {
deck = new Deck();
} // constructor
/**
* Outermost level of abstraction for the poker game
*/
public void play() {
System.out.println("Welcome to Poker!");
// Getting First Names
System.out.println("\nEnter first player's name: ");
String name = scan.nextLine();
players.add(new Player(name));
// Getting Second Name
System.out.println("Enter second player's name: ");
name = scan.nextLine();
players.add(new Player(name));
// First Player Goes
System.out.println(players.get(0).getName() + "'s Turn\n");
// Bet
System.out.println("Enter bet: ");
int bet = players.get(0).getBet();
// Able to bet?
while (!players.get(0).bet(bet) || !players.get(1).bet(bet)) {
bet = 20;
if (!players.get(0).bet(bet) || !players.get(0).bet(bet)) {
bet = 1;
}
}
// Draw Cards/Deck
// *****NEED TO DEAL CARDS HERE*****
// *****DEAL AN ARRAY OF CARD[5] TO EACH PLAYERS[0] AND [1]******
for (Player player : players) {
player.setHand(deck.deal(5));
}
// Compare
// Add to winner
// Add to loser
// Winner Goes ^^
} // method play
}
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Player {
private int chips;
private int totalChips = 0;
private List<Card> hand = new ArrayList<Card>();
private String name;
public static final int START_CHIPS = 100;
public static final int WINNING_CHIPS = 200;
Scanner scan = new Scanner(System.in);
/**
* Sets the player's name and the starting number of chips.
*
* #param the
* player's name
*/
public Player(String n) {
name = n;
totalChips = START_CHIPS;
} // constructor
/**
* Sets the amount of the bet and decreases the number of chips that the player has by the number of chips bet. Do not allow
* bets if there are not enough chips left.
*
* #param the
* number of chips bet
* #return true if the bet was successful (there were enough chips)
*/
public boolean bet(int bet) {
boolean canBet;
// Get Bet
getBet();
// See if player has enough chips for bet
if (totalChips >= bet) {
canBet = true;
} else {
canBet = false;
}
return canBet; // this is a stub only - replace this!!!!
} // method bet
/**
* Return the number of chips bet
*
* #return the number of chips bet
*/
// DONE
public int getBet() {
int bet;
bet = scan.nextInt();
while (bet < 1 || bet > getChips()) {
System.out.println("Error. Re-enter bet: ");
bet = scan.nextInt();
}
return bet; // this is a stub only - replace this!!!!
} // method getBet
/**
* Return the number of chips currently held
*
* #return the number of chips held
*/
public int getChips() {
for (int i = 0; i < 1;) {
totalChips = START_CHIPS;
}
return totalChips; // this is a stub only - replace this!!!!
} // method getChips
public int setChips() {
int playersChips = getChips();
return playersChips;
}
/**
* Return the player's hand
*
* #return the player's hand object
*/
public List<Card> getHand() {
return hand;
} // method getHand
/**
* Return the player's name
*
* #return the player's name
*/
public String getName() {
return name;
} // method getName
/**
* Indicates whether this player has won
*
* #return true if the player has more than the number of winning points
*/
public boolean hasWon() {
return (chips > WINNING_CHIPS);
} // method hasWon
/**
* Set the Hand object to the incoming Hand object (this comes from the Dealer)
*
* #param the
* hand dealt by the dealer
*/
public void setHand(List<Card> dealtHand) {
hand = dealtHand;
} // method setHand
/**
* Return the player's name & the number of chips
*
* #return the players name & number of chips
*/
public String toString() {
return "Name: " + name + ", Chips: " + chips;
} // method toString
/**
* We won the hand, so increase chips
*
* #param the
* number of chips won
*/
public int winHand() {
int chipsAB = 0;
// if(hand.beats(other))
{
chipsAB = getChips() + getBet();
}
// else
chipsAB = getChips() - getBet();
return chipsAB;
} // method winHand
} // class Player
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class Deck {
public static final int CARDS_IN_DECK = 52;
private List<Card> deck = new ArrayList<Card>(CARDS_IN_DECK);
/**
* Constructor
*
* Instantiate an array of Cards and populate the array with 52 Card objects. The face values of the cards should be between 2 -
* 14. Values 2 - 10 represent the number cards. Values 11 - 14 represent Jack, Queen, King, and Ace, respectively.
*
* You should both shuffle and cut the cards before this method concludes.
*/
public Deck() {
for (Suit suit : Suit.values()) {
// I made the Ace equal to 1, but it's just preference
for (int value = 2; value <= 14; value++) {
deck.add(new Card(suit, value));
}
}
Collections.shuffle(deck);
cut();
} // default constructor
/**
* Cut the deck. Choose a point in the deck (this can be either random or fixed) and re-arrange the cards. For example, if you
* choose to cut at position 26, then the 27th - 52nd cards will be placed in the 1st - 26th positions. The 1st - 26th cards
* will be placed in the 27th - 52nd positions.
*/
public void cut() {
Random rand = new Random();
int cutPoint = rand.nextInt(deck.size()) + 1;
List<Card> newDeck = new ArrayList<Card>(deck.size());
newDeck.addAll(deck.subList(cutPoint, deck.size()));
newDeck.addAll(deck.subList(0, cutPoint));
deck = newDeck;
}
// method cut
/**
* Deal 5 cards from the deck. Deal out the next 5 cards and return these in an array. You will need to maintain a pointer that
* lets you know where you are in the deck. You should make sure also to reshuffle and cut the deck and start over if there are
* not enough cards left to deal a hand.
*
* #return an array of 5 cards
*/
public List<Card> deal(int size) {
List<Card> hand = new ArrayList<Card>(size);
hand.add(deck.remove(0));
return hand;
} // method deal
/**
* Get a card from the deck
*
* #param the
* position of the card you are retrieving
* #return the card object
*/
public Card getCard(int position) {
if (position >= 0 && position < deck.size()) {
return deck.remove(position);
}
else {
return null; // or throw an exception, or print an error or whatever
}
} // method getCard
} // class Deck
public class Card {
private Suit suit;
private int value;
public Card(Suit suit, int value) {
this.suit = suit;
this.value = value;
}
public Suit getSuit() {
return suit;
}
public int getValue() {
return value;
}
}
public enum Suit {
CLUBS, DIAMONDS, HEARTS, SPADES;
}

Java access protected variable from subclass

I am working on a homework assignment looking at inheritance in java. I am having a little trouble understand how to access an array in the superclass from the subclass. I looked at several other questions, and since I am so new to java, I'm still just not quite getting it.
Here is the super class
import java.text.NumberFormat;
/**
* Bank represents a single Bank containing a number of BankAccounts.
*/
public class Bank {
// Member variables:
/** The array of BankAccount objects contained in this bank. */
protected BankAccount[] myAccounts = new BankAccount[2000];
/** The number of BankAccount objects stored in the array in this bank. */
protected int numberOfAccounts = 0;
// Constructors:
/**
* Creates a Bank.
*/
public Bank() {}
// Methods:
/**
* Creates an account with the name and balance, and adds it to
* the bank's list of accounts.
* If the name already exists, no account will be created.
* #param aName The name for the new account.
* #param aBalance The initial balance for the new account.
*/
public void createAccount( String aName, double aBalance) {
BankAccount existing = this.findAccount( aName);
if( existing != null) return;
BankAccount anAccount = new BankAccount( aBalance, aName);
this.myAccounts[ numberOfAccounts] = anAccount;
this.numberOfAccounts++;
}
/**
* Finds an account in the bank's list of accounts by name.
* If no account is found, this method returns null.
* #param aName The name of the BankAccount to search for.
* #return The BankAccount bearing the given name, if found.
*/
public BankAccount findAccount( String aName) {
BankAccount answer = null;
for( int index = 0; index < numberOfAccounts; index++) {
BankAccount anAccount = this.myAccounts[ index];
if( aName.equals( anAccount.getName())) {
return( anAccount);
}
}
return( answer);
}
/**
* Returns a String which represents a short summary of
* all the accounts in the bank.
* #return A String representation of all accounts and their balances in the bank.
*/
public String toString() {
String answer = "";
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();
for( int index = 0; index < numberOfAccounts; index++) {
BankAccount anAccount = this.myAccounts[ index];
String money = currencyFormatter.format( anAccount.getBalance());
answer += anAccount.getName() + " \t" + money + "\n";
}
return( answer);
}
}
and here is the start of the subclass
public class BankSubClass extends Bank{
private double interestPaid;
// Constructor
public BankSubClass(String aName, double aBalance, double aInterest) {
super();
this.interestPaid = aInterest;
}
// Getters
public double getInterestPaid() {return(this.interestPaid);}
// Setters
public void setInterestPaid(double setInterestPaid) {this.interestPaid = setInterestPaid;}
// Other methods
public double endOfYear() {
for (i=0;i<BankAccount.length();i++) {
}
}
}
That for loop at the end are where things are getting a little tripped up. Netbeans is throwing up errors saying "cannot find symbol: variable i". Maybe this has nothing to do with the bank account array I'm trying to use, I don't know. Any help is much appreciated
Thanks for your time!
edit
So here is a continuation of the same homework
Thanks for the replies everyone, your suggestions took care of that problem, I am currently hitting another speed bump at the moment however. The idea behind this method that the for loop is in is to run through the array of BankAccount objects, check to see if any of them are of the InterestAccount type (a class I previously built) and if they are, call the yearlyUpdate() method from that class
Here is the InterestAccount class
public class InterestAccount extends BankAccount {
private double interestRate;
// Constructor
/**
* Create and interest bearing bank account with a balance, name,
* and interest rate
* #param aBalance The balance of the account
* #param aName The name tied to the account
* #param myInterestRate The interest rate of the account
*/
public InterestAccount(double aBalance, String aName, double myInterestRate) {
super(aBalance, aName);
this.interestRate = myInterestRate;
}
// Getters
/**
* Gets the interest rate of the account
* #return the interest rate of the account
*/
public double getInterestRate() {return(this.interestRate);}
// Setters
/**
* Sets the interest rate of the account
* #param interestSet The new interest rate of the account
*/
public void setInterestRate(int interestSet) {this.interestRate = interestSet;}
// Other Methods
/**
* Calculates the interest earned on the account over a year
* #return the interest earned over a year
*/
public double yearlyUpdate() {
double answer = (super.getBalance()*this.interestRate);
return answer;
}
}
Here is the super class I am currently working with
import java.text.NumberFormat;
/**
* Bank represents a single Bank containing a number of BankAccounts.
*/
public class Bank {
// Member variables:
/** The array of BankAccount objects contained in this bank. */
protected BankAccount[] myAccounts = new BankAccount[2000];
/** The number of BankAccount objects stored in the array in this bank. */
protected int numberOfAccounts = 0;
// Constructors:
/**
* Creates a Bank.
*/
public Bank() {}
// Methods:
/**
* Creates an account with the name and balance, and adds it to
* the bank's list of accounts.
* If the name already exists, no account will be created.
* #param aName The name for the new account.
* #param aBalance The initial balance for the new account.
*/
public void createAccount( String aName, double aBalance) {
BankAccount existing = this.findAccount( aName);
if( existing != null) return;
BankAccount anAccount = new BankAccount( aBalance, aName);
this.myAccounts[ numberOfAccounts] = anAccount;
this.numberOfAccounts++;
}
/**
* Finds an account in the bank's list of accounts by name.
* If no account is found, this method returns null.
* #param aName The name of the BankAccount to search for.
* #return The BankAccount bearing the given name, if found.
*/
public BankAccount findAccount( String aName) {
BankAccount answer = null;
for( int index = 0; index < numberOfAccounts; index++) {
BankAccount anAccount = this.myAccounts[ index];
if( aName.equals( anAccount.getName())) {
return( anAccount);
}
}
return( answer);
}
/**
* Returns a String which represents a short summary of
* all the accounts in the bank.
* #return A String representation of all accounts and their balances in the bank.
*/
public String toString() {
String answer = "";
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();
for( int index = 0; index < numberOfAccounts; index++) {
BankAccount anAccount = this.myAccounts[ index];
String money = currencyFormatter.format( anAccount.getBalance());
answer += anAccount.getName() + " \t" + money + "\n";
}
return( answer);
}
}
And finally, here is the subclass in which I am trying to run this for loop
public class BankSubClass extends Bank{
private double interestPaid;
// Constructor
public BankSubClass(String aName, double aBalance, double aInterest) {
super();
this.interestPaid = aInterest;
}
// Getters
public double getInterestPaid() {return(this.interestPaid);}
// Setters
public void setInterestPaid(double setInterestPaid) {this.interestPaid = setInterestPaid;}
// Other methods
public double endOfYear() {
double trackInterest=0;
for (int i=0;i<numberOfAccounts;i++) {
BankAccount working = myAccounts[i];
boolean hasInterest = working instanceof InterestAccount;
if (hasInterest) {
trackInterest = trackInterest + working.yearlyUpdate();
}
return trackInterest;
}
}
}
currently netbeans can't find the "yearlyUpdate()" method when attempting to call it on "working" what I'm not understanding is since the previous code verified that the working object was of the InterestAccount type, it should have that method available
Thanks for the help!
// Other methods
public double endOfYear() {
for (i=0;i<BankAccount.length();i++) {
}
}
You need to declare i
// Other methods
public double endOfYear() {
for (int i=0;i<BankAccount.length();i++) {
}
}
In your loop, variable i is undeclared. Also, since I think you wish to loop through the accounts in the array, I think you should be using the following:
for(int i = 0; < numberOfAccounts; i++)
{
BankAccount bankAccount = myAccounts[i];
// other stuff
}
Like the error says: i is undefined.
try:
for (int i=0;i<BankAccount.length();i++)
I'm guessing that is still bad since you want the length of the array, not the BankAccount class (which may be undefined)
for (int i=0;i<myAccounts.length();i++)
For the error, you need to define the variable i before using it in BankSubClass.endOfYear. The statement should be
for (int i=0;i<BankAccount.length();i++)
You didn't declare i in side the for loop
for (int i=0;i<BankAccount.length();i++)

Categories

Resources