Define the main method as: public static void main(String[] args) [duplicate] - java

This question already has answers here:
"Main method not found" error when starting program? [duplicate]
(7 answers)
Closed 8 years ago.
Can someone please help me with the code below it builds without any error but when i Run it i get "Error: Main method not found in class Program, please define the main method as:
public static void main(String[] args)"...
any ideas why ?
import java.util.*;
public class Program
{
// Create an array/database for 100 prizes We can increase this number
private Prize[] prizeDatabase = new Prize[100];
// variable to store the next available position in the database
private int currentArrayPosition = 0;
/**
This method displays the menu to the user
*/
private void DisplayMenu()
{
System.out.println("Please select an option from the following:");
System.out.println("1. Enter details of a prize");
System.out.println("2. Print the details stored for all prizes");
System.out.println("3. Search for a prize by description or value");
System.out.println("4. Quit");
// Get the users selection
String selection = new Scanner(System.in).nextLine();
if (selection.equals("1"))
{
EnterPrizeDetails();
}
else if (selection.equals("2"))
{
PrintPrizes();
}
else if (selection.equals("3"))
{
SearchPrize();
}
else if (selection.equals("4"))
{
// do nothing, console will exit automatically
}
}
/**
Search a prize
*/
private void SearchPrize()
{
System.out.println("Please enter search term and press enter: ");
// get the users search term from the console
String searchTerm = new Scanner(System.in).nextLine();
System.out.println("Your following matches are: ");
// Loop round all the prizes
for (Prize prize : prizeDatabase)
{
if ((prize != null))
{
// if the prize matches the users search criters then print the prize
if (prize.MatchPrize(searchTerm))
{
prize.PrintPrize();
}
}
}
System.out.println();
DisplayMenu();
}
/**
Print all prizes in the database
*/
private void PrintPrizes()
{
System.out.println("The following prizes are in the database: ");
for (Prize prize : prizeDatabase)
{
if (prize != null)
{
prize.PrintPrize();
}
}
System.out.println();
DisplayMenu();
}
/**
Enter a prize and store it into the database
*/
private void EnterPrizeDetails()
{
// Take user input and store it to the enter the prize into the database
System.out.println("Please enter a description of the prize and then enter");
String description = new Scanner(System.in).nextLine();
System.out.println("Please enter the colour of the prize and then enter");
String color = new Scanner(System.in).nextLine();
System.out.println("Please enter a value of the prize and then enter");
String value = new Scanner(System.in).nextLine();
Prize newPrize = new Prize();
newPrize.SetPrizeDetails(description, color, value);
// Check if we can add the prize to our database
if (currentArrayPosition < 100)
{
prizeDatabase[currentArrayPosition] = newPrize;
currentArrayPosition++;
System.out.println("A prize has successfully been added to the database.");
}
else
{
System.out.println("Please contact admin to increase the size of the database");
}
System.out.println();
DisplayMenu();
}
static void main(String[] args)
{
Program program = new Program();
program.DisplayMenu();
}
}
class Prize extends Program
{
private String privateDescription;
private String getDescription()
{
return privateDescription;
}
private void setDescription(String value)
{
privateDescription = value;
}
private String privateColor;
private String getColor()
{
return privateColor;
}
private void setColor(String value)
{
privateColor = value;
}
private String privateValue;
private String getValue()
{
return privateValue;
}
private void setValue(String value)
{
privateValue = value;
}
public Prize()
{
}
/**
Setter method to set all the prize details
#param description
#param color
#param value
*/
public final void SetPrizeDetails(String description, String color, String value)
{
setDescription(description);
setColor(color);
setValue(value);
}
/**
Check if a search term matches the prize
#param searchTerm
#return
*/
public final boolean MatchPrize(String searchTerm)
{
boolean match = false;
// Check if the search matches colour or value and return true if it does
if (searchTerm.equals(getColor()) || searchTerm.equals(getValue()))
{
match = true;
}
return match;
}
/**
Print out the details of the prize
*/
public final void PrintPrize()
{
System.out.println("Description: " + getDescription() + " Colour: " + getColor() + " Value: " + getValue());
}
}

When a method don't have a visibility it's package by default. Read here too.
So you should make your
static void main(String[] args)
public.
public static void main(String[] args)
The reason that the compiler don't complain about the public is because it doesn't care about the main method. It doesn't take difference for it if a main exists or not.
It's the JVM which need a start point public and static to launch your application.
Try to make other methods named main and you will see you don't have problems. main is a name like others.

