Java - User input in a main method and calling setters to main - java

This is my assignment if you want to read it:
Create a NetBeans project. Create a Java file for EACH of the three classes. For example, add to your project a new file calledBook.java and then create the new class from scratch in that file. Use your UML diagrams as the guideline for writing the code. The variables and methods from the diagrams will be part of each of your classes. Make sure ALL your variables are declared to be private.Protect Your Data!Objects store data or information! When variables are declared private you can protect or guard that information like a Pit Bull protects a piece of meat. Never allow bad data to be stored in your objects!In each 'set' method, make sure the value passed to the method is in range, greater than or equal to the minimum and less than or equal to the maximum. For strings,you may check the length of the string. Each 'set' method should have some sort of 'if-else' statement, assign the data when it is good and print an informative message when an incorrect value is passed. The Shoe class setSize() method would assign the value '10' to the size global variable when it is passed to the method. But, it would print a 'Shoe size must be between 1 and 15' and NOT change the global variable when a value such as '437' was passed to the method. The private variable declarations build a wall around your data, and the 'set' methods are the gates that allow only 'good' information in. Your constructor that assigns values to global variables should use the 'set' methods so you DO NOT have to repeat the same checks in the constructor. The constructor with NO parameters can go ahead and directly set the default values into the global variables.Test Next For each class, create a main method that will declare, build and use an object of that class. So the Book.java main will declare, build and use a Book object, and the other two classes will do the same. Use a command line interface and ask the user to input a value for EACH global variable. Call a constructor or the set methods and insert that information into the object. Once the data is inserted use the object to call the toString method
and print the object to the console. You will be writing THREE main methods, one for each class. When you test, make sure your set methods DO NOT allow bad data into the object. Try to make it fail, see if you can sneak bad values into the variables.To insure you complete each class, use this checklist:_____ Three global variables (not the same type)_____ Two constructor methods_____ Three 'get' methods_____ Three 'set' methods_____ One 'toString' method_____ One main method that creates an object, assigns values, and prints the object
My issue with this is that I have all that is needed except for the user input which i am not sure where to put as well as where to call the set methods because i am not sure how to call those methods in my main. Any help would be greatly appreciated.
This is what I have so far for the first shoe class:
public class Shoe {
private String brand;
private String color;
private int size;
public Shoe() {
}
//every setter should have one check
public Shoe(int size, String brand, String color) {
this.color = color;
this.brand = brand;
this.size = size;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
if(size<1 || size>20){
System.out.println("Invalid");
}
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
if (brand.length()>20 || brand.length()<3)
System.out.println("Invalid Name");
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
if (color.length()>15 || color.length()<3)
System.out.println("Invalid Color");
}
#Override
public String toString(){
return "size is " + this.size + " \nbrand is " + this.brand + " \ncolor is "
+ this.color;
}
public static void main(String[] args){
Shoe s = new Shoe();
System.out.println(s.toString());
}
}

public static void main(String[] args){
Shoe s = new Shoe();
Scanner scan= new Scanner(System.in);
System.out.print("Enter show brand :");
s.setBrand(scan.next());
System.out.print("Enter show color :");
s.setBrand(scan.next());
System.out.print("Enter show Size :");
s.setBrand(scan.nextInt());
System.out.println(s.toString());
}

Related

Set & Get Methods

