Question

1. Private data fields: name (of String type, initialized to “Bob”), endurance (of int type, initialized to 4) and happiness (of int type, initialized to 3);


Language: JAVA


Part a: Write a class called Geniegotchi with:

1. Private data fields: name (of String type, initialized to “Bob”), endurance (of int type, initialized to 4) and happiness (of int type, initialized to 3);

2. Public methods:

-void setName(String newName) : renames Genie with newName, printsnewName confirmation to screen;

void setName(String newName) : renames Genie with newName, printsnewName confirmation to screen;

- intgetEndurance() : returns current endurance;

-intgetHappiness() : returns current happiness;

-void feed() : this method increases current endurance by 1 if endurance is less than 10, otherwise it prints a “No, thanks...” message to the screen;

-void play() : if happiness is less than 10, then this method increases current happiness by 1 and decreases current endurance by 2, otherwise it prints a “No, thanks...” message to the screen;

-voidaskFortune() : if happiness is greater than 6 and endurance is greater than 5 (that is, if your Genie is happy and healthy enough to predict your fortune...), then:

- using Math.random(), pick a random number ran between 1 and100 (inclusive);

-display to the screen the fortune from line number ran in the fortunes.txt file;

-if happiness is greater than 6 but endurance is at most 5, then: – display message to screen regarding low endurance;

-ifendurance greater than 5 but happiness is at most 6, then: – display message to screen regarding low happiness;

-if both endurance and happiness are at most 5 and 6 respectively, then: – display message telling user to feed and play with the Geniegotchi.

-Regardless of branch, this method should reduce both endurance and happiness by 1.

Part b: Write a class called GeniegotchiDemo containing two static methods:

1. public static void printMenu() :

Prints a welcoming message and the menu. 0- Quit

1- Rename your Geniegotchi

2- Get current stats on Geniegotch

3- Feed your Geniegotchi

4- Play with your Geniegotchi

5- Ask your fortune!

6- Print Menu

(keep options and functionality the same, but feel free to customize these strings)

2. public static void main(String[] args) :

-instantiates a Geniegotchi object;

-prints the menu;

-repeatedly asks for user to enter menu option and performs appropriate actions given user input until user selects 0;

Other than the game stopping when user selects 0 (which should print a nice good bye message), the game should also stop if the Geniegotchi runs out of happiness or endurance (the user is messaged that the Geniegotchi has run away either hungry or unhappy).

Part c: In a text file called genie.txt, answer the following questions:

1. Why is it important for instance variables to be private?

2. Propose a new method for the Geniegotchi class. Provide its signature and describe what it does (what it takes, what it returns, etc). You do not have to implement it.

input this file (fortunes.txt)