The signature for a method to be used as an entry point for a java application is public static void main(String[] args).
But if the class isn't meant to be used as entry point, static void main(String[] args) is also a valid method signature - so the compiler doesn't complain.
The compiler doesn't know that you want to use the method as the entry point.

Your main method must be declared as public so that it can be accessed by the JVM (Java Virtual Machine) that actually executes the Java bytecode. Java bytecode is what results from compiling the code you write.
The JVM is programmed to look for a specific signature for the main method before executing the program. It finds this signature by looking for a specific series of bytes in the bytecode. That signature only results from compiling a method that is - public static void main. If any of the three modifiers (public, static and void) are omitted the bytecode code will look different and the JVM will not be able to find your main method.
You would not find this error when you compile the program because technically there is nothing illegal about having a method called "main." Main is not a reserved word in Java so there's nothing stopping you from using it as a method (or variable) title. The error will only be detected at runtime when the JVM actually tries to execute the code and cannot find a main method with the appropriate signature.

Related

Using an ArrayList to display values from another class

I am trying to make a to do list that asks you to enter your tasks one by one then display them in order (as in 1. task1, 2. task 2, 3. task 3 etc). But when it displays the tasks it comes back as "0. null" one time instead of listing any of the tasks entered. Here is the script I am using:
1st class
package todolist;
import java.util.ArrayList;
public class ToDoList1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<ToDoList2> list = new ArrayList<ToDoList2>();
System.out.println("Time to make a digital to-do list!");
ToDoList2 n = new ToDoList2();
list.add(n);
System.out.println(ToDoList2.name + "'s to-do list");
System.out.println(ToDoList2.i + ". " + ToDoList2.l);
for(ToDoList2 enhanced : list)
{
System.out.println(ToDoList2.i + ". " + ToDoList2.m);
}
}
}
2nd class
package todolist;
import java.util.Scanner;
public class ToDoList2 {
public static String name;
public static int i;
public static String l;
public static String m;
{
Scanner s = new Scanner(System.in);
System.out.println("First type your name to identify your list in case you lose it");
name = s.nextLine();
System.out.println("Make sure to type \"end\" when you are finished");
System.out.println("Type in the first item on your to-do list");
String l = s.nextLine();
}
public ToDoList2()
{
Scanner s = new Scanner(System.in);
for(int i = 1; i == i; i++)
{
System.out.println("Type in the next item for your to-do list");
String m = s.nextLine();
if("end".equals(m))
{
break;
}
}
}
}
Your code is not correct. ToDoList2 scanning item list from standard input but not storing it. You should do as follow
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class TodoList {
public static String name;
List<String> tasks;
public TodoList(String name) {
this.name = name;
this.tasks = new ArrayList<>();
}
public void addTask(String task) {
this.tasks.add(task);
}
public String toString() {
int i = 1;
StringBuilder stringBuilder = new StringBuilder();
for (String task : tasks) {
stringBuilder.append(i + ". " + task);
stringBuilder.append("\n");
i++;
}
return stringBuilder.toString();
}
}
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("First type your name to identify your list in case you lose it");
String name = s.nextLine();
System.out.println("Make sure to type \"end\" when you are finished");
System.out.println("Type in the first item on your to-do list");
TodoList todoList = new TodoList(name);
String task = null;
while (!(task = s.nextLine()).equals("end")) {
todoList.addTask(task);
System.out.println("Type in the next item for your to-do list");
}
System.out.println(todoList);
}
}
a) Given that each ToDoList2 object is a separate task, I'm not sure why you've made the object class members static?
b) In your ToDoList2 constructor, you've got a for loop that introduces a local variable i which hides the ToDoList2 member variable i. You'd do well to change one of the variable names.
c) In your ToDoList2 constructor, you've got a for loop which is assigning a string returned by the Scanner to a local variable m. Are you sure you want m to be a local variable or do you actually want to assign the returned string to the member variable, m? I'm thinking the latter since the member variable m is never being assigned a value which explains why the code is printing out null.
d) When writing code, it is good practice to use meaningful variable names. Using names like i is OK as an index in a loop but in all other circumstances, you should go for something more descriptive that tells the reader what the variable is storing.
e) Consider making all your ToDoList2 member variables private (and final if possible). Add a print function to the ToDoList2 class to print out the task details. A key principle is Object Oriented Programming is to hide the internals of a class.

Storing data in an Array and outputting that data

