Task at hand:Consider a class ratingScore that represents a numeric rating for some thing such as a move. Attributes: A description of what is being rated, The maximum possible rating, rating.
It will have methods to: get rating from ta user, Return the maximum rating posisble, return the rating, return a string showing the rating in a format suitable for display.
a. write a method heading for each method
b. write pre and post conditions for each method
c. write some java statements to test the class
d. implement the class.
I think i did what i was supposed to do, but it is a method and i am not sure that i put enough room for it to be changed much, this is what i have so far.
import java.util.*;
public class MovieRating
{
// instance variables
private String description = " A movie that shows how racism affect our lives and choices";
private int maxRating = 10;
private int rating;
// methods
//precondition: Must have maxRating, rating and description before you post it back to the user.
//rating between 1 and 10, maxRating is set to 10, description of a movie
public void writeOutput()
{
System.out.println("The max rating is: " + maxRating );
System.out.println("Your rating is: " + rating );
System.out.println("The rating for" + description + " is " + rating);
System.out.println("while the max rating was " + maxRating);
}
// PostCondition: Will write maxRating, rating and description to the user.
//Precondition: description, enter the rating
public void readInput()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("What would you rate the movie \"American History x\" out of ten");
System.out.println(description);
rating = keyboard.nextInt();
}
//postcondition: rating will be set to user's input for the movie American History x.
}
This is my Tester program.. not much so far
public class MovieRatingTester
{
public static void main(String[] args)
{
//object of the class MovieRating
MovieRating rating1 = new MovieRating();
rating1.readInput();
rating1.writeOutput();
}
}
SO did i cover what was told to cover? i think i did but i think i did it the wrong way, let me know please.
Ok, my point of view is:
Your class, MovieRating is missing some basic elements of OOP, and that is what I think you suppose to learn in this homework.
The first element missing is a constructor method, what you did is automatically assigning each new MovieRating the same description. The job of the constructor function is giving a unique values to the Object when it first built in the system.
The constructor method is special, it is public and has the exact same name is the class, as we said, in this method you suppose to assign values to your object variables.
the second thing will be to put getters/setters, these are methods who has access to your private values and will be used to assign/get the values from them. Note the use of them in the code:
import java.util.*;
public class MovieRating
{
// instance variables
private String description;
private int maxRating;
private int rating;
/*This is the constructor
Note the use of .this - the expression is used to call the class form withing
itself*/
public MovieRating(String description, int maxRating, int rating) {
this.setDescription(description);
this.setMaxRating(maxRating);
this.setRating(rating);
}
/*These are the getters and setters - get is used for getting the value
and set is used for assigning a value to it*/
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getMaxRating() {
return maxRating;
}
public void setMaxRating(int maxRating) {
this.maxRating = maxRating;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
//This is a method for the printing commands - notice the use of the get methods//
public void printRatings()
{
System.out.println("The max rating is: " + this.getMaxRating() );
System.out.println("Your rating is: " + this.getRating() );
System.out.println("The rating for" + this.getDescription() + " is " +
this.getRating());
System.out.println("while the max rating was " + this.getMaxRating();
}
// PostCondition: Will write maxRating, rating and description to the user.
/*Precondition: description, enter the rating
Note the use of this.setRating()*/
public void readInput()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("What would you rate the movie \"American History x\" out of ten");
System.out.println(description);
this.setRating(keyboard.nextInt());
}
//postcondition: rating will be set to user's input for the movie American History x.
}
Using the constructor, you can create a different rating from your tester program
MovieRating rating1 = new MovieRating("description 1", 10, 5);
MovieRating rating2 = new MovieRating("description 2", 9, 7);
You should not ask / print the data from the Ratings class. These ratings can come from user input, but also from database, web, etc.
1 Add getters and setters for properties of MovieRating
2 Pass the read and write methods to the main. Something like
System.out.println("The rating for the movie |" + rating1.getTitle() + "| is " + rating1.getRating());
3 You are not aggregating ratings to a movie. You can't have two rating to the same movie (v.g., by different users) together. Convert the rating attribute into a Vector to solve it. Change setRating for addRating
There are many other things, but obviously this is a starters exercise and I do not want you to get confused. Work on these issues and check with your teacher.
Java (and OO in general) is all about abstractions. You want to keep your objects as general as possible so that you extend your programs functionality without modifying existing code. This may be beyond what your professor was looking for but here are my suggestions:
1) Rating - separate this into its own class
Again, the rating is totally separate from the movie - songs can have ratings, tv shows can have ratings. Today ratings can be 1-10, tomorrow ratings can up thumbs up or thumbs down, etc. A Movie "has a" rating. Let Rating decide how to prompt the user and how to display itself.
2) Now that you have a separate Movie class, I would take away the hard-coded title, description in my Movie class (this will let me create many movies and rate them).
Then I would eliminate System.out.println in writeOutput method (you can pass in the OutputStream to the function)
By hard-coding in System.in you are forcing implementation. What if tomorrow your professor says "now, instead of printing to the console, print to a file or a database"? You have to modify the code. Actually, instead of writeOutput, I would override the toString method that all Objects have and then just call System.in(movie.toString()) in main.
3) Your test method doesn't "test" anything - it is just executing a statement. Typically a test method will simulate input, execute the statements, and check for the proper state at the end. A good way to signal that the state is improper (if your test fails, like maybe your Movie Rating is -1), then you throw an exception.
4) This is un-OO related and just a preference, but I would put both Pre and Post conditions before the methods. This just makes it easier to find in my opinion.
The idea of OO is that you separate responsibilities/concerns into separate classes. Each class is responsible for itself. This helps to keep your code more flexible and maintainable. Good luck on the assignment!
Related
I do not know how to do the borrowHolding() in the Library Menu I have to create.
So the purpose of the borrowHolding() is for members to be able to borrow books or videos.
This is a just a sample data of the array:
member[0] = new StandardMember("ID", "Name");
member[1] = new PremiumMember("ID", "Name");
holding[0] = new Book("ID", "Title");
holding[1] = new Video("ID", "Title", loanFee);
This is the borrowHolding() method in the TestLibrary class: (the array is in the TestLibrary class too)
public static void borrowHolding(){
String option;
option = input.next();
do{
Scanner scan = new Scanner(System.in);
int tempId = 0;
System.out.println("Enter your ID: ");
String searchID = scan.next();
for(int i = 0; i < member.length; i++){
if(member[i].getID().equals(searchID)){
tempId = i;
}
}
So for the method, I tried to write a code that will search through the array to find the memberID that wants to borrow. It is not completed yet because I believe I am not doing it correctly
There is a Member class that contains
public class Member{
public Holding[] getCurrentHoldings(){
}
}
from the name of the method, it is used to store the holdings of the members that borrowed. So if member 1 borrows a book, that book will be stored inside the array, i think. I was thinking of using an ArrayList for this method, but not sure if it would make sense.
To borrow a book or video, there are certain conditions to be able to borrow, but I do not know how to implement this into the borrowHolding(). One of the condition are in the Holding class.
public class Holding{
public boolean borrowHolding(){
if(status == true && isOnLoan() == false)
borrowDate = newDateTime(); //this is to get the time when the book or video is borrowed
return true;
}else
return false;
}
}
And there is another condition in the Member class is that the Member must have enough credit to borrow. A book loan fee will cost $10 and a video will vary from $4 or $6.
I think I wrote a few information that is not needed but I guess its better than less information.
My problem is what do I do to the borrowHolding() method in the LibraryMenu? how do I make that if a member wants to borrow a holding, the holding will go under the member's array in the member class
public class Member{
public Holding[] getCurrentHoldings(){
}
}
with the condition from the holding class if it is met, and while executing the borrowHolding method, the method from the member class will be able to subtract the member credit by the loan fee from the book or video. is it possible?
public class Member{
private int credit = 30;
public int calculateRemainingCredit(){
credit = credit - //(the loan fee from the book or video class)
}
}
If your intentions are to add a holding to the member class then this is possible. I would suggest adding an ArrayList of Holding's rather than a regular array because it seems as if the size is going to be constantly changing.
public class Member{
private ArrayList<Holding> currentholdings; // you may need to import the arraylist
private int credit;
public void init(){ // goes in constructor
currentholdings = new ArrayList<Holding>();
credit=0;
}
public void addHolding(Holding newholding){ // adds a new holding to the members array
currentholdings.add(newholding);
credit-=newholding.getFee(); // will need to add a fee variable to the holding class;
}
}
And as for checking to see whether or not the member has enough "credit", that can be done in the borrowHolding() method right after you identify the index of the array. I would just recommend adding a parameter of the member to the borrowHolding() method so you can easily access the variables from that member.
if(member[i].getID().equals(searchID)){
tempId = i;
int tempHolding; // index of whatever holding you wanted (could get this from the scanner)
if (holding[tempHolding].borrowHolding(member[tempId])){ // check status
member[tempId].addHolding(holding[tempHolding]); // they have passed the req. so you can add the holding
}
break;
}
Hope this answered your question.
I have these 2 string variables, Hulk and Thing, Hulk has a strength of 10 and Thing has a strength of 53, they both fight (the IF statement) where the higher integer strength wins.
Then Hulk received a powerup boosting his strength to 110, now both fight again. The winner's name is printed on the screen both times.
I have 2 classes (a main class and a supporting one). The IF statement of my supporting class is attached along with my getStrength() method (if anymore code is needed let me know).
I am getting an error where is says: if (name1.getStrength() > name2.getStrength()) ; the error is that getStrength() isn't defined for string where name1 and name2 are.
Also, after solving this, how do I call this subroutine in my main class?
Thanks in advance!
IF Statement:
if (name1.getStrength() > name2.getStrength())
{
System.out.println(name1 + " Wins!");
}
else {
System.out.println(name2 + " Wins!");
}
getStrength method:
int getStrength() {
return this.strength;
}
You need to make the characters as objects of class that has properties like name, strength, etc.
Then this thing should work : if (Hulk.getStrength() > Thing.getStrength())
Firstly you should read about java first steps.
But in your app, you should create class which is representing your fighters and in this class create methods which get the strength from it, i.e.:
public class Fighter {
private String name;
private int strenght;
public int getStrength() {
return strength;
}
}
of course you need to create constructor or other setters/getters in this class. Then you can create objects, i.e.:
Fighter hulk = new Fighter();
Fighter thing = new Fighter();
// use constructor or setters to set strength and name
Now you can call method from class Fighter:
if(hulk.getStrength() > thing.getStrength()) {
// your code
}
Your error is because you were trying to call getStrength() method on object of String type. The best way is to create your own type.
I was asked to write this part of a program and then test it in the following way:
Add some statements to the main method that create two or three contact instances, add them to the address book, and then search for one or two of them. Display the result of each search to see if they were retrieved correctly. Then remove one of them and show the list to be sure that it was removed correctly.
I wasn't entirely sure how to test this. What should I write in the main class? Also, is the rest of the code correct?
Do this for Contact Class:
Create this class in the client package. This class should have three fields (An email address, A full name, A nick name). All of these should be Strings.
Provide two constructors: one full constructor (parameters for all three member variables), and one that has a parameter only for the email address. This second constructor will leave the other two fields null.
Add a toString method (and use the #Override annotation) that works like this:
Contact c1 = new Contact("jenny#gmail.com");
c2.toString() should return "jenny#gmail.com".
Contact c2 = new Contact("jenny#gmail.com", "Jennifer Abott", "jenny");
c2.toString() should return "Jennifer Abott (jenny) jenny#gmail.com".
Do this for AddressBook Class:
Create this class and have a single member variable of type ArrayList<Contact>. Define the variable, don't just declare it
You do not need a constructor.
Write an add method that has a Contact parameter and adds the contact to the contact list.
Write a remove method that has a String parameter, which is the nick name of the contact to remove. It returns nothing. Remove that contact from the contact list. Hint: Use the search method that you already wrote in order to find the contact, then remove that contact from the contact list. See the online documentation for ArrayList for how the remove method works in the ArrayList class. Be sure that the remove method does not crash if you give it a nick name that does not exist in the list.
Write a search method that has a String parameter, which is a nick name to search for. The method must iterate over the contact list. If the nick name is found (use .equals), return that contact. If no contact is found, return null.
Write a show method that displays each Contact instance. It has no parameters and returns nothing. Display one contact per line, and number each line. Like this:
Jeff Meunier (jeff)
Bill Gates (money)
Vladimir Putin (vman)
Make sure that the numbers shown start at 1, not at 0.
Contact class:
package client;
public class Contact
{
private String _emailAddress;
private String _fullName;
private String _nickName;
public Contact(String emailAddress, String fullName, String nickName)
{
_emailAddress = emailAddress;
_fullName = fullName;
_nickName = nickName;
}
public Contact(String emailAddress)
{
_emailAddress = emailAddress;
}
#Override
public String toString()
{
if(_fullName == null)
{
return "<" + _emailAddress + ">";
}
else
{
return _fullName + " " + "(" + _nickName + ")" + " " + "<" + _emailAddress + ">";
}
}
}
Address Book class:
package client;
import java.util.ArrayList;
public class AddressBook
{
public ArrayList<Contact> contactList = new ArrayList<Contact>();
public void add(Contact _contact)
{
contactList.add(_contact);
}
public Contact search(String nickName)
{
for (int n=0; n < contactList.size(); n++)
{
if(contactList.get(n).equals(nickName))
{
return contactList.get(n);
}
}
return null;
}
public void remove(String nickName)
{
if(search(nickName) != null)
{
contactList.remove(search(nickName));
}
}
public void show()
{
for(int n=0; n<contactList.size(); n++)
{
System.out.println(n++ + ". " + contactList.get(n).toString());
}
}
}
I don't have much in the main class yet, but here it is:
Main Class
import java.util.ArrayList;
import client.Contact;
public class Main
{
public static void main(String[] args)
{
Contact c1 = new Contact("jeffm#engr.uconn.edu");
Contact c2 = new Contact("jeffm#engr.uconn.edu", "Jeff Meunier", "jeff");
}
}
"Add some statements to the main method that create two or three contact instances, add them to the address book, and then search for one or two of them. Display the result of each search to see if they were retrieved correctly. Then remove one of them and show the list to be sure that it was removed correctly."
If this is your task then:
1. You created a few contact instances, so this is done, but create a few more with all the available class fields set (this will be needed for the next steps)
2. Now you must create an instance of your address book class.
AddressBook addressBook = new AddressBook();
Add the created contacts to the adress book
addressBook.add(c1);
addressBook.add(c2);
// other contacts
Use the show method to see if everything is correct.
addressBook.show();
Try removing one and show the available contacts again to see if this worked.
addressBook.remove(c1.getNickName()); // Make get method for the nickname
addressBook.show();
Then search for a contact with a certain name, assign this to a new contact object and then print something from it to acknowledge that the object is the correct one.
Here your logic can break, because your search does not cover the possibillity that you have more then one contacts with the same name. So you should return an List of found contacts instead of one contact. Implement this and search again (make sure you search for objects with unique and non-unique names so the testing is acceptable).
Your search testing will look something like this at the end:
List <Contact> contacts = addressBook.search("John");
for(Contact contact in contacts) {
System.out.println(contact.toString());
}
Now since your delete method depends on the search, you will have to change it a bit too. When you do that, test the remove method again as above.
Work out every step until it works fine and your done.
P.S. You may want to print some description between different testing prints, so you can see clearly the results in the output
I've been working at this for a couple hours now and I feel (I hope) I'm right on the verge of figuring it out. This program reads in a bunch of values from an external file and places them in an array of objects which seems to be working just fine.
The Objects properties are:
Bank Account #
Customer Name
Bank Account Balance
1. I can output them in order of Account # (That's how their read in from the file, no sorting is necessary)
2. I've setup a method from implementing Comparable to sort by Bank Account Balance and it's working fine.
3. I need a second sort method, to sort by Customer Name.
- The problem I'm having with this is based on the research I've done and what I've tried I've come to the conclusion that the only way to make this work will be to build my own Comparable Objects (sorry if my terminology is skewed.) I've attempted this as well multiple times with both Java Doc and some similar questions on SE.
When all is said and done I'm going to throw some Listeners into my checkbox group to allow the user to toggle the different sort methods.
Here's the chunks i'm working on:
public class bankAccounts implements Comparable<bankAccounts> {
/* PRIVATE FIELDS HERE, FOLLOWED BY TYPICAL GET AND SET METHODS */
/*SORTS BY ACCOUNT BALANCE WORKING GREAT*/
public int compareTo(bankAccounts b) {
if (accountBalance < b.accountBalance)
{
return -1;
}
if (accountBalance > b.accountBalance) {
return 1;
}
return 0;
}
/* BEGIN SNIPPET OF MAIN CLASS */
/*METHOD I CALL FROM MAIN CLASS, SORTS BY BALANCE ^^ AS SEEN ABOVE */
Arrays.sort(retrievedAccounts);
for (int i=0; i<retrievedAccounts.length; i++) {
String resultFull = Integer.toString(retrievedAccounts[i].getAccountNumber()) + retrievedAccounts[i].getAccountLastName() + Double.toString(retrievedAccounts[i].getAccountBalance());
box.append(resultFull + "\n");
}
/* NORMAL METHOD WHICH OUTPUTS IN ORDER OF ACCOUNT NUMBER, NO SORTING HAPPENING HERE */
for(int x = 0; x < retrievedAccounts.length; ++x)
{
String resultFull=Integer.toString(retrievedAccounts[x].getAccountNumber()) + retrievedAccounts[x].getAccountLastName() + Double.toString(retrievedAccounts[x].getAccountBalance());
box.append("\n\n\n" + resultFull + "\n\n");
}
I'm hoping someone will have some insight towards a next step which might allow me to finish this up. If you have suggestions to take this a completely different direction I'm open to that as well.
This is an idea haven't tested.
Create a another private method to store compareType
public class bankAccounts implements Comparable<bankAccounts> {
private int compareType = 0; // 0 - compare by balance 1-compare by name
In your compare method
public int compareTo(bankAccounts b) {
if(this.compareType == 0){
if (accountBalance < b.accountBalance)
{
return -1;
}
if (accountBalance > b.accountBalance) {
return 1;
}
return 0;
}else{
return customerName.compareTo(b.customerName)
}
Use an implementation of Comparator<bankAccounts> that compares the names of your objects and pass that into the Arrays.sort() method.
Use an anonymous class like this:
Arrays.sort(retrievedAccounts, new Comparator<bankAccounts>() {
public int compare(bankAccounts a, bankAccounts b) {
return a.getName().compareTo(b.getName());
}
});
This code assumes you have a getter method on bankAccounts for customer name called getName()
You would do well to follow java naming conventions:
class names start with a capital letter
class names are singular, not plurals
I've hit a roadblock with this program.
I have a program that involves creating a program that involves the "inventory" of Cadillac, and among all else, I cannot find answers to my questions.
I just do not know what to do. I'll provide the directions and then post the syntax I have so far.
Here is what I have to do:
inventory for a fictional Cadillac Dealership and allows the inventory to be searched to display a list of cars that meet specific criteria.
create an ADT class called Cadillac which contains four fields of instance data: Strings for model name, stock number and color, and an integer for price. The class contains one Constructor, which receives values for all four instance fields, and assigns the parameter values to the instance variables. The class also contains a simple accessor method and mutator method for each field of instance data.
When the program is ran, it loads the inventory from a file, "inventory.dat".
Here is a sample of the contents of the file:
DTS 11210 Glacier White 42706
Escalade 66502 Crimson Pearl 65547
XLR 58362 Radiant Bronze 78840
SRX 16218 Radiant Bronze 44522
Each line (each record) contains 4 fields of data: strings for model name, a 5–digit stock number, and color, and an integer for price. The delimiter between the fields is a tab character (“\t”).
In main(), create an array of Cadillac objects, read in a record from the file, split it into its 4 fields, create a Cadillac object and add it to the array.
the inventory file changes and your program needs to work no matter how many records are in the file. You are guaranteed there will never be more than 100 records in the file (they only have room for 100 cars on the lot), and that each record will contain exactly 4 fields of valid data.
The user can search the inventory two ways: by model name and by price. After you load the inventory, ask the user which search they want to do. If they indicate “by model name”, have them enter the name to search for. The valid model names are: DTS, Escalade, ESV, EXT, SRX, STS, and XLR. Search the inventory for all cars with that name and display a table of results on the console screen.
-When the user indicates he/she wants to search by price, have them enter the price to search
for, then perform the search, displaying all cars that have a price within $3,000 of the search
price.
- The program should loop to do as many searches as the user wants. Let the user end the
program by clicking a “Cancel” button when asked for the type of search they want to perform.
A “Cancel” button on the second question (the model or price to search for) should not end the
program, but your code should recognize it as an invalid entry, and not throw an exception.
Besides the list output, all input and output in the program should be with JOptionPane dialogs.
Here is what I have so far:
import java.util.Scanner;
import java.io.*;
public class Inventory {
public static void main ( String[] args )
{
String line;
String[] fields;
String[] items;
int count = 0;
int recCount;
Cadillac[] list = new Cadillac[100];
try
{
BufferedReader br = new BufferedReader( new FileReader( "inventory.dat" ) );
line = br.readLine();
while( line != null )
{
fields = line.split( "\t" );
items[count++] = new Cadillac( fields[0], fields[1], fields[2],
fields[3] );
line = br.readLine();
}
br.close();
}
catch( IOException e )
{
System.out.println( "Can't open input file. Program terminating." );
System.exit( 1 );
}
}
public static int loadArray(Cadillac[] items)
{
}
}
class Cadillac {
//Instance data
private String model;
private String stockNum;
private String color;
private int price;
//Constructor
public Cadillac(String mdl, String stckNum, String clr, int prc)
{
model = mdl;
stockNum = stckNum;
color = clr;
price = prc;
}
//Set of Accessor and Mutator Methods
public String getModel(){
return model;
}
public void setModel(String newModel){
model = newModel;
}
public String getStockNum(){
return stockNum;
}
public void setStockNum(String newStockNum){
stockNum = newStockNum;
}
public String getColor(){
return color;
}
public void setColor(String newColor){
color = newColor;
}
public int getPrice(){
return price;
}
public void setPrice(int newPrice){
price = newPrice;
}
}
PLEASE HELP! I do not have any other idea of what to do.
In regards to your comment:
It is saying that it cannot find the symbol constructor Cadillac
Your only constructor defined for Cadillac has parameters (String, String, String, int) but when you try to instantiate the object in main, you pass it four Strings. Java is throwing an error because it can't find the correct constructor.
Either pass the last parameter as an int or create a new constructor for your arguments.
Your most immediate problem is that the signature of your data objects constructor is incompatible with the way you are calling it. You have declared your constructor as so:
public Cadillac(String mdl, String stckNum, String clr, int prc)
It takes three string arguments and an int, but you are calling it with four strings:
new Cadillac( fields[0], fields[1], fields[2], fields[3] );
Thats the source of the compile error you reported seeing. You should convert your last String to an int.
new Cadillac( fields[0], fields[1], fields[2], Integer.parseInt(fields[3]).intValue() );
Apart from that there is another glaring error in your code. You declare an array of strings, but are attempting to store instances of 'Cadillac' into it:
String[] items;
// ...
items[count++] = new Cadillac( ... );
I won't code your entire homework for you, but my advise would be to first right down in plain English sentences, each task that needs to be accomplished in order to complete the overall program. Then start translating each individual sentence into code, ideally in the form of methods on your classes that can be called. As you run into issues, come back and ask specific questions and I'm sure there will be someone here willing to help you more.
Good luck.