Define the instance variables of the object

Assignment Help JAVA Programming
Reference no: EM131587273

Topics

- Writing/Testing classes

Coding Guidelines
- Give identifiers semantic meaning and make them easy to read (examples numStudents, grossPay, etc).
- Keep identifiers to a reasonably short length.
- Use upper case for constants. Use title case (first letter is upper case) for classes. Use lower case with uppercase word separators for all other identifiers (variables, methods, objects).
- Use tabs or spaces to indent code within blocks (code surrounded by braces). This includes classes, methods, and code associated with ifs, switches and loops. Be consistent with the number of spaces or tabs that you use to indent.
- Use white space to make your program more readable.
- Use comments after the ending brace of classes, methods, and blocks to identify to which block it belongs.

Assignment/Lab Documentation
At the beginning of each programming assignment you must have a comment block with the following information:

/*-------------------------------------------------------------------------
// AUTHOR: your name
// FILENAME: title of the source file
// SPECIFICATION: description of the program
// FOR: CSE 110- Lab #6
// TIME SPENT: how long it took you to complete the assignment
//-----------------------------------------------------------*/

Getting Started
Create a class called Lab6 and a class called SuperHero. Be sure to import the Scanner class in Lab6. Be sure to name your files Lab6.java and SuperHero.java, respectively. Also, make sure the files are saved in the same directory.

Task Overview
Remember that creating by creating a class, we are defining a Java Object. These objects are often used to model various real-world objects. The overall goal of this lab is to create a class to model a superhero. This SuperHero class will then be tested using the Lab6 driver class.

Part 1: Defining the Class
The first part of creating any class is to declare it as a class. The overall set up for the SuperHero class when the lab is done should look something like the code below. Copy it to your SuperHero.java file.

public class SuperHero {
// instance variables go below here

// the two constructors go below here

// getNumberOfHeroes() goes below here

// recordSave() goes below here

// the second recordSave method goes here

// killHero() goes below here

// printSuperHeroRecord() goes below here
}

Part 2: Defining the Instance Variables
Instance variables are used to define different traits about an object. In the SuperHero class, define the following instance variables in the appropriate place:
- numberOfHeroes, a static int
- heroName, a String
- secretIdentity, a String
- numberOfLifeChances, an int
- numberOfPeopleSaved, an int

Notes & Hints
- Be sure to declare all of your instance variables as private, as we do not want other programs to have direct access to them.
- numberOfHeroes needs to be a static variable, because its value needs to be the same between all instances of the SuperHero class. You can read about static instance variables on page 400 or see the video example.

- As an example for the other three, the heroName instance variable is written below:
private String heroName;
The section on instance variables starts on page 371.

Part 3: Creating the Constructors
The purpose of a constructor is to define the instance variables of the object upon its creation. By allowing for arguments to be passed into the constructor, these instance variables can be easily customized. For example, the following constructor will allow for the heroName, secretIdentity, and numberOfPeopleSaved to be customized:
public SuperHero(String initHeroName, String initSecretIdentity, int initPeopleSaved) { numberOfHeroes++; // one more hero created
numberOfLifeChances = 2; // start the hero with two lives heroName = initHeroName;
secretIdentity = initSecretIdentity; numberOfPeopleSaved = initPeopleSaved;
}
Include this code in the constructor section of your SuperHero class. Notice how numberOfHeroes and numberOfLifeChances are explicitly defined in the constructor, while the values of the other instance vari- ables depend on what was passed into the constructor.

Now, create another constructor that will only take one parameter for the hero's name. The constructor should contain the following (you can place it below the first one):
- Only allow the heroName as a parameter for the constructor
- Use the same code for defining the numberOfHeroes and the numberOfLifeChances
- Set the heroName attribute to the parameter passed into the constructor
- Set the secretIdentity to "unknown"
- Set numberOfPeopleSaved to 0
When this part is completed, you will have a SuperHero class with two constructors. The following calls will be valid calls to one of the constructors:
SuperHero hero1 = new SuperHero("Superman", "Clark", 1000); SuperHero hero2 = new SuperHero("Batman");
The section on constructors start on page 375.

Part 4: Creating the Other Methods
Now that we have the instance variables and constructors made, we need to define some other methods to make the class useful.

Method: getNumberOfHeroes
First, we will create an accessor method to return the number of heroes. To do this, simply fill in the body of this method:
public static int getNumberOfHeroes() {
// Put something here (only 1 line is required)
}

Method: recordSave
Next, we will create a method to keep track of when the hero saves someone. This method will simply increment the numberOfPeopleSaved instance variable by 1. This method is given to you below. Include it in your lab.

public void recordSave() { numberOfPeopleSaved++;
}
Now, create another method called recordSave. This time, require an integer, called num, as input. Inside of the method, increment the number of people saved by this value. This allows a hero to save multiple people at once. An unfinished version of this is given below:

public void recordSave(<define a parameter, "int num", here>) {
// Increment numberOfPeopleSaved by num
}

Method: killHero
If a hero is defeated by his/her enemy, they should lose a life. This is represented by decreasing numberOfLifeChances by 1. However, the hero cannot possibly die if they have no lives. So, if the hero has no lives left, display a message stating as such. The code is partially given to you below:

public void killHero() {
if (<check if the hero has lives, using numberOfLifeChances>) {
// Decrease numberOfLifeChances by 1
} else {
// Print a message saying the hero is dead
}
}

