Development of monopoly game - java

I seem to have a problem with a subtask. It's in danish so I put in the translated version of it:
Create a class Field, that is representing the fields of a monopoly game. Initially, Field can contain these encapsulated variables:
String name - short name of the field
int number - a number in the range[1..40]
Both variables must be initialized in a constructor, and there must only be getters, as they never will be changed after creation.
Moreover, there should be a method with the signature public String toString(), so it's easy to print what Field a player has landed on.
At first it's allowed to just call the fields Field1, Field2...
My Field class look like this:
public class Field {
String name;
int number;
public Field(String name, int number) {
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
public int getNumber() {
return number;
}
}
In my main method I wanted to test this. So I wrote the following:
Field[] board = new Field[40]; // a board containing 40 fields
for (int i = 0; i < board.length; i++) {
board[i] = new Field("Field" + (i + 1), i + 1);
}
System.out.println("Board: " + Arrays.toString(board));
In my console I get this:
Board: [test.Field#2a139a55, test.Field#15db9742, test.Field#6d06d69c,......]
And I want this:
Board: [Field1, Field2, Field3,......]

Override Field's toString() to return the name, i.e.
public String toString() {
return name;
}
What you get (e.g. test.Field#2a139a55) is the default implementation of toString() which can be found in Object:
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}

You missed the
Moreover, there should be a method with the signatur public String toString(),
part of your task.

Are you able to use java8? Then I would suggest this:
Field[] board = new Field[40]; // a board containing 40 fields
for(int i = 0; i < board.length; i++){
board[i] = new Field("Field" + (i + 1), i + 1);
}
String commaSeparatedName =
Arrays.stream(board) // all items as stream
.map(Field::getName) // for each take its name
.collect(Collectors.joining(", "); // join names with a comma
System.out.println("Board: [" + commaSeparatedNames +"]");

Related

Referencing the array variables in the Reference class, sorting it using another method, and invoking the sorted values in the case statement

I am trying to call the array variables in the reference class, try to sort them using a user-defined method and call the method onto the case statement that will be invoked if the user chooses a particular number. I wanted to provide the user the option what attribute of a student will be sorted (i.e. name, course...) and show the sorted one dimensional array called in the case statements and invoked through the main method.
Here's the variables in the Reference class:
class RecordReference {
private int idNumber;
private String firstName = "";
private String middleName = "";
private String lastName = "";
private int age;
private String yearLevel;
private String course = "";
private double gwa;
public RecordReference(int i, String f, String m, String l, int a, String y, String c, double g) {
idNumber = i;
firstName = f;
middleName = m;
lastName = l;
age = a;
yearLevel = y;
course = c;
gwa = g;
}
public int getIdNumber() {
return idNumber;
}
public String getFirstName() {
return firstName;
}
public String getMiddleName() {
return middleName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public String getYearLevel() {
return yearLevel;
}
public String getCourse() {
return course;
}
public double getGwa() {
return gwa;
}
public void setIdNumber(int idnumber) {
idNumber = idnumber;
}
public void setFirstName(String fName) {
firstName = fName;
}
public void setMiddleName(String mName) {
middleName= mName;
}
public void setLastNameName(String lName) {
lastName= lName;
}
public void setAge(int a) {
age = a;
}
public void setYearLevel(String yLevel) {
yearLevel = yLevel;
}
public void setCourse(String c) {
course = c;
}
public void setGwa(int gwa) {
gwa = gwa;
}
public String toString() {
return String.valueOf(System.out.printf("%-15s%-15s%-15d%-15d%n",
firstName, course , yearLevel ,gwa));
}
} // end of class
And I am trying to call it in this sort method, but I don't know how to reference it.
public static void sortFirstNameArray(String[] f){
for (int i = 0; i < f.length - 1; i++) {
for (int j = i + 1; j < f.length; j++) {
if (f[i].compareToIgnoreCase(f[j]) > 0) {
String temp = f[i];
f[i] = f[j];
f[j] = temp;
}
}
}
}
After the sorting is successfully done, I'll call it in a switch case statements that will be invoked once the user chooses a particular number. This part has 5 case statements (Name, Age, Course, General Weighted Average and the option to sort it all - I plan to add more student attributes if this works)
(I don't know if I should store this in another method and call it in the main method or just put it in the main method like that)
public RecordReference Process(RecordReference[] f, RecordReference[] a) {
// for loop?
for (int x = 0; x < f.length; x++) {
switch (choice) {
case 1:
System.out.println("Sorted array of first name: ");
sortFirstNameArray(f[x].getFirstName());
System.out.printf("%-15s%n", Arrays.toString(f));
break;
case 2:
System.out.println("Sorted array of age: ");
// invokes the age method
sortAgeArray(a[x].getAge());
System.out.printf("%-15s%n", Arrays.toString(a));
break;
}
}
}
If it is in another method, what param do I include when I call it in the main method?
I tried this but it doesn't work, I don't know what to do
System.out.print("Please choose what student attribute you want to
sort :");
choice = keyboard.nextInt();
// calling the process method here, but I receive syntax error
Process(f,a); // Here, I want to pass the sorted values back into the array but I get an error.
If you can help me out that would be great. Thank you in advance.
I'm just a first year student and I am eager to learn in solving this error.
It's good to see that you have attempted the problem yourself and corrected your question to make it clearer, because of that I am willing to help out.
I have tried to keep the solution to the problem as close to your solution as possible, so that you are able to understand it. There may be better ways of solving this problem but that is not the focus here.
First of all, let's create a class named BubbleSorter that will hold methods for sorting:
public class BubbleSorter
{
//Explicitly provide an empty constructor for good practice.
public BubbleSorter(){}
//Method that accepts a variable of type RecordReference[], sorts the
//Array based on the firstName variable within each RecordReference
//and returns a sorted RecordReference[].
public RecordReference[] SortByFirstName(RecordReference[] recordReferencesList)
{
for (int i = 0; i < recordReferencesList.length - 1; i++) {
for (int j = i + 1; j < recordReferencesList.length; j++) {
if (recordReferencesList[i].getFirstName().compareToIgnoreCase
(recordReferencesList[j].getFirstName()) > 0) {
RecordReference temp = recordReferencesList[i];
recordReferencesList[i] = recordReferencesList[j];
recordReferencesList[j] = temp;
}
}
}
return recordReferencesList;
}
}
That gives us a class that we can instantiate, where methods can be added to be used for sorting. I have added one of those methods which takes a RecordReference[] as a parameter and sorts the RecordReference[] based on the firstName class variable within each RecordReference. You will need to add more of your own methods for sorting other class variables.
Now for the main class:
class Main {
public static void main(String[] args) {
//Get a mock array from the GetMockArray() function.
RecordReference[] refArray = GetMockArray();
//Instantiate an instance of BubbleSorter.
BubbleSorter sorter = new BubbleSorter();
//Invoke the SortByFirstName method contained within the BubbleSorter
//and store the sorted array in a variable of type RecordReference[] named
//sortedResult.
RecordReference[] sortedResult = sorter.SortByFirstName(refArray);
//Print out the results in the sorted array to check if they are in the correct
//order.
//This for loop is not required and is just so that we can see within the
//console what order the objects in the sortedResult are in.
for(int i = 0; i < sortedResult.length; i++)
{
System.out.println(sortedResult[i].getFirstName());
}
}
public static RecordReference[] GetMockArray()
{
//Instantiate a few RecordReferences with a different parameter for
//the firstName in each reference.
RecordReference ref1 = new RecordReference(0, "Ada", "Test", "Test", 22, "First",
"Computer Science", 1.0f);
RecordReference ref2 = new RecordReference(0, "Bob", "Test", "Test", 22, "First",
"Computer Science", 1.0f);
RecordReference ref3 = new RecordReference(0, "David", "Test", "Test", 22,
"First", "Computer Science", 1.0f);
//Create a variable of type RecordReference[] and add the RecordReferences
//Instantiated above in the wrong order alphabetically (Based on their firstName)
//class variables.
RecordReference[] refArray = {
ref2, ref3, ref1
};
return refArray;
}
}
In the main class I have provided verbose comments to explain exactly what is happening. One thing I would like to point out is that I have added a method named GetMockArray(). This is just in place to provide a RecordReference[] for testing and you probably want to do that somewhere else of your choosing.
If anything is not clear or you need some more assistance then just comment on this answer and I will try to help you further.
Thanks.

Writing a java program containing two classes

I've attempted to write a Java program containing two classes: Dog and a driver class Kennel.
A dog consists of the following information:
An integer age.
A string name. If the given name contains non-alphabetic characters, initialize to Wolfy.
A string bark representing the vocalization the dog makes when they ‘speak’.
A boolean representing hair length; true indicates short hair.
A float weight representing the dog’s weight (in pounds).
An enumeration representing the type of tail (LONG, SHORT, NONE).
A dog has the following methods:
A default constructor.
A constructor that takes a name as argument.
A method private boolean validName(String) that returns true / false whether the given name contains non-alphabetic characters.
humanAge that computes and returns the age of the dog in “human years.”
speak that returns the dog’s bark...
I am having trouble trying to figure out how to do the method for validName. Can anyone point me in the right direction? Also do I do the method for speak the same way or no? The code is attached below.
package lab101;
public class Dog
{
public enum TailType
{
LONG, SHORT, NONE
}
private int age;
private float weight;
private String name;
private String bark;
private boolean hairLength;
private TailType tail;
//Default Constructor--> initializes an object (called once)every constructor
//must initialize all the classes attributes!!
public Dog()
{
age = 0;
weight = 0;
name = "";
bark = "";
hairLength = false;
tail = TailType.NONE;
}
//Overloaded constructor (must have an argument)
public Dog(String theName)
{
age = 0;
weight = 0;
name = theName;
bark = "";
hairLength = false;
tail = TailType.NONE;
}
//If the name contains non-alphabetic characters
private boolean validName(String str)
{
str = str.toLowerCase();
if (str.length() <= 0)
{
}
return false;
}
//Computes the dog's age in human years.
public int humanAge()
{
int theAge = 7 * age;
return theAge;
}
//Returns the value of bark if true
public String(speak)
{
return bark;
}
//Method: <privacy: (private, public)> <return-type (data type or void)> <methodName>(<argument>){
// <body>
// return
// }
public String toString()
{
String str = "";
str += "Name: " + name;
str += "Weight: " + weight;
str += "Bark: " + bark;
str += "Hair Length: " + hairLength;
str += "Tail: " + tail;
str += "Age: " + age;
return str;
}
}
I am having trouble trying to figure out how to do the method for validName.
Assuming your validName method checks whether a valid name was given by checking whether there exist only alphabets:
//Return true if name is valid
private boolean validName(String str)
{
if(str == null || str.length() == 0)
return false;
return str.toLowerCase().matches("[a-z]+"); //Name only has a-z(A-Z)
}
Also do I do the method for speak the same way or no?
Well, I do not know what do you mean by "the same way". But your speak method is incorrect.
According to your description, it should be:
public String speak(){
return bark;
}
Something you did not ask, but could be done better:
You are implementing your class constructor twice. You could have invoke the constructor like this:
public Dog(){
this(""); //invoke Dog(String)
}
public Dog(String theName){
age = 0;
weight = 0;
name = theName;
bark = "";
hairLength = false;
tail = TailType.NONE;
}
The effect of the above is the same as what you did, but this is preferred.
you can also do this if you don't know regular expression:
private boolean validName(String str)
{ char[] letters = str.toUpperCase().toCharArray();
for(int i = 0 ; i < letters.length; i++){
int oneLetter = (int) letters[i];
if( !(oneLetter > 64 && oneLetter < 91)) // letters as ASCII for A-Z
return false; // if anyone is not A-Z then return false
}
return true; // if every letter is valid then return true
}

Array from a seperate object not printing correctly

I have a program that currently I'm trying to create a player with customizable integers. I use this object:
public class Player {
public String player = null;
private int Strength=0;
private int Defense=0;
private int Magic=0;
private int Resistance=0;
private int Skill=0;
private int Luck=0;
public Player(String name, int int1, int int2, int int3, int int4, int int5, int int6) {
this.player = name;
this.Strength = int1;
this.Defense = int2;
this.Magic = int3;
this.Resistance = int4;
this.Skill = int5;
this.Luck = int6;
}
}
I use this main class to run it, and set the integer and string values.
public class Main {
public static void main(String[] args) {
Player[] playerList = new Player[] {new Player("Player1", 3, 3, 2, 1, 1, 3),new Player("Player2", 1, 1, 1, 1, 1, 1)};
}
}
However, whenever I attempt to print this, it prints this:Player#659e0bfd
I looked through similar questions, but I am not sure where to put the #Override in my program, and if I need to do something different since I have multiple integers, and a string. I only want the string to print out. (Also, is there a way to print out just one part of the playerList, ie. the first section "Player1")
In the Player class you need to put the override.
Someting like:
public class Player {
// fields here
#Override
public String toString() {
return Strength + " " + Defense; // plus all the fields here
}
}
Regarding your other question: yes, you can, but since all the fields are private, you need to create getters for those fields. Then you can do:
public class Player {
private int defense;
private String name;
public Player(int defense, String name) {
this.defense = defense;
this.name = name;
}
public int getDefense() {
return this.defense;
}
public String getName() {
return this.name;
}
}
Player player = new Player(9000);
System.out.println(player.getName + " has defense + " player.getDefense());
Also, it's a good idea to stick to Java conventions. This means that variables are written with a lower case, like strength instead of Strength.
What you are seeing is the output of the toString method in the Object class, which your Player class implicitly extends. If you wish for it to output something else, you must override the toString() method in your Player class.
For instance, add something like this:
#Override
public String toString() {
return "Player(Strength: " + Strength + ", Defense: " + Defense + ")";
}
So basically i assume u use the System.out.println(); method to display ur Object right? You defined your own class and objects. You have to define your own print method, which you have to override. The method is called
#Override
public String toString(){ return this.Strength + " " + this....);
This method will be called automatically if you insert your object in your System.outprintln();

A store that sells one type of item

Okay, I don't know If I wrote a code correctly please check. So I created software for a store that sells one type of item. And each instance of my class should be an item of merchandise my store sells.
For example if my store sells neckties, I would design a necktie class:
class Necktie { …
My class must have five instance variables, including at least one of type integer, at least one of type String and one called price which must be double. Also it should have a toString method that accepts no parameters and returns a description of the item. It should have a constructor. The constructor can take however many parameters you choose, but it must set all instance variables.
• It should contain an accessor method for each instance variable.
• It should contain no unnecessary instance variables. Any information that does not need to be stored in an instance of your class should be stored as local variables.
Here is the code below. (incomplete, because I am kinda stuck..Please check if I did it correctly. If not, then please correct me.)
public class Pets {
public static void main(String[] args) {
System.out.print (Pets.toString()); //toString
}
String color, pattern;
int age, size;
double price;
Pets (String color, String pattern, int age, int size, double price){
this.color = color;
this.pattern = pattern;
age = age;
size = size;
price = price;
}
public String toString(){ //I don't get this part..
String description;
description = "red";
return description;
}
public String getColor(){
return color;
}
public String getPattern(){
return pattern;
}
public int age(){
return age;
}
public int size(){
return size;
}
public double price(){
return price;
}
}
Where you've written
age = age;
size = size;
price = price;
This is actually not setting the instance variable. You should carry on writing
this.age = age
// etc...
When you write this it tells Java that you're referring to the instance variable, not the local variable
When the main method is called, Java doesn't create an instance of Pets for you. But the rest of your code works on a Pets object, so you'll need to create one somewhere in your main. Thus, instead of:
public static void main(String[] args) {
System.out.print (Pets.toString()); //toString
}
it will be something like
public static void main(String[] args) {
Pets pet = new Pets(........); // creates an instance; you'll need to supply
// the arguments
System.out.print (pet.toString()); // calls toString on this instance
}
That will get past the "cannot make a static reference" error, but there are other problems as described in other answers.
Your main method tries to call a static method toString(), but your toString() method is not static (as it shouldn't be).
For testing purposes, your main method should look like this:
public static void main(String[] args) {
Pets pet = new Pets("red", "plain", 1, 2, 10.25);
System.out.println(pet.toString());
}
In your constructor:
Pets (String color, String pattern, int age, int size, double price){
this.color = color;
this.pattern = pattern;
this.age = age;
this.size = size;
this.price = price;
}
Your toString() method has a typo in the name. It should probably return a description of the attributes of the instance (not an actual description field). For example:
public String toString() {
StringBuilder description = new StringBuilder("Color: ")
.append(color)
.append(", Pattern: ")
.append(pattern)
.append(", Age: ")
.append(age)
.append(", Size: ")
.append(size)
.append(", Price: ")
.append(price);
return description.toString();
}
Your getters should start with get:
public int getAge(){
return age;
}
public int getSize(){
return size;
}
public double getPrice(){
return price;
}
Edit
At the OPs request:
An alternative toString() method which uses String concatenation (bad) and no special formatting:
public String toString() {
return "Color: " + color + ", Pattern: " + pattern + ", Age: " + age + ", Size: " + size + ", Price: " + price;
}

Array help needed - Coding errors

I need to implement a method that takes an array called applicants, and two instances from a seperate class called Person, and prints out names of those applicants whose age is between 22 and 30 inclusive. The class Person has methods getName() and getAge() that return the name and the age of the applicant. In other words, the class Person is declared as follows:
public class Person{
public String getName(String name) {
return name;
}
public int getAge(int age){
return age;
}
}
Here is my main method:
public class Applicants
{
public static void main(String args[]){
String [] name = new String[8];
name[0] = "Student A";
name[1] = "Student B";
name[2] = "Student C";
name[3] = "Student D";
name[4] = "Student E";
name[5] = "Student F";
name[6] = "Student G";
name[7] = "Student H";
int [] age = new int[8];
age[0] = 21;
age[1] = 28;
age[2] = 16;
age[3] = 23;
age[4] = 22;
age[5] = 28;
age[6] = 22;
age[7] = 21;
}
public static void printSelection(Person applicants[]) {
for (int i = 0; i < applicants.length; i++)
if (22 <= applicants[i].getAge() && applicants[i].getAge() <= 30)
System.out.println(applicants[i].getName());
}
}
I know I have not prepared an array called applicants (yet). I am not sure how I can basically take these two arrays called names and ages and make the one array called applicants?
Or do I just convert the array names to applicants?
This is a class session so please forgive my errors. I just need to learn how a professional would do this sort of thing so that I may learn from it and move on.
The final output is required to print out the applicant name and age that is between 22 and 30. The getName and getAge must be called from a separate class as shown below.
Firstly, there is no need for two arrays. You can simply create object instances of type Person.
public class Person{
public String getName(String name) {
// Why would the user pass a value they want returned right back to them?
return name;
}
public int getAge(int age){
// Same here as well. This needs to be addressed!
return age;
}
}
Firstly this code will not work. There is no field name and field age in the class. That is your first problem to solve. You also need to make a constructor for this class, that takes name and age as a parameter, and binds them to the fields you have defined. ie:
public Person(int age, String name)
{
this.age = age;
this.name = name;
}
The next step would be to add the values to a person object, then adding that person object to a collection(like an array, or arraylist). In your main method, you might have something like..
Person[] applicants = new Person[8];
Now you should add new instances of the Person object to this collection, with the relevant data.
Pass this array to your function and you will print out the selected values.

Categories

Resources