START OF INSTRUCTIONS
If there is a game piece on the clicked square (clickedSquare.getPiece()!= null)
Make sure the game piece belongs to the current player. You can get the owning player by calling the getPlayerType() method on the AbstractGamePiece returned by getPiece(). You can then compare that to the currentPlayerTurn JailBreak class member.
If the piece on the clicked square belongs to the current player
Set the selected square equal to the clicked square
Call the select() method on the selected square to show the yellow border
END OF INSTRUCTIONS
I've figured out how to highlight the piece by implementing the select() method, butt
I've tried several different implementations, such as AbstractGamePiece.getPlayerType()==currentPlayerTurn, using nested if statements to set conditions on clickedSquare.getPiece(), and a couple others that I can't think of off the top. I can't seem to get a reference to getPlayerType() from the abstract class. There is pre-written code in the class that seems to work fine as far as accessing the AbstractGamePiece, such as
private void changePlayerTurn()
{
if (currentPlayerTurn == AbstractGamePiece.PLAYER_OUTLAWS)
currentPlayerTurn = AbstractGamePiece.PLAYER_POSSE;
else
currentPlayerTurn = AbstractGamePiece.PLAYER_OUTLAWS;
}
I feel like I'm going about this wrong, but I can't seem to get a reference to the getPlayerType(). The one time I did, I created a new object of the abstract class, but the constructor needs 3 parameters that aren't really appropriate here.
Supporting code:
abstract public class AbstractGamePiece
{
// All class members are provided as part of the activity starter!
// These two constants define the Outlaws and Posse teams
static public final int PLAYER_OUTLAWS = 0;
static public final int PLAYER_POSSE = 1;
// These variables hold the piece's column and row index
protected int myCol;
protected int myRow;
// This variable indicates which team the piece belongs to
protected int myPlayerType;
// These two strings contain the piece's full name and first letter abbreviation
private String myAbbreviation;
private String myName;
// All derived classes will need to implement this method
abstract public boolean hasEscaped();
// The student should complete this constructor by initializing the member
// variables with the provided data.
public AbstractGamePiece(String name, String abbreviation, int playerType)
{
myName = name;
myAbbreviation = abbreviation;
myPlayerType = playerType;
}
public int getPlayerType()
{
return myPlayerType;
}
public void setPosition (int row, int col)
{
myRow = row;
myCol = col;
}
public int getRow()
{
return myRow;
}
public int getCol()
{
return myCol;
}
public String getAbbreviation()
{
return myAbbreviation;
}
public String toString()
{
return (myName + " at " + "(" + myRow + "," + myCol + ")");
}
public boolean canMoveToLocation(List<GameSquare> path)
{
return false;
}
public boolean isCaptured(GameBoard gameBoard)
{
return false;
}
Code that highlights the pieces indiscriminately has been implemented successfully.
private void handleClickedSquare(GameSquare clickedSquare)
{
if (selectedSquare == null)
{
selectedSquare=clickedSquare;
selectedSquare.select();
}
else if (selectedSquare == clickedSquare)
{
selectedSquare.deselect();
selectedSquare = null;
}
else
{
}
Why is it that I'm unable to create a reference to the getPlayerType() method?
Just call getPlayerType on any expression of type X, where X is either AbstractGamePiece or any subclass thereof. For example, square.getPiece().getPlayerType().
Method references are a thing in java and are definitely not what you want, you're using words ('I'm unable to create a reference to getPlayerType') that mean something else. A method reference looks like AbstractGamePiece::getPlayerType, and let you ship the concept of invoking that method around to other code (for example, you could make a method that calls some code 10 times in a row - so this method takes, as argument, 'some code' - and method references are a way to that). It is not what you want here, you want to just invoke that method. Which is done with ref.getPlayerType() where ref is an expression whose type is compatible with AbstractGamePiece. From context, clickedSquare.getPiece() is that expression.
Related
i'm quite new to Java so let me know if I'm missing something basic here..
I came across this chunk of code referencing a method from the same class. (i.e. both methods exist with the same superclass)
//Method (Part of a bigger superclass)
private int hopDistance()
{//Implementation Not Shown}
//The Code in Question with the function call
public boolean simulate()
{
int position = 0;
for (int count = 0; count < maxHops; count++)
{
position += hopDistance();
if (position >= goalDistance)
{
return true;
}
else if (position < 0)
{
return false;
}
}
return false;
}
Why does it seem that line 7 in the code on the bottom is referencing the hopDistance() class without instantiating an object? I understand how static methods can have this property but didn't understand how non-static ones could...
In Java, one method within a class can call other methods within the same instance of that class without explicitly invoking the class name.
In other words, if simulate() and hopDistance() are both defined as methods in the same class, then
public boolean simulate() {
hopDistance();
}
and
public boolean simulate() {
this.hopDistance();
}
are identical.
my professor gave me an exercise to find how many time the characters of string called "filter" are to be found in a second string called "query".
before I begin I am java noob and English isnt my native language.
example:
String filter="kjasd";
String query="kjg4t";
Output:2
getting how many times a char has been found in another string isnt my problem but the problem that the professor gave us some rules to stick with:
class filter. The class must be the following public
Provide interfaces:
public Filter (String letters) (→ Constructor of class)
The string representing the filter should be stored in the letters string
public boolean contains (char character)
Returns true if the passed character is contained in the query string, otherwise false
-public String toString ()
Returns an appropriate string representation of the class (just to be clear I have no clue about what does he means with this one!)
To actually determine the occurrences of the filter in the query, another class QueryResolver is to be created.
The class should be able to be used as follows:
QueryResolver resolver = new QueryResolver();
int count = resolver.where(query).matches(filter).count();
the filter and the query are given by the user.
(i couldnt understand this one! )The methods "where" and "matches" configure the "QueryResolver" to include a subsequent call of "count" the calculation based on the previously passed variables
"query" and "filter" performs.
The count method should use the filter's previously-created method.
The modifier static is not allowed to use!
I dunno if he means that we cant use static {} or we cant use public (static) boolean contains (char character){}
we are not allowed to use void
so the problems that encountered me
- I can not pass a char to the method contains as long as it is not static.
error "Non-static variable can not be referenced from a static context"
i did not understand what i should do with the method toStirng!
what I've done so far:
Approach Nr 1:
so I just wrote everything in the main method to check whether the principle of my code works or not and then I wanted to create that whole with constructor and other methods but unfortunately I did not succeed.
Approach Nr 2:
then I tried to write the code in small mthoden as in the exercise but I did not succeed !.
in both aprroaches i violated the exercise rules but i cant seem to be able to do it alone thats why i posted the question here.
FIRST APPROACH:
public class filter{
public filter(String letters) {
//constructor of the class
String filter;
int count;
}
public boolean contains (char character){
/*Subprogram without static!
*the problem that I can't pass any char to this method if it wasn't static
*and I will get the following error"Non-static variable cannot be referenced from a static context"
*I understand why I'm getting the error but I don't know how to get around it X( */
return true ;
}
public String toString (){
/*he told us to include it in the program but honestly, I don't know what shall I write in it -_-
*I make it to null because you have to return something and I don't know what to do yet
*so, for now, I let it null. */
return null;
}
public static void main(String[] args) {
Scanner in =new Scanner (System.in);
System.out.println("please enter the query string! ");
String query= in.next();
System.out.println("please enter the filter stirng!");
String filter= in.next();
System.out.println("the query string is : [" + query+ "]");
System.out.println("the filter string is : [" + filter+ "]");
int count=0;
// I initialized it temporarily because I wanted to print it!
//later I need to use it with the boolean contains as a public method
boolean contains=false;
//to convert each the query and the filter strings to chars
char [] tempArray=query.toCharArray();
char [] tempArray1=filter.toCharArray();
//to iterate for each char in the query string!
for (int i = 0; i < tempArray.length; i++) {
char cc = tempArray[i];
//to iterate for each char in the filter string!
for (int j = 0; j < tempArray1.length; j++) {
// if the value in the filter string matches the value in the temp array then increment the counter by one!
if(tempArray1[j] == cc){
count++;
contains=true;
}
}
}
System.out.println("the characters of the String ["+filter+"] has been found in the forworded string ["+query+"] exactly "+count+" times!" );
System.out.println("the boolean value : "+ contains);
in.close();
}
}
SECOND APPROACH
- But here too I violated the rules of the task quite brutally :(
- First, I used void and did not use the tostring method.
- Second, I did not use a constructor.
- I did not add comments because that's just the same principal as my first attempt.
public class filter2 {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.println("enter the filter string:");
String filterStr=in.next();
System.out.println("enter the query string:");
String querystr =in.next();
Filter(filterStr, querystr);
in.close();
}
public static void Filter(String filterstr , String querystr){
char [] tempArray1 = filterstr.toCharArray();
contains(tempArray1, querystr);
}
public static void contains(char[]tempArray1, String querystr){
boolean isThere= false ;
int counter=0;
char [] tempArray = querystr.toCharArray();
for (int i = 0; i < tempArray.length; i++) {
char cc = tempArray[i];
for (int j = 0; j < tempArray1.length; j++) {
if(tempArray1[j] == cc){
counter++;
isThere=true;
}
}
}
System.out.println("the letters of the filter string has been found in the query string exactly "+counter+" times!\nthus the boolean value is "+isThere);
}
/*
* sadly enough i still have no clue what is meant with this one nor whatshall i do
* public String toString (){
* return null;
* }
*
*/
}
Few hints and advice would be very useful to me but please demonstrate your suggestions in code because sometimes it can be difficult for me to understand what you mean by the given advice. ;)
Thank you in advance.
(sorry for the gramatical and the type mistakes; english is not my native language)
As already mentioned, it is important to learn to solve those problems yourself. The homework is not for punishment, but to teach you how to learn new stuff on your own, which is an important trait of a computer scientist.
Nonetheless, because it seems like you really made some effort to solve it yourself already, here is my solution, followed by some explanation.
General concepts
The first thing that I feel like you didn't understand is the concept of classes and objects. A class is like a 'blueprint' of an object, and the object is once you instanciated it.
Compared with something like a car, the class would be the description how to build a car, and the object would be a car.
You describe what a class is with public class Car { ... }, and instanciate an object of it with Car myCar = new Car();.
A class can have methods(=functions) and member variables(=data).
I just repeat those concepts because the code that you wrote looks like you didn't fully understand that concept yet. Please ask some other student who understood it to help you with that.
The Filter class
public class Filter{
String letters;
public Filter(String letters) {
this.letters = letters;
}
public boolean contains (char character){
for(int i = 0; i < letters.length(); i++) {
if(letters.charAt(i) == character)
return true;
}
return false;
}
public String toString (){
return "Filter(" + letters + ")";
}
}
Ok, let's brake that down.
public class Filter{
...
}
I guess you already got that part. This is where you describe your class structure.
String letters;
This is a class member variable. It is unique for every object that you create of that class. Again, for details, ask other students that understood it.
public Filter(String letters) {
this.letters = letters;
}
This is the constructor. When you create your object, this is the function that gets called.
In this case, all it does is to take an argument letters and stores it in the class-variable letters. Because they have the same name, you need to explicitely tell java that the left one is the class variable. You do this by adding this..
public boolean contains (char character){
for(int i = 0; i < letters.length(); i++) {
if(letters.charAt(i) == character)
return true;
}
return false;
}
This takes a character and looks whether it is contained in this.letters or not.
Because there is no name collision here, you can ommit the this..
If I understood right, the missing static here was one of your problems. If you have static, the function is class-bound and not object-bound, meaning you can call it without having an object. Again, it is important that you understand the difference, and if you don't, ask someone. (To be precise, ask the difference between class, object, static and non-static) It would take too long to explain that in detail here.
But in a nutshell, if the function is not static, it needs to be called on an object to work. Look further down in the other class for details how that looks like.
public String toString (){
return "Filter(" + letters + ")";
}
This function is also non-static. It is used whenever the object needs to be converted to a String, like in a System.out.println() call. Again, it is important here that you understand the difference between class and object.
The QueryResolver class
public class QueryResolver {
Filter filter;
String query;
public QueryResolver where(String queryStr) {
this.query = queryStr;
return this;
}
public QueryResolver matches(String filterStr) {
this.filter = new Filter(filterStr);
return this;
}
public int count() {
int result = 0;
for(int i = 0; i < query.length(); i++) {
if(filter.contains(query.charAt(i))){
result++;
}
}
return result;
}
}
Again, let's break that down.
public class QueryResolver {
...
}
Our class body.
Note that we don't have a constructor here. It is advisable to have one, but in this case it would be an empty function with no arguments that does nothing, so we can just leave it and the compiler will auto-generate it.
public QueryResolver where(String queryStr) {
this.query = queryStr;
return this;
}
This is an interesting function. It returns a this pointer. Therefore you can use the result of the function to do another call, allowing you to 'chain' multiple function calls together, like resolver.where(query).matches(filter).count().
To understand how that works requires you to understand both the class-object difference and what exactly the this pointer does.
The short version is that the this pointer is the pointer to the object that our function currently lives in.
public QueryResolver matches(String filterStr) {
this.filter = new Filter(filterStr);
return this;
}
This is almost the same as the where function.
The interesting part is the new Filter(...). This creates the previously discussed Filter-object from the class description and puts it in the QueryResolver object's this.filter variable.
public int count() {
int result = 0;
for(int i = 0; i < query.length(); i++) {
if(filter.contains(query.charAt(i))){
result++;
}
}
return result;
}
Iterates through the object's query variable and checks for every letter if it is contained in filter. It keeps count of how many times this happens and returns the count.
This function requires that filter and query are set. Therefore it is important that before someone calls count(), they previously call where(..) and matches(..).
In our case, all of that happens in one line, resolver.where(query).matches(filter).count().
The main function
I wrote two different main functions. You want to test your code as much as possible during development, therefore the first one I wrote was a fixed one, where you don't have to enter something manually, just click run and it works:
public static void main(String[] args) {
String filter="kjasd";
String query="kjg4t";
QueryResolver resolver = new QueryResolver();
int count = resolver.where(query).matches(filter).count();
System.out.println(count);
}
Once you understand the class-object difference, this should be straight forward.
But to repeat:
QueryResolver resolver = new QueryResolver();
This creates your QueryResolver object and stores it in the variable resolver.
int count = resolver.where(query).matches(filter).count();
Then, this line uses the resolver object to first call where, matches, and finally count. Again, this chaining only works because we return this in the where and matches functions.
Now finally the interactive version that you created:
public static void main(String[] args) {
Scanner in =new Scanner(System.in);
System.out.println("please enter the query string! ");
String query= in.next();
System.out.println("please enter the filter stirng!");
String filter= in.next();
System.out.println("the query string is : [" + query+ "]");
System.out.println("the filter string is : [" + filter+ "]");
QueryResolver resolver = new QueryResolver();
int count = resolver.where(query).matches(filter).count();
System.out.println("the characters of the String ["+filter+"] has been found in the forworded string ["+query+"] exactly "+count+" times!" );
in.close();
}
I'm having a problem with my Java assignment on inheritance. I won't go into detail on the task as that's not my issue. In the program. have a superclass with some fields in it. Two of these fields are ints, xCoord and yCoord. There is then a subclass that obviously also has these ints. It also has another attribute, short direction, that is not contained in the superclass. I need to access all three of these attributes in the user class. The user class needs to be able to change these values. When attempting to compile. I get the error:
error: ';' expected
in all the lines in my user class that try to increment xCoord or yCoord. For example:
mov1.yCoord++
^
So, I don't really know what the problem is. I assume it has something to do with the attributes not be directly declared in that class. My reasoning for this is because I have lines that deal with the short direction in the same manner. For example:
mov1.direction = 1
This goes through the compiler with no problem. So I reckon in must be because xCoord and yCoord only declared in the super class. But that's just my assumption, I could be wrong. Regardless if whether I am or not, I need to fix this while still using inheritance for these fields, the assignment requires it. Any help?
For reference, here are some snippets of relevant code:
The superclass: (didn't include the methods because not relevant)
public class StationaryThing {
// Attributes
protected String name;
protected final int gridlength = 10;
protected final int gridwidth = 10;
public int xCoord;
public int yCoord;
// Constructor
public StationaryThing(String name, int xCoord, int yCoord) {
this.name = name;
this.xCoord = xCoord;
this.yCoord = yCoord;
}
The subclass: (again, didn't include methods)
public class MovingThing extends StationaryThing {
// Attributes
public short direction = 0;
// Constructor
public MovingThing(String name, int xCoord, int yCoord) {
super(name, xCoord, yCoord);
}
And some of the relevant lines from the user class:
for (int i = 0; i < noMoves; i++) {
if (mov1.direction == 0) {
if (hole1.xCoord == mov1.xCoord && hole1.yCoord == mov1.yCoord+1) {
mov1.direction = 1;
mov1.holeAhead();
mov1.directionChange();
}
if (mov1.yCoord == 9) {
mov1.direction = 1;
mov1.directionchange();
}
else {
mov1.displayAttributes
mov1.yCoord++;
}
}
Again, thanks for any help you can give.
Are those lines "missing ;" inside a method? There cannot be "just code" inside the class, but there should be a method like
public void doSth () {
a++;
}
Please refer java code is showing error. ( ';',expected) for a similar situation.
So, I am trying to use an enumerated data type as parameter in the place of an object being passed in. I know that a simple switch statement would work but that doesn't really seem elegant to me. I have searched and found that enums can also have actions attached to them but I'm not so clear how to use it in this case or if it is even possible, or if i am just really tired. let me try to use code to explain what I'm asking.
First I have a class with certain fields of other objects that I am basically trying to use the enums to reference. In this case I have a method that acts on one of the fields of trees, because their are multiple trees the method needs to know which tree to act on.
public class bstContactManage()
{
// fields of other objects
BST searchTreeFirstName = new BST(new ComparatorObjOne);
BST searchTreeLastName = new BST(new ComparatorObjTwo);
// and so on and so forth
public boolean modify(Contact contactToFind, BST ToFindIn, String newContactInfo)
{
Contact contUpdate = new Contact(ContactToFind)//save for readdition to tree
contUpdate.update(newContactInfo);
toFindIn.remove(contactToFind);
if(toFindIn.add(contUpdate)) return true;
else return false;
}
}
what I'm wondering or more or less pondering is how to replace the BST parameter with a an enum
i know i could use a switch statement but that doesn't seem any more effective maybe more elegant than passing it an int value and letting it go wild!
so is there a way to get method to look something like
public boolean modify(Contact contactToFind, Enum BSTType, String newContactInfo)
{
Contact contUpdate = new Contact(ContactToFind)//save for readdition to tree
contUpdate.update(newContactInfo);
BSTType.remove(contactToFind);
if(BSTType.add(contUpdate)) return true;
else return false;
}
most of my question stems from the fact that an object such as
bstContactManage man = new bstContactManage()
will be instantiated in another class, and therefore it isn't safe or doesn't seem proper to me to do something like
man.modify(contactIn, man.searchTreeFirstName, "String");
update:
so for more clarification i have another method find which searches a given BST, and currently i am implementing it like this
public List<Contact> find(BinarySearchTree treeUsed, String findThis)
{
//create a new contact with all fields being the same, find is dependent and comparator on tree;
Contact tempContact = new Contact(findThis, findThis, findThis);
return treeUsed.getEntry(tempContact); // where getEntry returns a list of all matching contacts
}
I could do something like
public List<Contact> find(EnumField field, String findThis)
{
BST treeUsed;
switch(Field){
case FIRST:
treeUsed = this.searchTreeFirstName;
break;
cast LAST:
treeUsed = this.searchTreeLastName;
break;
Contact tempContact = new Contact(findThis, findThis, findThis);
return treeUsed.getEntry(tempContact); // where getEntry returns a list of all matching contacts
}
Enum could provide different implementation of its method. A good example would be Math operation:
enum Op {
PLUS {
int exec(int l, int r) { return l + r; }
},
MINUS {
int exec(int l, int r) { return l - r; }
};
abstract int exec(int l, int r);
}
Then I could do Op.PLUS.exec(5, 7) to perform 5 plus 7
See http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html for more detail on how to use enum.
In your case, I wouldn't use enum for something having loads of logic and state, but here is how you could use enum with methods having different implementations.
enum BSTType {
SearchTreeFirstName {
void someMethod(Contact c) {...}
},
SearchTreeLastName {
void someMethod(Contact c) {...}
};
abstract void somemethod(Contact c);
}
public boolean modify(Contact contactToFind, BSTType bstType, String newContactInfo) {
// ...
bstType.someMethod(contact);
// ...
}
By looking at the variable name and class name, I think what you actually meant is indexing Contact in a TreeSet either by first name or last name
enum IndexType implements Comparator<Contact> {
IndexByFirstName {
#Override
public int compare(Contact o1, Contact o2) {
return o1.firstName.compareTo(o2.firstName);
}
},
IndexByLastName {
#Override
public int compare(Contact o1, Contact o2) {
return o1.lastName.compareTo(o2.lastName);
}
};
}
TreeSet<Contact> contacts = new TreeSet<Contact>(IndexType.IndexByLastName);
How can I tell if a method is being called so that I can add a counter to measure the total calls of this method?
Edit for clarification.
assuming that I have
class anything{
public String toString() {
++counter;
return "the time this method is being called is number " +counter;
}
}//end class
and I am creating an instance of anything in a main method 3 times,
and the output I want if I call its toString() the whole 3 times is this:
the time this method is being called is number 1
the time this method is being called is number 2
the time this method is being called is number 3
I want the counter being added succesfully inside the class and inside the ToString() method and not in main.
Thanks in advance.
You can use a private instance variable counter, that you can increment on every call to your method: -
public class Demo {
private int counter = 0;
public void counter() {
++counter;
}
}
Update : -
According to your edit, you would need a static variable, which is shared among instances. So, once you change that varaible, it would be changed for all instances. It is basically bound to class rather than any instance.
So, your code should look like this: -
class Anything { // Your class name should start with uppercase letters.
private static int counter = 0;
public String toString() {
++counter;
return "the time this method is being called is number " +counter;
}
}
The best way to do this is by using a private integer field
private int X_Counter = 0;
public void X(){
X_Counter++;
//Some Stuff
}
You have 2 options...
Count the messages for one instance:
public class MyClass {
private int counter = 0;
public void counter() {
counter++;
// Do your stuff
}
public String getCounts(){
return "The time the method is being called is number " +counter;
}
}
Or count the global calls for all created instances:
public class MyClass {
private static int counter = 0;
public void counter() {
counter++;
// Do your stuff
}
public static String getCounts(){
return "the time the method is being called is number " +counter;
}
}
It depends on what your purpose is. If inside you application, you want to use it, then have a counter inside every method to give details.
But if its an external library, then profilers like VisualVM or JConsole will give you number of invocations of each method.