Method: printSuperHeroRecord
This method will simply print out the different attributes of the hero. The output should look like the following:

Name: Superman
Secret Identity: Clark Status: Alive
People Saved: 1000
Note that if the hero has no lives left, the status should be "Dead".

Part 5: Create a Test SuperHero
Now that we have the SuperHero class created, we need to make a class to test it. This is the Lab6.java file, as explained in the Getting Started section. Make sure you've imported the Scanner class. All of the following instructions should be implemented inside of the main method of the Lab6 class. Copy the following code into your Lab6 main method. We will be modifying this code.

// Create a Scanner object for later use Scanner scan = new Scanner(System.in);
// Create a superhero called Spider-Man System.out.println("Creating Spider-Man......."); SuperHero spiderman = new SuperHero("Spider-Man");
// Ask the user to enter a superhero name System.out.println("\nWhat is the name of your superhero?"); String heroName = scan.nextLine(); // This is line 10 System.out.println("What is his secret identity?");
/** 13: Read in the identity */ System.out.println("Creating your super hero.......");
/** 16: Create the hero called yourHero, who saved 10 people */ System.out.println("\nSpider-Man just saved 100 lives!");
/** 19: Call recordSave on spiderman with 100 as the input */ System.out.println("Oops, Spider-Man was shot dead twice!");
/** 22: Kill spiderman twice */ System.out.print("\nYour hero saved a kidnapped kid "); System.out.println("but was shot once");
/** 26: Kill your hero once */
/** 27: Add 1 to your hero's lives saved */ System.out.println("\n---- Superhero information ----");
/** 30: Store the number of heroes in an int called numHeroes */ System.out.println("There are " + numHeroes + " known superheroes."); spiderman.printSuperHeroRecord();
System.out.println();
/** 33: print the record of yourHero */

Replace the "/**<comment>*" comments with the appropriate code. Each of these comments contains its line number for reference in the below hints.

Reference no: EM131587273

Questions Cloud

Efficiency in an organization storage system : Evaluate the importance of measuring storage efficiency in an organization's storage system. Suggest the main approaches for measuring storage efficiently.
Processing arrays of objects : Stocks4U needs to develop an app for you to manage your stock purchases. You should be able to store a list of stock purchases, view the individual stocks
What are your goals in life : What are your goals in life? Describe steps you will take to achieve your goals and ambitions. As you can see we are in the travel industry.
What is the smallest number greater than n : How many edges does a forest with n trees and v vertices (and vi vertices in the ith tree) have?
Define the instance variables of the object : Define the instance variables of the object upon its creation. By allowing for arguments - create another constructor that will only take one parameter
Annotate and evaluate their rhetorical effectiveness : Annotate and evaluate their rhetorical effectiveness and their usefulness in your essay
Decrease net working capital of a firm : Does IRP imply that interest rates are the same in all countries? Which of the following will decrease net working capital of a firm?
Internal and external customers : What is the company's philosophy related to both internal and external customers? What strategies does the company use to meet customer expectations?
What steps you would take to reduce the chances of conflict : Describe what the issues were and discuss what steps you would take to reduce chances of conflict escalation between teams if you saw this occurring in future.

Reviews

Write a Review

JAVA Programming Questions & Answers

  Create set methods for color and height, but not for price

Create a class for the business named Candle that contains data fields for color, height, and price. Create get methods for all three fields

  Write a gui that can be used to keep track of the score

This coursework is only 40% of your module mark. You will write a GUI that can be used to keep track of the score during a lawn tennis match at Wimbledon.

  Recursion in binary search trees

Assignment is intended to give you practice writing recursive code that traverses a common computer programing structure: a binary search tree.

  How do you write else statements

How do you write else statements when you write an infinite loop?

  2 before we developed a stringlog adt it represents a log

2. before we developed a stringlog adt. it represents a log that holds objects of class string. suppose that instead of

  Reimplement the labeledpoint class of exercise

Reimplement the LabeledPoint class of Exercise P9.12 by storing the location in a java.awt.Point object. Your toString method should invoke the toString method of the Point class.

  Program to find maximum-minimum of sequence of values

Common task which should be done in loop is to find maximum and minimum of sequence of values. File Temps.java contains program which reads in sequence of hourly temperature readings over 24- hour period.

  Writing a program that computes the average salary

The first programming project involves writing a program that computes the average salary for a collection of employees of different types. This program consists of four classes

  Implement threads and a gui interface using advanced java

Implement threads and a GUI interface using advanced Java Swing classes - Implement a thread for each job representing a task that ship requires

  Develop the change calculator

Develop the Change Calculator - In this exercise, you'll develop an application that tells how many quarters, dimes, nickels, and pennies are needed to make change for any amount of change from 0 through 99 cents

  It inherits the functionality of super class

It inherits the functionality of super class Package and contains an additional data member representing an additional fee per ounce charged for overnight-delivery service.

  Comparator that compares point objects by their distance

write a comparator that compares point objects by their distance from the origin of (0,0). points that are closer to the origin are considered to come before those which are further from the origin

Free Assignment Quote

Assured A++ Grade

Get guaranteed satisfaction & time on delivery in every assignment order you paid with us! We ensure premium quality solution document along with free turntin report!

All rights reserved! Copyrights ©2019-2020 ExpertsMind IT Educational Pvt Ltd