The greatest risk is not taking one.
Now is the time to try something new.
If winter comes, can spring be far behind?
A stranger, is a friend you have not spoken to yet.
Conquer your fears or they will conquer you.
You learn from your mistakes, you will learn a lot today.
You only need look to your own reflection for inspiration. Because you are Beautiful!
You are not judged by your efforts you put in; you are judged on your performance.
Rivers need springs.
Good news from afar may bring you a welcome visitor.
When all else seems to fail, smile for today and just love someone.
When you look down, all you see is dirt, so keep looking up.
If you are afraid to shake the dice, you will never throw a six.
A single conversation with a wise man is better than ten years of study.
Happiness is often a rebound from hard work.
The world may be your oyster, but that doesn't mean you'll get it's pearl.
Your life will be filled with magical moments.
You're true love will show himself to you under the moonlight.
Do not follow where the path may lead. Go where there is no path...and leave a trail.
Do not fear what you don't know.
The object of your desire comes closer.
You have a flair for adding a fanciful dimension to any story.
If you wish to know the mind of a man, listen to his words.
The most useless energy is trying to change what and who God so carefully created.
Do not be covered in sadness or be fooled in happiness they both must exist.
You will have unexpected great good luck.
You will have a pleasant surprise.
All progress occurs because people dare to be different.
Your ability for accomplishment will be followed by success.
The world is always ready to receive talent with open arms.
Things may come to those who wait, but only the things left by those who hustle.
We can't help everyone. But everyone can help someone.
Every day is a new day. But tomorrow is never promised.
Express yourself: Don't hold back!
It is not necessary to show others you have change; the change will be obvious.
You have a deep appreciation of the arts and music.
If your desires are not extravagant, they will be rewarded.
You try hard, never to fail. You don't, never to win.
Never give up on someone that you don't go a day without thinking about.
It never pays to kick a skunk.
In case of fire, keep calm, pay bill and run.
Next full moon brings an enchanting evening.
Not all closed eye is sleeping nor open eye is seeing.
Impossible is a word only to be found in the dictionary of fools.
You will soon witness a miracle.
The time is always right to do what is right.
Love is as necessary to human beings as food and shelter.
You will make heads turn.
You are extremely loved. Don't worry.
If you are never patient, you will never get anything done. If you believe you can do it, you will be rewarded with success.
You will soon embark on a business venture.
You believe in the goodness of man kind.
You will have a long and wealthy life.
You will take a pleasant journey to a place far away.
You are a person of culture.
Keep it simple. The more you say, the less people remember.
Prosperity makes friends and adversity tries them.
Nothing seems impossible to you.
Patience is bitter, but its fruit is sweet.
The only certainty is that nothing is certain.
Success is the sum of my unique visions realized by the sweat of perseverance.
When you expect your opponent to yield, you also should avoid hurting him.
Intelligence is the door to freedom and alert attention is the mother of intelligence.
Back away from individuals who are impulsive.
Enjoyed the meal? Buy one to go too.
You believe in the goodness of mankind.
A big fortune will descend upon you this year.
Now these three remain, faith, hope, and love. The greatest of these is love.
For success today look first to yourself.
Determination is the wake-up call to the human will.
There are no limitations to the mind except those we acknowledge.
A merry heart does good like a medicine.
Whenever possible, keep it simple.
Your dearest wish will come true.
Poverty is no disgrace.
If you don't do it excellently, don't do it at all.
You have an unusual equipment for success, use it properly.
Emotion is energy in motion.
You will soon be honoured by someone you respect.
Punctuality is the politeness of kings and the duty of gentle people everywhere.
Your happiness is intertwined with your outlook on life.
Elegant surroundings will soon be yours.
If you feel you are right, stand firmly by your convictions.
Your smile brings happiness to everyone you meet.
Instead of worrying and agonizing, move ahead constructively.
Do you believe? Endurance and persistence will be rewarded.
A new business venture is on the horizon.
Never underestimate the power of the human touch.
Hold on to the past but eventually, let the times go and keep the memories into the present.
Truth is an unpopular subject. Because it is unquestionably correct.
The most important thing in communication is to hear what isn't being said.
You are broad minded and socially active.
Your dearest dream is coming true. God looks after you especially.
You will receive some high prize or award.
Your present question marks are going to succeed.
You have a fine capacity for the enjoyment of life.
You will live long and enjoy life.
An admirer is concealing his/her affection for you.
A wish is what makes life happen when you dream of rose petals.
Love can turn cottage into a golden palace.
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Geniegotchi.java

import java.util; // importing java.util package to use Math.random() function.