Java I student here!
I am having a hard time understanding how to make set and get methods. I am working on a question in my textbook Java Programming, 9th Edition independently and I am asked to do the following:
"Create a class named Sandwich. Data fields include a String for the main ingredient (such as tuna), a String for bread type (such as wheat), ad a double for price (such as 4.99). Include methods to get and set values for each of these fields."
It then asks me to do this:
"Create an application named TestSandwich that instantiates one Sandwich object and demonstrates the use of the set and get methods."
So for the first part, I made a .java file with the following code:
public class Sandwich {
private String ingredient;
private String bread;
private double price;
public Sandwich(String ing, String bre, double pri) {
ingredient = ing;
bread = bre;
price = pri;
}
public void setIngredient(String ing) {
this.ingredient = ing;
}
public String getIngredient() {
return ingredient;
}
public String getBread() {
return bread;
}
public Double getPrice() {
return price;
}
}
For the second part, I did the following:
import java.util.Scanner;
public class TestSandwich {
public static void main(String[] args) {
String Ingredient;
String Bread;
Double Price;
Scanner keyboard = new Scanner(System.in);
System.out.println("MAKE A SANDWICH");
System.out.println("Enter an ingredient: ");
Ingredient = keyboard.nextLine();
System.out.println("Enter bread: ");
Bread = keyboard.nextLine();
System.out.println("Enter a price");
Price = keyboard.nextDouble();
Sandwich obj = new Sandwich(Ingredient, Bread, Price);
System.out.println("The ingredient is " + obj.getIngredient());
System.out.println("The bread is " + obj.getBread());
System.out.println("The price is " + obj.getPrice());
}
}
I completed this and it works well, however I realize that I did not create any set methods. Could someone explain to me a better way to do this according to the directions? I'm sure that this way works but I would like to do it by the book and be able to understand it better. I'm not sure where to start with creating the set methods. Please let me know. Thanks so much!
PS: This is NOT homework, I'm just trying to understand this a little better.
-Mark
Here you create an object with these values
Sandwich obj = new Sandwich(Ingredient, Bread, Price);
Here you create an empty object and then set the values
Sandwich obj = new Sandwich();
obj.setIngredient(Ingredient);
obj.setBread(Bread);
obj.setPrice(Price);
Consider this code in your class named Sandwich :
public Sandwich(String ing, String bre, double pri) {
ingredient = ing;
bread = bre;
price = pri;
}
This is called a constructor, a special kind of method that is having the same name as that of the class. But it does not return a value. This constructor is accepting three parameters, of which two are strings and one is a double value. In the constructor body you are actually setting values that are passed to the constructor as parameters and so you can consider this as a setter method which is setting three values at once.
Now consider this code inside the same class :
public void setIngredient(String ing) {
this.ingredient = ing;
}
This method is a setter method which sets only one value, i.e. ingredient. You can create other setter methods as well like this giving any name you want to. For example setBread and setPrice method inside the Sandwich class as follows:
public setBread(String bre) {
bread = bre;
}
public setPrice(double pri) {
price = pri;
}
You can either use the constructor to set the values or the "setter methods"(It is just a normal method that is used to accept and set the values). You can use a single method to set all the values in one go, which is what the constructor is doing or use individual methods to set each values like the setter methods we have defined.
If you are using a single method to set all values at once(in this case the constructor) then during the time of instantiating Sandwich class you need to pass all the values at once to the constructor like you did this :
Sandwich obj = new Sandwich(Ingredient, Bread, Price);
If you do not pass three variables to the constructor at once in the correct order, then compilation error will occur. As you already have a constructor setting three values, the other setter methods are not of great use except when you need to change the values afterwards. I hope this helps.
Simple go like:
System.out.println("Enter another price");
double newPrice = keyboard.nextDouble();
obj.setPrice(newPrice);
and print your obj before / after that call (and of course: #Overwrite toString() on that class to get meaningful output).

How program passes values to method ranking()

Hi all,
I would like to ask you for help to understand logic of this program specially some parts that I am probably stack in.
1.Method ranking(). It doesn´t accept any parametr but returns result from parametrs "won" and "tied". OK. But when we call this method like this
System.out.println(adelaideCrows.getName()+": result:
"+**adelaideCrows.ranking()**);
how the program knows values of "won" and "tied" for this adealideCrows team? I know that OOP is about passing objects respective references to objects. So does it work so that when we firstly call method adelaideCrows.matchResult(ohioFotlball, 1,0); then adelaideCrows is the reference to method matchResult passing there parametres in brackets and then they are stored in memory under reference of adelaideCrows? so when we next call the same method with another reference melbournSoccer.matchResult(newyorkSoccer,6,4); then parametres "won" and "tied" have their own values passed in brackets under reference melbournSoccer? So after calling method ranking() with reference e.g. adelaideCrows program knows that under this reference there are already stored values of parametres "won" and "tied" and method then returns correct values. Right?
2.And also here System.out.println(melbournSoccer.compareTo(newyorkSoccer)); Does the logic is the same? melbournSoccer reference is connected in method public int compareTo(Team<T> team) to this.ranking() but reference newyorkSoccer is connected to team.ranking()? So calling this.ranking() invokes values stored in memory of reference melbournSoccer and so on?
Thank A LOT.
Here is the code for Main class:
public class Main
{
public static void main(String[] args) {
SoccerPlayer soccerPlayer = new SoccerPlayer("joe");
BaseballPlayer baseballPlayer = new BaseballPlayer("pat");
FootballPlayer footballPlayer = new FootballPlayer("backham");
Team<FootballPlayer> adelaideCrows = new Team<>("Adelaide Crows
footbal");
Team<SoccerPlayer> melbournSoccer = new Team<>("Melbourn soccer");
Team<BaseballPlayer> jerseeBaseball = new Team<>("Jersee
Baseball");
melbournSoccer.addPlayer(soccerPlayer);
jerseeBaseball.addPlayer(baseballPlayer);
adelaideCrows.matchResult(ohioFotlball, 1,0);
melbournSoccer.matchResult(newyorkSoccer,6,4);
System.out.println("Ranking...");
System.out.println(adelaideCrows.getName()+": result:
"+adelaideCrows.ranking());
System.out.println(melbournSoccer.getName()+": result:
"+melbournSoccer.ranking());
System.out.println(jerseeBaseball.getName()+": result:
"+jerseeBaseball.ranking());
System.out.println(melbournSoccer.compareTo(newyorkSoccer));
System.out.println(adelaideCrows.compareTo(ohioFotlball));
Player class here from which another three classes FotballPlayer, SoccerrPlayer and BaseballPlayer inherits.
public abstract class Player{
private String name;
public Player(String name){
this.name = name;
}
public String getName(){
return name;
}
}
And here is Team class.
import java.util.ArrayList;
public class Team<T extends Player> implements Comparable<Team<T>>{
private String name;
int played = 0;
int lost = 0;
int won = 0;
int tied = 0;
private ArrayList<T> members = new ArrayList<>();
public Team(String name){
this.name = name;
}
public String getName(){
return name;
}
public boolean addPlayer(T player){
if(members.contains(player)){
System.out.println(player.getName()+" is already on this
team.");
return false;
}else{
members.add(player);
System.out.println(player.getName()+" has been added to team
"+this.name);
return true;
}
}
public int numPlayers(){
return this.members.size();
}
public void matchResult(Team<T> oponent, int ourScore, int theirScore){
if(ourScore > theirScore){
won++;
}else if(ourScore == theirScore){
tied++;
}else{
lost++;
}
played++;
if(oponent != null){
oponent.matchResult(null, theirScore, ourScore);
}
}
public int ranking(){
return (won * 2) + tied;
}
#Override
public int compareTo(Team<T> team){
if(this.ranking() > team.ranking()){
return -1;
} else if(this.ranking() < team.ranking()){
return 1;
}
else{
return 0;
}
}
}
Here are some clarifications to the questions.
Question 1:
Method ranking(). It doesn´t accept any parametr but returns result
from parametrs "won" and "tied". OK. But when we call this method like
this:
System.out.println(adelaideCrows.getName() + ": result: " + **adelaideCrows.ranking()**);
how the program knows values of "won" and "tied" for this
adealideCrows team? ...
Answer 1:
Consider this statement in the Main class: adelaideCrows.matchResult(ohioFotlball, 1, 0);. When this statement executes:
The adelaideCrows object gets affected. In the matchResult method the
instance variables won and tied are changed based on the method input
parameters (1 and 0, in this case).
When the statement adelaideCrows.ranking() is executed, the ranking() method uses the adelaideCrows's object instance variables won and tied (which were set earlier) to calculate the ranking ((won * 2) + tied) and return the value.
NOTES: See this article (my answer) on StackOverflow to get an idea about a Java class, an object, a reference, and class's attributes and behavior: Object References in Java.
Question 2:
And also here
System.out.println(melbournSoccer.compareTo(newyorkSoccer)); Does the
logic is the same? melbournSoccer reference is connected in method
public int compareTo(Team<T> team) to this.ranking() but reference
newyorkSoccer is connected to team.ranking()? So calling
this.ranking() invokes values stored in memory of reference
melbournSoccer and so on?
Answer 2:
Consider the statement: System.out.println(melbournSoccer.compareTo(newyorkSoccer));
Q). melbournSoccer reference is connected in method public int compareTo(Team<T> team) to this.ranking()
A). The keyword this refers to the current object - here it is melbournSoccer. this.ranking method gets the ranking for the melbournSoccer.
Q). Reference newyorkSoccer is connected to team.ranking()?
A). The method parameter compareTo() takes a Team as input - here it is a newyorkSoccer team object.
Q). So calling this.ranking() invokes values stored in memory of reference melbournSoccer and so on?
A). YES.
NOTES: Here is a link to Oracle's Java tutorials topic Using the this Keyword.
I try to answer your first question: The variables „won“ and „tied“ are instance variables. That means every time you create an object of your team class, the object gets its own „won“ and „tied“ variable to save data in it. You can access them with the name of the unique object (in your case the team name as example „adelaideCrows.won“ without the quotes). To answer the question about the „matchResult“ function: The function is related to your object again because you are not using „static“ declaration in front of the method name. So without static every instance of your class gets their own method so if you are passing parameters to that function they are passed into the objects function. If you want to save them you have to create a class variable (which is made with „static int“ as example) or a instance variable in order to save the data as long as the object exists, otherwise the data will get passed to the function and will be lost after the function execution is finished.

Is this proper encapsulation for this Java code? I am confused

Does this Java code involving a Book class use proper encapsulation? I feel it can be a lot simpler if I omit some methods but we're required to every method that is in there [especially setters and getters].
Here's the first class:
public class Book
{
private String title;
private double price;
private final double SALES_TAX=0.075;
public String getTitle()
{
return title;
}
public void setTitle(String title)
{
this.title=title;
}
public double getPrice()
{
return price;
}
public void setPrice(double price)
{
this.price=price;
}
public double getSalesTax()
{
return SALES_TAX;
}
public double increasePrice(double incresePrice)
{
return incresePrice;
}
public double calculateSales(double sales)
{
return sales;
}
}
And the second class:
public class BookDriver
{
public static void main(String[] args)
{
Scanner keyboard=new Scanner(System.in);
Book bookOne=new Book();
Book bookTwo=new Book();
bookOne.setTitle("Life of Pi");
System.out.print("Enter number to buy of "+bookOne.getTitle()+": ");
bookOne.setPrice(13.50*bookOne.calculateSales(keyboard.nextDouble()));
bookOne.setPrice((bookOne.getPrice()*bookOne.getSalesTax())+bookOne.getPrice());
System.out.print("Cost for "+bookOne.getTitle()+" $");
System.out.printf("%.2f"+"\n",bookOne.getPrice());
bookTwo.setTitle("Harry Potter: The Goblet Of Fire");
System.out.print("Enter number to buy of "+bookTwo.getTitle()+": ");
bookTwo.setPrice(22.00*bookTwo.calculateSales(keyboard.nextDouble()));
bookTwo.setPrice((bookTwo.getPrice()*bookTwo.getSalesTax())+bookTwo.getPrice());
System.out.print("Cost for "+bookTwo.getTitle()+" $");
System.out.printf("%.2f"+"\n",bookTwo.getPrice());
System.out.print("Enter percent increase of "+bookOne.getTitle()+": ");
bookOne.setPrice((bookOne.getPrice()*bookOne.increasePrice(keyboard.nextDouble()))+bookOne.getPrice());
System.out.printf("Cost of "+bookOne.getTitle()+": $"+"%.2f"+"\n",bookOne.getPrice());
System.out.print("Enter percent increase of "+bookTwo.getTitle()+": ");
bookTwo.setPrice((bookTwo.getPrice()*bookTwo.increasePrice(keyboard.nextDouble()))+bookTwo.getPrice());
System.out.printf("Cost of "+bookTwo.getTitle()+": $"+"%.2f"+"\n",bookTwo.getPrice());
keyboard.close();
}
}
I know that this is a lot so I'm not really expecting much in terms of a response but anything would help. Thanks!!
Let's look at the point of encapsulation. You have a Class which consists of properties and methods. The idea behind encapsulation is, you want the methods in your class to be the only way to change the value (state) of the properties. Think of it like this: if some other code in the program wants to change the value of one of the properties, it cannot do it itself, it must ask a method on the class they reside in to do it. That way, you control access to the properties.
The way this is implemented is with getter and setter methods of which you have created a few. A getter method returns the value of the property and a setter method changes it to a new value.
1.
Your getter and setter methods up to increasePrice() are good. You are preventing access to the properties other than from the methods on your class.
2.
increasePrice() only spits out what was passed into it. It doesn't change the value of any of the properties and thus has no purpose. If you want to be able to increase the price you can change the method like so:
public void increasePrice(double amountOfPriceIncrease) {
price += amountOfPriceIncrease;
/*
price += amountOfPriceIncrease is the same as
price = price + amountOfPriceIncrease
*/
}
3.
This line is a bit troubling. For starters, increasePrice() doesn't do anything other than spit out what was put into it and secondly, there is a lot going on in the one line that makes it complicated and hard to follow.
bookTwo.setPrice((bookTwo.getPrice()*bookTwo.increasePrice(keyboard.nextDouble()))+bookTwo.getPrice());
You dont necessarily need all the setters. For example, its probably reasonable to assume that a book has a title, and it doesnt change. So you can make it final, omit the setter, and pass it into the constructor.
Also, think about how you're modelling things. Is sales tax a property of a book? I'd say not.
Because all the required variables title, price for class Book are set to private, and that access can only be used using get..(), and changing it if possible can only be used using set..(some variable) or an instance method affecting one of the fields, it demonstrates proper encapsulation, so all getting and setting are regulated.
However, I spotted several mistakes in BookDriver, namely with the improper usage of Book fields.
The price should change only through setPrice or increasePrice.
You should also implement getPriceAfterTax to determine after-tax prices for a book.
The total cost of the books you bought should not involve any setPrice.
There is a mistake with public double calculateSales(double sales). It does nothing but returns back sales. The calculateSales should calculate the total cost of the book(s) being bought, using one int variable, and you also resorted in changing the price of these books, which shouldn't happen. It is the reason why you wrote messy code, as in the excerpt
bookTwo.setPrice(22.00*bookTwo.calculateSales(keyboard.nextDouble()));
bookTwo.setPrice((bookTwo.getPrice()*bookTwo.getSalesTax())+bookTwo.getPrice());
This avoids the potential case of changing the values of that BOOK object to unexpected or unusual values and value combinations.
Additionally, SALES_TAX can be made into a public static final double instead, as it is assumed to never change, and you can simply obtain SALE_TAX without requiring getSalesTax().
The last two methods do not make much sense. You simply return what you put in. Do it this way:
public double increasePrice(double increase)
{
price *= increase;
}
public double calculateSales(double sales)
{
//return {your formula}
}

Java Constructor Chaining [duplicate]

This question already has answers here:
How to avoid constructor code redundancy in Java?
(4 answers)
Closed 9 years ago.
Hi I am just learning about constructor chaining in Java and had some questions...
First of all could someone please explain when I would ever need to use this? Off the top of my head I seriously cannot think of a situation.
In this example, within the constructor with no arguments I call another constructor. How do I access this new "James Bond" object for future use?
import java.util.*;
class Employee
{
private String name;
private double salary;
public Employee()
{
this("James Bond", 34000);
}
public Employee(String n, double s)
{
name = n;
salary = s;
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public static void main(String[] args)
{
Employee a = new Employee();
}
}
Actually I believe the most common use of chained Constructors is when the Constructor does more than just setting the member variables.
static int numOfExamples = 0;
public Example(String name, int num)
{
this.name = name;
this.num = num;
numOfExamples++;
System.out.println("Constructor called.");
Log.info("Constructor called");
}
public Example()
{
this("James Bond",3);
}
That way we don't have to write the code for logging and incrementing the static variable twice, instead just chaining the constructors.
Chaining constructors like this is useful to avoid repeating code, and helps with maintainability:
public MyClass(int x, double y, String z) {
// set fields
}
public MyClass() { // i.e. a constructor that uses default values
this(42, 4.2, "hello world"); // x is 42, y is 4.2, and z is "hello world"
}
If we didn't use the chain, and wanted to change how the x argument (for example) is processed when constructing an instance of MyClass, we would have to change code in both constructors. With the chain, we only need to change one of them.
1) As others have said, it's for code maintenance, basically the idea is that you only write one piece of code once, which means you only need to edit it once, there is no risk of overlooking something when editing your methods and the two accidentally becoming different.
Personally I tend to use this differently than in your example. Like so:
Employee() {
setupStuff();
}
Employee(String name) {
this();
this.setName(name);
}
This is a nice way of doing things, because potentially your setter can be way more complicated than just setting a member in the class. So basically what this does is puts calling the empty constructor and then a setter into a single method, making it much easier for anyone using the class.
2) The constructor being called doesnt't create a different object at all, it creates this object. Note that there is no new keyword used. Basically you're just calling a different method inside your constructor, except that method happens to also be a constructor.
Every time you want to allow constructing an object wit default values, and also want to allow creating the same object with non-default values. Let's imagine a DateTime class. You could want to initialize it with the current time by default, or with a specific time. Imagine a Car class. You could imagine constructing it with Black as the default color, or with a specific color. This kind of situation is very common. See java.util.ArrayList or java.util.Locale, for concrete examples.
It's stored in the name field. So you access it, from the object itself, with this.name (this being optional, just as in the getName() method).
How do I access this new "James Bond" object for future use?
Because you saved the values of name and salary as fields of your employee class, then inside the employee class you can use those fields, and outside your employee class you can use the getter/setter methos of your employee class

accessing an object array item, java

I have created a number objects using an array statement, and I can println the values passed within the class as it is created, but when I try and retrieve element values from outside of the class (monopolygame class) it doesn't recognise the refrence - how can I refrence this correctly?
public class monopolygame {
public static void main(String[] args) {
//set up array of 18 objects
property properties[] = new property[18];
//create 18 property objects and populate array
properties[0] = new property("a","available",400,500);//create property
properties[1] = new property("b","available",400,500);//create property
properties[2] = new property("c","available",200,300);//create property
properties[3] = new property("d","available",100,180);//create property
properties[4] = new property("e","available",400,700);//create property
}
}
property class...
public class property
{
public static void main(String[] args)
{
}
//constructor
public property(String propertyname, String owner, double price, double rent)
{
System.out.println("Property info for " + propertyname
+ " - Rent : £" + rent
+ "Price : £" + price
+ "owned by :" + owner);
}
}
I am using this kind of reference in the monopoly class to try and access the data
if (properties[2].propertyname == "available")
{
System.out.println("avaialble");
}
else
{
System.out.println("sold");
}
Thanks
You have to declare those attributes in the "property" class first:
class property {
String propertyname;
String owner;
int price;
int rent;
public Property( String somename, String owner, int price, int rent ) {
this.propertyname = somename;
this.owner = owner;
this.price = price;
this.rent = rent;
// and so on
}
}
The array you're using is local to the main method.
To access it outside of the scope of the main method you should declared either as a class attribute or as an instance attribute like this:
public class monopolygame {
public static property properties[];
public static void main(String[] args) {
//set up array of 18 objects
properties = new property[18];
.....
That way you can access the array in other method like this:
public void setUp() {
for( property p : properties ) {
System.out.println( p.propertyname ); // etc.
Then your code:
if (properties[2].propertyname == "available")
Will work.
BTW in Java all the class name start with uppercase by convention , so it should be:
Property instead of property and MonopolyGame instead of monopolygame
Given the code you've supplied us with, it doesn't look like you're actually storing the values passed in to your property constructor. Here's something a bit closer to what your property class should look like:
public class property
{
private String propertyname;
private String owner;
private double price;
private double rent;
public String getPropertyName()
{
return propertyname;
}
public void setPropertyName(string newName)
{
propertyname = newName;
}
// more getter/setter methods here
public property(String propertyname, String owner, double price, double rent)//constructor
{
this.propertyname = propertyname;
this.owner = owner;
this.price = price;
this.rent = rent;
System.out.println("Property info for " + propertyname + " - Rent : £" + rent + "Price : £" + price + "owned by :" + owner);
}
}
A few remarks:
In Java, string comparisons need to
be done with the equals() method, not
==. See this link for an explanation of why using == might work in some cases, but that shouldn't be expected.
It is a convention to capitalize class names -> Property rather than
property.
Avoid mixing and matching bracket positioning. Use at the end of the same line or at the beginning of the next line, but not both. The most frequent use is at the end of the same line.
You need to add a public method to access the internal of monopolygame class. That is the main aspect of your question.
But in general your code is not the correct way of doing things in Java. Class names must be capitalized, for example. An empty main in the second class is pointless. You need to learn more about the basic Java stuff, I answer your question because I think you could learn a lot here, but I suggest you to check the trails covering the basics on The Java Tutorial.
Two problems are immediately obvious:
You're not storing the arguments passed to the property constructor in fields within that class.
Once you do that, you're trying to compare strings by reference (or by identity, via ==) rather than by value (via String#equals(String)). Unless you've interned the strings via String#intern(), two different String instances with the same character content will not compare as equal via ==. That comparison only looks at the memory addresses of the object references, which will most likely point to two different String instances, each with a different address.
As this question looks like a homework assignment, please tag it as such.

Categories