This feels like a very obvious question but I can't figure out how to do it. I have a class called Hive and I want to add a hive object to my Garden class using an addHive method. I know it is going to be something very simple but I can't figure it out =/
My Garden class:
import java.util.ArrayList;
import java.util.Random;
public class Garden {
ArrayList<Flower> flowerbed = new ArrayList<Flower>();
Hive hive = null;
public void anotherDay(){
int size = flowerbed.size();
for(int i = 0; i < size; i++) {
Flower flower = flowerbed.get(i);
flower.grow();
}
}
public void addHive(Hive hive){
}
public void addFlower(Flower flower){
flowerbed.add(flower);
}
public Flower getFlower(int fi){
if(fi < flowerbed.size()){
return flowerbed.get(fi);
}else{
return null;
}
}
public Integer getRandomInteger(Integer max)
{
Random rand = new Random();
int number;
number = rand.nextInt(max) + 1;
return new Integer(number);
}
public Flower findFlower(){
return getFlower(getRandomInteger(flowerbed.size()));
}
public int size(){
return flowerbed.size();
}
}
I have also used what I feel is a rather untidy roundabout method for getting a random flower from my arraylist of flowers- can anyone suggest a better method or is this as good as it gets?
if you need only one hive, use:
public void setHive(Hive hive){
this.hive = hive;
}
If you need multiple hive, do exact the same as with flower. Including creating the list.
ArrayList<Hive> hives = new ArrayList<Hive>();
public void addHive(Hive hive){
hives.add(hive);
}
Related
My problem is that, simply I don't know what code to use to get my value from my getX method to my other classses main method.
package hangman;
public class Hangman {
private int triesLimit;
private String word;
public void setTriesLimit(int triesLimit) {
this.triesLimit = triesLimit;
}
public void setWord(String word) {
this.word = word;
}
public int getTriesLimit() {
return this.triesLimit;
}
public String getWord() {
return this.word;
}
#Override
public String toString() {
return ("Enter Secret Word " + this.getWord()
+ ".\nEnter max # of tries (Must be under 7) "
+ this.getTriesLimit());
}
}
Thats from the sub-class and I am trying to store the value of the triesLimit into the main of this classes main method
package hangman;
public class PlayHangman {
public static void main(String[] args) {
Hangman hangman = new Hangman();
Scanner scn = new Scanner(System.in);
int triesCount = 0;
int correctCount = 0;
hangman.toString();
int triesLimit = hangman.getTriesLimit();
String secretWord = hangman.getWord();
StringBuilder b = new StringBuilder(secretWord.length());
for (int i = 0; i < secretWord.length(); i++) {
b.append("*");
}
char[] secrectStrCharArr = secretWord.toCharArray();
int charCnt = secretWord.length();
for (int x = 0; triesCount < triesLimit; triesCount++) {
while (charCnt >= 0) {
System.out.println("Secrect Word :" + b.toString());
System.out.println("Guess a letter :");
char guessChar = scn.next().toCharArray()[0];
for (int i = 0; i < secrectStrCharArr.length; i++) {
if (guessChar == secrectStrCharArr[i]) {
b.setCharAt(i, guessChar);
correctCount++;
} else if (guessChar != secrectStrCharArr[i]) {
triesCount++;
System.out.println("Incorrect: " + triesCount);hangmanImage(triesCount,correctCount);
}
}
}
}
}
I tried looking it up on here but couldn't find setters and getters used in a sub/superclass
You need to create an instance of the class in the main method to access the variables and method available in that class like so
public class PlayHangman {
public static void main(String[] args) {
Hangman hangman = new Hangman();
hangman.setTriesLimit(2)
int value = hangman.getTriesLimit();
}
You can look into static keyword to access the value directly but that requires a bit more understanding of OOP's and JAVA.
This should work fine.
Hope it helps :)
EDITED
ToString method is just to convert everything in your model class to String which you have done correctly,but you have implemented incorrectly.... Change your ToString content so
#Override
public String toString() {
return ("The Secret Word you entered: " + this.getWord()
+ ".\n The max # of tries (Must be under 7): "
+ this.getTriesLimit());
}
You have initialized Scanner which does what you want, to ask the user to enter the values but again you haven't implemented it so add this to your main method
Scanner scn = new Scanner(System.in);
hangman.setTriesLimit(scn.nextInt());
hangman.setWord(scn.next());
hangman.toString()//Will work now
Trial and error is your best friend now :)
and Google some of the issues rather than waiting for an answer :)
Like rohit said, this is as simple as understand the basics of OOP, specific the encapsulation.
If you want to get a little deeper into OOP patterns, you could use the Observer pattern. This allows you to change the status of any class instance, even if they're not related by inheritance, aggregation, etc.
You can scale the solution by making List of Observer
Your observable interface
public interface IObservable {
// Set the observer
public void setObserver(IObserver iObserver);
// Notify the observer the current status
public void notifyObserver();
}
Your observer interface
public interface IObserver {
public void update(boolean status);
}
Your observer implementation
public class PlayHangman implements IObserver {
private boolean status = false;
public void printStatus() {
System.out.println("Status: " + (this.status ? "Win" : "Lose"));
}
#Override
public void update(boolean status) {
// The instance status is updated
this.status = status;
// Print the current status
this.printStatus();
}
}
Your observable implementation
public class Hangman implements IObservable{
private String goalWord = "";
private String currentWord = "";
private int triesLimit = 0;
private int tries = 0;
private IObserver iObserver;
public Hangman(String goalWord, int triesLimit) {
this.goalWord = goalWord;
this.triesLimit = triesLimit;
}
public void setCurrentWord(String currentWord) {
this.currentWord = currentWord;
this.notifyObserver();
}
public void addTry() {
this.tries++;
this.notifyObserver();
}
#Override
public void setObserver(IObserver iObserver) {
this.iObserver = iObserver;
}
#Override
public void notifyObserver() {
// True = win
this.iObserver.update(this.tries < this.triesLimit &&
this.goalWord.equals(this.currentWord));
}
}
Your Main class
public class Main{
public static void main(String[] args) {
// PlayHangman (game status)
PlayHangman playHangman = new PlayHangman();
// Hangman initializes with a goalWord and the triesLimit
Hangman hangman = new Hangman("HangmanJava", 5);
// Set the observer
hangman.setObserver(playHangman);
// During the game you just can set the current word and add a try
// You're not setting the status directly, that's the magic of the Observer pattern
hangman.setCurrentWord("Hang");
hangman.addTry();
hangman.setCurrentWord("HangmanJava");
}
}
Hope this helps and enjoy Java
So I have been pulling my hair out trying to understand how to call methods on objects in an array. The gist of this homework is to create a comparable interface from scratch, an abstract class called "Weapon", an interface called "Drawable", a couple classes that extend Weapon, and a "Spaceship" class that creates a spaceship with an array of weapon objects.
The following is the code for the "Spaceship" class. The error "not a statement" occures at line 40. The intended purpose of the fireFastestWeapon method is to sort the object array based on each objects fire time, and then activate the fire method for the first n weapons.
public class Spaceship implements Drawable
{
private Weapon [] mountedWeapons = new weapon[4];
private int curWeapon = 0;
public void draw()
{
System.out.print("Ship will be drawn here");
}
public void addWeapon(Weapon w)
{
if (curWeapon<mountedWeapons.length)
{
mountedWeapons [curWeapon] = w;
curWeapon++;
}
else System.out.print("The weapons bay is full Commander");
}
public void fireFastestWeapon(int n)
{
int count=mountedWeapons.length;
int k;
for (int m = count; m>=0;m--)
{
for(int i = 0; i<count-1;i++)
{
k=i+1;
if (mountedWeapons[i].compareTo(mountedWeapons[k]) == 1){
Weapon temp;
temp = mountedWeapons[i];
mountedWeapons[i] = mountedWeapons[k];
mountedWeapons[k] = temp;
}
}
}
if(n>mountedWeapons.length)
{
n=mountedWeapons.length;
}
for (f=0;f<n-1;n++)
{
mountedWeapon[f].fire;
}
}
}
Thank you for looking!
The parentheses on a method call are not optional in Java:
mountedWeapon[f].fire();
Ok, I have an object with multiple instance variables that I would like to sort by, so I read that i have to implement a comparator class and use it.
Basically its a plane class with PlaneSeats object as its member.
PlaneSeats has SeatID, CustomerID
I wish to print the occupied seats by CustomerIDs, does anyone know how?
//This Prints it by SeatID (Since it starts from 0)
for (int i = 0; i < seat.length; i++) {
if (seat[i].isOccupied()) {
System.out.println("SeatID " + seat[i].getSeatID() + " assigned to CustomerID " + seat[i].getCustomerID());
}
}
my failed Comparator code is as follows: I hope to NOT use a seperate class though, hopefully so sort of array.sort function?
import java.util.*;
public class Comparator implements Comparator<Plane> {
public int compare(Plane CustomerID[], Plane CustomerID[]) {
}
}
Arrays.sort(CustomerID, new Comparator<Plane>() {
public int compare(Plane p1, Plane p2) {
PlaneSeat ps1 = p1.getPlaneSeat();
PlaneSeat ps2 = p2.getPlaneSeat();
return ps1.getSeatID().compareTo(ps2.getSeatID());
}
});
This will sort on basis of SeatId. If you want to sort on basis of CustomerId, replace getSeatID() with getCustomerID().
This won't compile
public class Comparator implements Comparator<Plane> {
public int compare(Plane CustomerID[], Plane CustomerID[]) {
}
}
You are breaking the contract.
See this code for a possible solution.
PlaneSeat class definition
public class PlaneSeat {
//Create your custom comparator strategy
public static final Comparator<PlaneSeat> CUSTOMER_COMPARATOR = new CustomerComparator();
//fields
private final Integer customerID;
public PlaneSeat(Integer customerID){
this.customerID= customerID;
}
private static class CustomerComparator implements Comparator<PlaneSeat>{
#Override
public int compare(PlaneSeat o1, PlaneSeat o2) {
return o1.customerID.compareTo(o2.customerID);
}
}
#Override
public String toString() {
return "PlaneSeat [customerID=" + customerID + "]";
}
}
Plane class
public class Plane{
private List<PlaneSeat> seats;
public List<PlaneSeat> getSeats() {
return seats;
}
public void setSeats(List<PlaneSeat> seats) {
this.seats = seats;
}
public void sortSeatsByCustomer(){
Collections.sort(seats,PlaneSeat.CUSTOMER_COMPARATOR);
}
#Override
public String toString() {
return "Plane [seats=" + seats + "]";
}
}
Then in your client code:
public static void main(String args []){
List<PlaneSeat> seats = new ArrayList<>();
for(int i =10;i>0;i--)
seats.add(new PlaneSeat(i--));
Plane plane = new Plane();
plane.setSeats(seats);
System.out.println(plane);//print before sorting
plane.sortByCustomers();
System.out.println(plane);//after sorting by customer
}
You shouldn't name your class "Comparator", since that's already a Java interface name.
Plane CustomerID[]
This does not make sense.
Didn't I answer your prior question about seats?
Your PlaneSeat class should implement Comparable<PlaneSeat> and a method named
public int compareTo(PlaneSeat seat)
In this method, seat is the second seat, the object you're comparing with. The other object is
this
In this method, you can call the
getCustomerID()
method on the objects. It should look like:
public int compareTo(PlaneSeat seat) {
if (this.getCustomerID() > seat.getCustomerID()) return 1;
if (this.getCustomerID() < seat.getCustomerID()) return -1;
return 0;
}
If this gives you the reverse order of what you wanted, swap 1 and -1.
Before your comment
//This Prints it by SeatID (Since it starts from 0)
call
seat = Arrays.sort(seat);
to sort the seats.
You can't implement Comparator class again, it's defined as an interface and you have to implement it by naming a different class.
I am trying to test my player class properly, I have almost done it but I am having issues with my p1.setPlayerHand method. This is the following code I have used for my player class:
Player Class:
package model;
public class Player
{
private String PlayerName;
private Hand PlayerHand;
private boolean Dealer;
public Player(String name)
{
PlayerName = name;
PlayerHand = new Hand();
Dealer = false;
}
public void setName (String name)
{
this.PlayerName = name;
}
public String getName()
{
return PlayerName;
}
public void setDealer (Boolean dealer)
{
this.Dealer = dealer;
}
public boolean getDealer()
{
return Dealer;
}
public void setPlayerHand (Hand hand)
{
this.PlayerHand = hand;
}
public void getHand()
{
PlayerHand.displayCardsinHand();
}
public static void main (String [] args)
{
Player p1 = new Player("player1");
Hand h = new Hand();
//System.out.println(p1);
p1.setName("BARRY");
System.out.println(p1.getName());
p1.setDealer(false);
System.out.println(p1.getDealer());
//this is the error that is preventing my program to run
p1.setPlayerHand(h.addCard(new Card(Suit.CLUBS, CardRank.ACE)));
p1.getHand();
}
}
The following error I receive (after testing the Player Class) is this:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method setPlayerHand(Hand) in the type Player is not applicable for the arguments (void)
at model.Player.main(Player.java:57)
This is the Hand Class underneath (that is linked to the Player Class):
Hand Class:
package model;
import java.util.Vector;
import java.util.Random;
public class Hand
{
private Vector<Card> hand;
public Hand()
{
hand = new Vector<Card>();
}
public void addCard(Card c)
{
hand.add(c);
}
public void displayCardsinHand()
{
for (int card = 0; card < hand.size(); card++)
{
System.out.println(hand.elementAt(card));
}
}
public int getCardsinHand()
{
return hand.size();
}
public Card getCard(int position)
{
if(position >= 0 && position < hand.size())
return (Card)hand.elementAt(position);
else
return null;
}
public int getScore()
{
int value = 0;
boolean ace = false;
for (int i = 0; i < hand.size(); i++)
{
Card c;
c = getCard(i);
value = value + c.getRankValue();
if(c.getRankValue() == 1)
{
ace = true;
}
}
if(ace == true && value + 10 <= 21)
{
value = value + 10;
}
return value;
}
public static void main (String [] args)
{
Hand h = new Hand();
System.out.println(h);
h.displayCardsinHand();
System.out.println(h.getCardsinHand());
h.addCard(new Card(Suit.HEARTS, CardRank.ACE));
System.out.println(h.getCardsinHand());
h.addCard(new Card(Suit.SPADES, CardRank.JACK));
System.out.println(h.getCardsinHand());
h.addCard(new Card(Suit.DIAMONDS, CardRank.QUEEN));
System.out.println(h.getCardsinHand());
h.addCard(new Card(Suit.CLUBS, CardRank.KING));
System.out.println(h.getCardsinHand());
System.out.println(h.getCardsinHand());
h.displayCardsinHand();
h.getCard(1);
System.out.println(h.getScore());
}
}
I have tried modifying the p1.setPlayerHand testing numerous times. I appreciate any advice and tips on how to solve this issue, thank you.
If my code is too long for this post then I will gladly accept any advice on what I should do to cut it short (for future reference).
If anyone here required to see any other classes that I wrote (that may help them help me solve this error) then please notify me on here, thank you.
The method addCard doesn't return anything (void). So you can't pass the result of this method to setPlayerHand(Hand). That's what you're doing.
The code should compile and run if you change
p1.setPlayerHand(h.addCard(new Card(Suit.CLUBS, CardRank.ACE)));
to
h.addCard(new Card(Suit.CLUBS, CardRank.ACE));
p1.setPlayerHand(h);
This is because the setPlayerHand method needs to be passed an object of type Hand, but the addCard method doesn't return anything (it's declared as void).
I am developing a blackberry app in jdp plugin for eclipse.I want to store some values froma na array in the flash memory of blackberry device,& also check whether dat value already exits in the memory or not.I am giving the code which i tried to do with persistent object,bt somehw i am nt able to get want i want,plz modify the code where reqd
package com.firstBooks.series7.db;
import java.util.Random;
import com.firstBooks.series7.AppMain;
import com.firstBooks.series7.db.parser.XMLParser;
import net.rim.device.api.system.PersistentObject;
import net.rim.device.api.system.PersistentStore;
public class DBMain {
public static String answer = "";
public static String selectedAnswer = "";
public static Question curQuestion;
public static int currQuesNumber = 1;
public static int correctAnswerCount = 0;
public static int totalNumofQuestions = 50 ;
static int quesNum[] = new int[20];
static int quesNumNew[];
static int quesCount = -1;
static int randomPosition;
static PersistentObject store;
static {
store = PersistentStore.getPersistentObject( 0xf9f8c7a20bc35c51L);
}
static{
initialize();
}
private static void initialize(){
Random rgen = new Random(); // Random number generator
//--- Initialize the array
for (int i=0; i<quesNum.length; i++) {
quesNum[i] = i;
}
//--- Shuffle by exchanging each element randomly
for (int i=0; i< quesNum.length; i++) {
randomPosition = rgen.nextInt(quesNum.length);
int temp = quesNum[i];
quesNum[i] = quesNum[randomPosition];
quesNum[randomPosition] = temp;
synchronized(store) {
if(quesNum[randomPosition]!=quesNum[i]){
System.out.println("...........i can do it............ ");
store.setContents(quesNum);
store.commit();
}
}
}
}
/*Changed the code to get a unique random number
* #author: Venu
*/
public static int getQuestionNumber() {
quesCount++;
if(quesCount < quesNum.length){
synchronized(store) {
int [] quesNumNew = (int[])store.getContents();
return quesNumNew[quesCount];
}
}
else{
initialize();
quesCount = -1;
return getQuestionNumber();
}
}
}
What is the problem you are encountering? Did you try to wrap the array in an object that implements Persistable interface? It is like the Serializable interface in j2se.
also see:
http://www.blackberry.com/developers/docs/4.5.0api/net/rim/device/api/util/Persistable.html
"A class must explicitly implement this interface for the system to persistently store instances of the class."