public class Geniegotchi{

private String name = "Bob"; // Declaring and initializing the variables name,endurance,happiness
private int endurance = 4;
private happiness = 3;

public void setName(String newName){ // Setting the name with passed parameter when calling the method.
this.name = newName; // this represents a pointer which points the variable of that particular instance.
System.out.println(newName);
}

public String getName(){ // get the name of the instance.
return name;
}

public int getEndurance(){ // get the endurance of the instance.
return endurance;
}

public int getHappiness(){ // get the happiness of the instance.
return happiness;
}

public void feed(){ // this method will increase the endurance.

if(endurance<10)
endurance = endurance+1;
else
System.out.println("No, thanks..");
}

public void play(){ // this method will increase happiness and endurance based on the happiness

if(happiness<10){
happiness = happiness + 1;
endurance = endurance-2;
}
else
System.out.println("No, thanks..");

}

//start********************************************************

public void askFortune(){ //

if(happiness>6 && endurance>5){ // Returns true is happiness >6 and endurance>5
int num = 1 + (int)(Math.random()*100); // Math.random() will return float from 0(Inclusive) to 1.

FileInputStream filestream = null;
BufferedReader br = null;
String requiredFortune = null;
try{
filestream= new FileInputStream("fortunes.txt"); // Creating an filestream object with the directory of file fortunes.txt
br = new BufferedReader(new InputStreamReader(filestream)); // It creates byte streams from the filestream object created
for(int i = 1; i < num; ++i) // This for loop used to skip num-1 lines of data in the file specified.
br.readLine();
requiredFortune = br.readLine();
System.out.println(requiredFortune);
}
catch (FileNotFoundException e) {
log.error(e);
} catch (IOException e1) {
log.error(e1);
}


}

else if(happiness>6 && endurance<=5){
System.out.println("There is low endurance");
}

else if(endurance>5 && happiness<=6){
System.out.println("There is low happiness");
}

else{
System.out.println("Feed and play with Geniegotchi");
}

endurance = endurance - 1;
happiness = happiness - 1;

}

//end******************************************************

GeniegotchiDemo.java

public class GeniegotchiDemo{

public static void main(String[] args){

Geniegotchi geniegotchi = new Geniegotchi(); // creating instance of Geniegotchi class to access the methods we have created in the above class.

boolean flag = true; // setting flag as true so that the program will enter into while loop.
printMenu(); // it will call printMenu() method which is with in the same class.
  
while(flag){

  
Scanner sc = new Scanner(System.in); // Creating scanner object, it will be useful to take user input.

System.out.println("Enter your option");


switch (sc.nextInt()) { // sc.nextInt() will return the integer value from your input.

case 0: {
flag=false; // setting the flag to false will skip the while loop when user input is zero.
break;
}

case 1: { // If the user input is 1, console will prompt the user to enter the name.
System.out.println("Enter new Name");

geniegotchi.setName(sc.next()); // User input name is used to set the name with this method.
break;
}

case 2: { // If user input value is 2, then the following output will be displayed on screen.
System.out.println("Name is " + geniegotchi.getName());
System.out.println("Endurance is " + geniegotchi.getEndurance());
System.out.println("Endurance is " + geniegotchi.getHappiness());
break;
}

case 3: { // If user input value is 3, then it will call feed method.
geniegotchi.feed();
break;
}

case 4: { // If user input value is 4, then it will call the play method.
geniegotchi.play();
break;
}

case 5: { //  If user input value is 5, then it will call the askFortune() method.
geniegotchi.askFortune();
break;
}

case 6: { // If user input value is 6, then again menu will be printed on screen.
printMenu();
break;
}

default: // If user input value is not in the above mentioned values, then the code in the default is applied.
System.out.println("Enter valid option");
break;
}

}
  

}

public static void printMenu(){

System.out.println("0-Quit");
System.out.println("1-Rename your Geniegotchi");
System.out.println("2-Get current stats on Geniegotch");
System.out.println("3-Feed your Geniegotchi");
System.out.println("4-Play with your Geniegotchi");
System.out.println("5-Ask your fortune");
System.out.println("6-Print Menu");

}

}

genie.txt

1. It is important for instance variables to be private, because if it is private then Any child class can use the class variables without having its refference. If it is private, then the variables can be accessed through only the instance of parent class.
For example, there is a class for bank account. Then balance, credit , debit will be the variables
Some one can change there balances as they wish if they are public variables.
If they are private variables then they will be accessed only through the methods with in the class. They cannot be changed explicitly.

2. void getName() method is proposed because while getting the stats of the genie it should be required, as the variable is declared as private. We can get the name only through the method. So, i suggest the void getName() method.

Add a comment
Know the answer?
Add Answer to:
1. Private data fields: name (of String type, initialized to “Bob”), endurance (of int type, initialized to 4) and happiness (of int type, initialized to 3);
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • 23.4 Project 4: Using Pandas for data analysis and practice with error handling Python Please! 23.4...