I am working on a program that stores data in an Array from the user and outputs that data.
For example:
An input:
Happy HAPPY#foo.com
The output:
NAME: Happy
EMAIL: HAPPY#foo.com
I was hoping someone could look at what I've got so far and give me a pointer on how to continue. I know I have to use the scanner class and scan.nextLine, I'm not sure what comes next. I understand I don't have much, I'm not looking for someone to complete this, but maybe someone who can give me some pointers or point me in the right direction. I believe I have the correct base to my program.
My Code So Far:
import java.util.ArrayList;
import java.util.Scanner;
public class Program5 {
void loadContacts()
{
Scanner scan = new Scanner(System.in);
System.out.println(scan.nextLine());
scan.close();
}
void printContacts()
{
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Program5 program5 = new Program5();
program5.loadContacts();
program5.printContacts();
}
}
Better name the class "person" or like this, but nevermind for the explanation :
public class Program5 {
private String name;
private String mail;
public Program5(){}
void loadContacts(){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a name and a mail like this : name email#email.com (separate with ' ')");
String[] line = scan.nextLine().split(" ");
while(line.length!=2){
System.out.println("Again, enter a name and a mail like this : name email#email.com (separate with ' ')");
line = scan.nextLine().split("/");
}
this.setName(line[0]);
this.setMail(line[1]);
scan.close();
}
void printContacts() {
System.out.println("NAME : "+this.name+"\nEMAIL : "+this.mail);
}
public static void main(String[] args) {
Program5 program5 = new Program5();
program5.loadContacts();
program5.printContacts();
}
public void setName(String name) {
this.name = name;
}
public void setMail(String mail) {
this.mail = mail;
}
}
In the loadyou ask the user, check it he enter 2 element separate by '/' and if yes store them as attributes to be able to get them in another method ;)
You should have a global varible to store the name and the email. Try adding these lines on the top of the code. after public class Program5 {.
private String Name, Email;
The you must assing this values to void loadContacts(). Spliting the string you read.
void loadContacts()
{
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
String arr[] = input.split("\\s+");
Name = arr[0];
Email = arr[1];
scan.close();
}
And finally on void printContacts().
void printContacts()
{
System.out.println("NAME: " + Name + "\nEMAIL: " + Email);
}
Here is the code runnig: http://ideone.com/mjyfHK
You can do a variety of things.
You can make loadContacts() and printContacts() static methods, and also change loadContacts() so that it returns an Array or 2D array or however you choose to represent a name-email pair. Then change printContacts()` to take in that type and iterate through that Array to print out each name/email pair. This solution is a bit more work but you won't have to create an object of the same class within the main method of that class.
or
You can keep your method as they are and instead create a new field for the program class, called contacts and it would be of the type that you choose for representing name/email pairs. You would add items to contacts in loadContacts() and iterate through it in printContacts(). Then you don't have to change anything in your main method.

object java class code

These are the instructions for this assignment. Any help would be appreciated. I am a rookie when it comes to java and cant seem to figure this out.
This exercise has two classes. The first class is named ObjectsToArrayList. The second class is called just Objects.
Your responsibility is to create the Object class and figure out how the ObjectsToArrayList class works.
The ObjectsToArraylist class will create an ArrayList of objects. It will ask for and populate the data fields of an Object, then add it to the ArrayList. This can be done for as many instances of the Object that the user wants to enter.
Requirements for the Object Class.
2 data fields: int obj_id, String obj_name.
2 Constructors: No-Arg and one that takes both values and assigns them to the data field.
Gets and sets for both data fields
A toString() method that returns output like:
The object ID is 22 and the name is Andrea
Here's my code
import java.util.*;
/**
*
* #author Student
*/
public class ObjectsToArrayList {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList <Object> objectList = new ArrayList();
System.out.println("Please enter information for your favorite object!");
do { // collect an indicator to determine the method to call
Object object = new Object();
System.out.println("Enter a whole number for the ID of your object:\n"
+ "or enter 99 to quit.");
int tmpInt = input.nextInt();
// if 99 is entered exit the loop.
if (tmpInt == 99) {
break;
}
object.setObj_id(tmpInt);
input.nextLine();
// ask for the Object Name
System.out.println("Please enter the name of the Object:");
object.setObj_name(input.nextLine());
objectList.add(object);
} while (true); // this is a contineous loop if the break isn't included.
for(Object object:objectList) {
System.out.println(object.toString());
}
}
}
//****************************************************
//**** Objects Class is below this block **
//****************************************************
class Object {
// enter object code here (This is the part I cannot figure out)
}
Here are examples of constructors:
class Objects{
// This is a constructor with no argument
public Objects(){
}
// This is a constructor with 2 arguments
public Objects(int obj_id, String obj_name){
}
}
You can refer in the link below to learn more about creating constructors and assigning values to fields:
http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
Note: Do not use Object as a class because Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.
http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html
Try something like this:
public class ObjectsToArrayList {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList <Object> objectList = new ArrayList();
System.out.println("Please enter information for your favorite object!");
do { // collect an indicator to determine the method to call
Object object = new Object();
System.out.println("Enter a whole number for the ID of your object:\n"
+ "or enter 99 to quit.");
int tmpInt = input.nextInt();
// if 99 is entered exit the loop.
if (tmpInt == 99) {
break;
}
object.setObj_id(tmpInt);//runs the setObj_id method in the Objects class
//for the users input
input.nextLine();
// ask for the Object Name
System.out.println("Please enter the name of the Object:");
object.setObj_name(input.nextLine());//runs the setObj_name method in the Objects class
//for the users input
objectList.add(object);
} while (true); // this is a contineous loop if the break isn't included.
for(Object object:objectList) {
System.out.println(object.toString());//prints out what the toString method returns in
//the Objects class
}
}
}
//****************************************************
//**** Objects Class is below this block **
//****************************************************
public class Objects
{
//add stuff like methods and instance variables
private int ID;
private String name;
public Objects(){//default constructor
}
public Objects(int i, String n){//constructor to change both ID and name at the same time
ID = i;
name = n;
}
public void setObj_id(int i){//constructor to change only ID
ID = i;
}
public void setObj_name(String n){//constructor to change only name
name = n;
}
public String toString(){
return (name + ": " + ID);
}
}
Ok so you want to create your own object soo have 2 classes rather, personProfile and arrayOfProfiles
So class personDetails object note seperate class file not *not in same file
class personProfile{
private int ID = 0;
private String Name = "";
public personProfile(int id,String name){
ID = id;
Name = name;
}
public int getID(){
return ID;
}
public String getName(){
return name;
}
}
now the other class* different file
class arrayOfProfiles{
personProfile profiles[] = new personProfile[0];
public personProfile[] array(){
return profiles;
}
public void addProfileToArray(personProfile profileObject){
personProfile arrayMod = new personProfile[profiles.length+1];
for(int i = 0;i<profiles.length;i++){
arrayMod[i] = profiles[i];
}
arrayMod[arrayMod.length-1] = profileObject;
}
public static void main(String args[]){
arrayOfProfiles profiles = new arrayOfProfiles();
for(int i = 0;i<5;i++){
int id = Integer.parseInt(JOptionPane.showInputDialog("enter ID ");
String name = JOptionPane.showInputDialog("enter name");
profiles.addProfileToArray(new personProfile(id,name));
}
for(int i =0;i<profiles.array().length;i++){
System.out.println("ID :"+profiles[i].getID()+" name - "+profiles[i].getName());
}
}
}

Cannot make static reference to the non-static method printMenuGetSelection() from the type SpecialAssignment1 [duplicate]

This question already has answers here:
Cannot make a static reference to the non-static method
(8 answers)
Closed 8 years ago.
Pre Edit: The problem is when I mark it as static, so
public static int printMenuGetSelection()
it gives me the message
This Static method cannot hide the instance method from AMenu
I'm writing a Java program that reads files and gives the user multiple options for displaying things about the file. I'm currently writing a menu interface that implements an actual Interface and makes the program easier to use. However, I'm getting an exception when I try to call the menu method in my main method. The error is on the one active line in the main method where I call printMenuGetSelection(), and it says
Cannot make static reference to the non-static method printMenuGetSelection() from the type SpecialAssignment1
How do I fix this bug? here is my program:
import java.util.*;
import java.io.*;
import java.text.*;
public class SpecialAssignment1 implements AMenu {
public static void main(String[] args) throws FileNotFoundException{
printMenuGetSelection();
/*System.out.println(RewardCustomer("transactions1.dat")); //CURRENTLY DISPLAYING TOP 6, DOESN'T WORK WITH TIES OR TOPN < lines
ProcessTransactionsFile("transactions2.dat", 52);*/
}
public int printMenuGetSelection() throws FileNotFoundException{
boolean runProgram = true;
Scanner s = new Scanner(System.in);
printStartMenu();
String startMenuSelection = s.next();
while(runProgram){
if(startMenuSelection.equals("1")){
startMenu1();
} else if(startMenuSelection.equals("2")){
startMenu2();
} else if(startMenuSelection.equals("3")){
startMenu3();
} else if(startMenuSelection.equals("4")){
startMenu4();
} else if(startMenuSelection.equals("5")){
runProgram = false;
} else {
System.out.println("***Selection Invalid!***");
}
}
return 1;
}
public static void printStartMenu(){
System.out.println("**********************************************************");
System.out.println("Main Menu...");
System.out.println(" (1) RewardCustomers");
System.out.println(" (2) ProcessTransactionFiles");
System.out.println(" (3) TopCustomers");
System.out.println(" (4) QueryStatsFile");
System.out.println(" (5) Quit");
System.out.println(" Enter a valid selection: ");
}
public static void startMenu1() throws FileNotFoundException{
boolean runMenu1 = true;
while(runMenu1){
Scanner s = new Scanner(System.in);
System.out.println("Reward Customers Menu...");
System.out.println(" (1) Use transactions1.dat");
System.out.println(" (2) Use transactions2.dat");
System.out.println(" (3) Quit");
System.out.println(" Enter a valid selection: ");
String menu1Selection = s.next();
if(menu1Selection.equals("1")){
System.out.println(RewardCustomer("transactions1.dat"));
} else if(menu1Selection.equals("2")){
System.out.println(RewardCustomer("transactions2.dat"));
} else if(menu1Selection.equals("3")){
runMenu1 = false;
} else {
System.out.println("***Selection Invalid!***");
}
}
}
public static void startMenu2(){
boolean runMenu2 = true;
while(runMenu2){
Scanner s = new Scanner(System.in);
System.out.println("Process Transaction Files Menu...");
System.out.println(" (1) Create transactions2.dat file");
System.out.println(" (2) Display transactions1.dat");
System.out.println(" (3) Display transactions2.dat");
System.out.println(" (4) Query transactions1.dat");
System.out.println(" (5) Query transactions2.dat");
System.out.println(" (6) Quit");
System.out.println(" Enter a valid selection: 4");
String menu2Selection = s.next();
if(menu2Selection.equals("1")){
}
}
}
public static void startMenu3(){
}
public static void startMenu4(){
}
I removed the code not pertaining to the question to make it easier to read, if it's needed I'll put it in. Also, here is the AMenu Interface. Please do not suggest any other changes to my program. If you think it's dumb to have the menu as an Implemented Interface, I 100% agree with you but that's the requirement. For reference, here is the AMenu Interface:
import java.io.FileNotFoundException;
public interface AMenu {
/**
* Prints a menu with selections and logic to return a valid selection.
* #return the selected item
*/
abstract int printMenuGetSelection() throws FileNotFoundException;
/**
* #return the numberOfMenuItems
*/
abstract int getNumberOfMenuItems();
}
Since printMenuGetSelection() is non static, you cannot call it from within the static method main() unless you create an instance of SpecialAssignment1 and call the method on that object.
you need to create an instance of your SpecialAssignment1 then call the method from that, as abstract requires an object.
As other people have said, you need to create an instance of SpecialAssignment1, then call printMenuSelection() on it. Part of what's making this confusing though is that you've stuck the main method inside the menu interface class. This whole thing would make more sense if you had a class SpecialAssignment1 with just the main method and a separate MenuGenerator class with all the menu generation stuff.

Need someone to check my Program, I think my equals method is wrong

I am done with this assignment think god, and was wondering if someone could please check it so I can make sure there are no errors, it seems like I work hard on these programs but always doing something wrong. I am doing this course online so I have a hard time communicating with the instructor. I think my equals to methods might be wrong but, they seem to have no error when running the program and the program is 100% done. Please take the time to look over it, and thank you so much for your time.
Assignment:
About the first class
Create a class named RoomDimension that has two fields: one for the length of the room and another for the width. The RoomDimension class should have two constructors: one with no parameters (a default) and one with two parameters. The class should have all of the appropriate get and set methods, a method that returns the area of the room, a toString method that will allow us to print the length, width and area of the room and an equals method to compare room dimensions.
About the second class
Create another class named RoomCarpet that has two fields: one is a RoomDimension object and the other is a field that holds the cost of carpet per square foot. The class should have two constructors: one with no parameters and one with the two field parameters (RoomDimension and double). The class should have a get and set method for each field, a method that returns the total cost of carpeting the room, a toString method that will print all of the room information (length, width, area) and cost of the carpet per square foot and the total cost to carpet the room. (Dollar amounts should be displayed with two decimal places.), and an equals method that compares room dimensions and carpet cost.
About the application program
Write an application program that contains one RoomDimension object and one RoomCarpet object. The program should allow the user to enter the length and width of the room and the cost of the carpet per square foot. The program should instantiate both objects and use a simple System.out.println statement to print all of the information about the RoomCarpet object.
MY code:
import java.text.DecimalFormat;
public class RoomCarpet {
private RoomDimension rmSize;
private double pricePerSqFt;
//default constructor
public RoomCarpet()
{
this.rmSize = new RoomDimension();
this.pricePerSqFt = 0.00;
}
//parameters constructor
public RoomCarpet(RoomDimension rmSize, double pricePerSqFt)
{
this.rmSize = new RoomDimension(rmSize.getRmLength(),rmSize.getRmWidth());
this.pricePerSqFt = pricePerSqFt;
}
//accessor methods
public RoomDimension getRmSize()
{
return new RoomDimension(rmSize.getRmLength(),rmSize.getRmWidth());
}
public double getPricePerSqFt()
{
return this.pricePerSqFt;
}
// mutator methods
public void setRmSize(RoomDimension rmSize)
{
this.rmSize = new RoomDimension(rmSize.getRmLength(), rmSize.getRmWidth());
}
public void setPricePerSqFt(double pricePerSqFt)
{
this.pricePerSqFt = pricePerSqFt;
}
// Or price for the room to be carpeted
public double rmTotalCost()
{
return rmSize.getAreaRoom() * pricePerSqFt;
}
//toString method
public String toString()
{
DecimalFormat dollar = new DecimalFormat("$#,##0.00");
String str = this.rmSize.toString() + " Price per sq. ft : " +dollar.format(pricePerSqFt) + " Price to carpet Room: " + dollar.format(rmTotalCost()) + '\n';
return str;
}
public boolean equals(RoomCarpet object2)
{
boolean status;
if ((this.equals(object2)==true)&&(this.pricePerSqFt==object2.pricePerSqFt))
status = true;
else
status = false;
return status;
}
}
public class RoomDimension {
private int rmLength;
private int rmWidth;
//Default constructor
public RoomDimension()
{
rmLength=0;
rmLength=0;
}
// constructor with parameters
public RoomDimension(int rmLength, int rmWidth)
{
this.rmLength=rmLength;
this.rmWidth=rmWidth;
}
// accessor methods
public int getRmLength()
{
return this.rmLength;
}
public int getRmWidth()
{
return this.rmWidth;
}
//mutator methods
public void setRmLength(int rmLength)
{
this.rmLength=rmLength;
}
public void setRmWidth(int rmWidth)
{
this.rmWidth =rmWidth;
}
//area of the room
public int getAreaRoom()
{
return this.rmLength * this.rmWidth;
}
//toString Method
public String toString()
{
String str = "Room Length: " + this.rmLength + " Room Width: " + this.rmWidth + " Area of Room: " + this.getAreaRoom();
return str;
}
public boolean equals(RoomDimension object2)
{
boolean status;
if (this.getAreaRoom() == object2.getAreaRoom())
status = true;
else
status = false;
return status;
}
}
import java.util.Scanner;
public class CarpetPrice {
public static void main(String[] args)
{
RoomDimension rmSize;
RoomCarpet rmCarpet;
Scanner keyboard = new Scanner(System.in);
rmSize=new RoomDimension();
System.out.println(" Please enter the length of the room: ");
int rmLength= keyboard.nextInt();
rmSize.setRmLength(rmLength);
System.out.println("Please enter the rooms width: ");
int rmWidth = keyboard.nextInt();
rmSize.setRmWidth(rmWidth);
System.out.println("Please enter the price per sq foot: ");
double pricePerSqFt = keyboard.nextDouble();
rmCarpet = new RoomCarpet(rmSize, pricePerSqFt);
System.out.println("\n"+rmCarpet.toString());
}
}
The equals method must have an Object argument and you have to override the hashCode method too.
#Override
public boolean equals(Object obj)
{
}
I would say that for RoomDimension, two objects are equal only if both length and width match. Especially if you're laying carpet, a 4x5 room would be much different from a 1x20 hallway, even though the total area is the same. For the RoomCarpet object, again equal only if both the dimensions are equal and the price is the same, I guess.
Also, I would write some tests because you may be surprised at what happens when you call RoomCarpet's .equals() method (as written above).
Finally, pay attention to your indenting because that's important for any reader of your code.

Categories

Resources