    23.4 Project 4: Using Pandas for data analysis and practice with error handling Python Please! 23.4 PROJECT 4: Using Pandas for data analysis and practice with error handling Overview In this project, you will use the Pandas module to analyze some data about some 20th century car models, country of origin, miles per gallon, model year, etc. Provided Input Files An input file with nearly 200 rows of data about automobiles. The input file has the following format (the same...

  • 23.4 PROJECT 4: Using Pandas for data analysis and practice with error handling Overview In this...

    23.4 PROJECT 4: Using Pandas for data analysis and practice with error handling Overview In this project, you will use the Pandas module to analyze some data about some 20th century car models, country of origin, miles per gallon, model year, etc. Provided Input Files An input file with nearly 200 rows of data about automobiles. The input file has the following format (the same as what you had for your chapter 13 labs). The following is an example of...

  • Word Guessing Game Assignment Help Needed. This C++ (I'm using Visual Studio 2015) assignment is actually...

    Word Guessing Game Assignment Help Needed. This C++ (I'm using Visual Studio 2015) assignment is actually kind of confusing to me. I keep getting lost in all of the words even though these are supposed to instruct me as to how to do this. Can I please get some help as to where to start? Word guessing game: Overview: Create a game in which the user has a set number of tries to correctly guess a word. I highly recommend...

  • In C Program This program will store the roster and rating information for a soccer team. There w...

    In C Program This program will store the roster and rating information for a soccer team. There will be 3 pieces of information about each player: Name: string, 1-100 characters (nickname or first name only, NO SPACES) Jersey Number: integer, 1-99 (these must be unique) Rating: double, 0.0-100.0 You must create a struct called "playData" to hold all the information defined above for a single player. You must use an array of your structs to to store this information. You...

  • in c++ please Page 1 of 3 (PRO) Project Assignment Instructions Last Charged: 6/1/2020 Read and...

    in c++ please Page 1 of 3 (PRO) Project Assignment Instructions Last Charged: 6/1/2020 Read and follow the directions below carefully and perform the steps in the order listed. You will be solving one program as instructed and turning in your work electronically via an uploaded file within Eagle Online/Canvas and copy & paste the program to the Text Entry box as well. Make sure and check your work prior to uploading the assignment (NOTE: For Steps 1 & 2...

  • /*************************************************** Name: Date: Homework #7 Program name: HexUtilitySOLUTION Program description: Accepts hexadecimal numbers as input. Valid...

    /*************************************************** Name: Date: Homework #7 Program name: HexUtilitySOLUTION Program description: Accepts hexadecimal numbers as input. Valid input examples: F00D, 000a, 1010, FFFF, Goodbye, BYE Enter BYE (case insensitive) to exit the program. ****************************************************/ import java.util.Scanner; public class HexUtilitySOLUTION { public static void main(String[] args) { // Maximum length of input string final byte INPUT_LENGTH = 4; String userInput = ""; // Initialize to null string Scanner input = new Scanner(System.in); // Process the inputs until BYE is entered do {...

  • C++ please Programming Assignment #6 Help Me Find The Secret Message Description: This assignment will require...

    C++ please Programming Assignment #6 Help Me Find The Secret Message Description: This assignment will require that you read in an encrypted message from a file, decode the message, and then output the message to a file. The encryption method being used on the file is called a shift cipher (Info Here). I will provide you with a sample encrypted message, the offset, and the decrypted message for testing. For this project I will provide you main.cpp, ShiftCipher.h, and ShiftCipher.cpp....

  • I need help modifying this code please ASAP using C++ Here is what I missed on this code below Here are the instruction...

    I need help modifying this code please ASAP using C++ Here is what I missed on this code below Here are the instructions Here is the code Produce correct70 pts O pts Full Marks No Marks results and statisfy requirements view longer Comments 1. Your display amount is not readable 2. I withdraw more than my balance, but I didn't see any error message description Documentations10 pts 0 pts Full Marks No Marks : comment i code and block comment...

  • Activity: Writing Classes Page 1 of 10 Terminology attribute / state behavior class method header class...

    Activity: Writing Classes Page 1 of 10 Terminology attribute / state behavior class method header class header instance variable UML class diagram encapsulation client visibility (or access) modifier accessor method mutator method calling method method declaration method invocation return statement parameters constructor Goals By the end of this activity you should be able to do the following: > Create a class with methods that accept parameters and return a value Understand the constructor and the toString method of a class...

  • C++ Programming Objects Problem Assignment: Programming challenge #1 on page 714: "File Head Program" Write a...

    C++ Programming Objects Problem Assignment: Programming challenge #1 on page 714: "File Head Program" Write a program that asks the user for the name of a file. The program should display the first ten lines of the file on the screen (the “head" of the file). If the file has fewer than ten lines, the entire file should be displayed, with a message indicating the entire file has been displayed. Lab Help: Use the following two files to test your...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT