Application class can't change subclass fields - java

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.

Related

further separating / calling function that is in class from object

I'm having trouble calling move.m_north from another function.
It is asking me to make the class move and the function m_north static, but if I do i can't reference y unless I make it static too.
I found that if y is static then any dot object I make will have the same value for y, and I need multiple dots
public class dot {
int y=0; //<-- 3. but if I make this static then it will stay the same for every object
public void step(int direction) {
switch (direction){
case 0:
move.m_north(); //<-- 1. is asking to make move.m_north static
}
}
public class move {
public int m_north() {
if (y > 0) {
y -= 1; //<-- 2. but I need to modify and read non static variables
return -1;
} else return -2;
}
}
}
I am able to call m_north if it is not in the move class but there are many similar functions which I believe need to be split up so I can use same names and it becomes easier to find different functions.
I would much appreciate any assistance.
You can make this work by declaring an instance of the move class. For example (with captialization changed to match Java naming conventions):
public class Dot {
int y=0;
Move move = new Move();
public void step(int direction) {
switch (direction){
case 0:
move.m_north();
}
}
public class Move {
public int m_north() {
if (y > 0) {
y -= 1;
return -1;
} else return -2;
}
}
}
Note that Move with an uppercase M is the class name, and move with a lowercase m is the name of an instance variable in the class Dot.
The reason this is required is that m_north requires an enclosing instance of Dot in order to access its y field. To put it another way, you need to call m_north on a specific dot's move instance. Making the method static doesn't provide an enclosing dot in scope.

Referencing method from abstract class

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.

Syntax error on "x", VariableDeclaratorld expected after this

class anyName
{
int Tcol = 0;
int fc = 0;
int x = 0;
float randx = (random(1, 1000));
float randy = (random (0, 600));
int Tsizes = 1;
{
if (fc >= x) { //Random Ellipse 3
stroke (Tcol);
fill (Tcol);
ellipse (randx, randy, Tsizes, Tsizes);
}
}
}
anyName ranx1 = new anyName();
ranx1.x = 100;
Hi, I am trying to add a class/object to my code and it is not working. This is the class I have so far, but when I instantiate one object from that class (ranx1), and then try change one of the variables inside it (x), it says there is a error. Is there anything I need to change? I would really appreciate any help.
Since I instantiated an object from that class, how would I change the variables for the new object? For example, if in the class x = 0, then I made a copy and this time I want x to = 100, but all the other variables such as Tcol and fc to stay the same. I know this is possible because my teacher taught it, but it is not working right now for me.
ranx1.x = 100;
You need to declare your variables as "public" if you are trying to access from a class that is not in the same package.
I guess your problem is you are trying to access to that attribute from a class that is in another package, you should declare the atrributes as public to gain access to them. But this solution wouldn't be totally correct, a better approach is declaring them as private and creating public getters and setters to access/modify them.
Said that, you should post a working example, that piece code does not compile because you are trying to execute code that is out of any class... and I'm not sure what you are trying to do with the curly braces before the if clause.
when you careate a class, every member has a control access.
when you don't state the control access like:
public x;
protected fc;
private Tcol;
they all get default private.
you can't access private members from outside the class.
do:
class anyName
{
public int Tcol = 0;
public int fc = 0;
public int x = 0;
public float randx = (random(1, 1000));
public float randy = (random (0, 600));
public int Tsizes = 1;
{
if (fc >= x) { //Random Ellipse 3
stroke (Tcol);
fill (Tcol);
ellipse (randx, randy, Tsizes, Tsizes);
}
}
}
whoever, i must point out that most times it's not recommended to set members access as public and you should learn about getter and setters.
now i hope the rest of your code is in a main function and in a main class, but if not it should be like so:
public class Main
{
public static void main(String[]args){
anyName ranx1 = new anyName();
ranx1.x = 100;
}
}
First of all you cannot access sub class veriables like that. If you want to access you should make this
public class ExampleApp {
class anyName
{
int x = 0;
}
public static void main(String[]args){
ExampleApp ea = new ExampleApp();
ExampleApp.anyName ranx1= ea.new anyName();
ranx1.x =100;
}
}
Or you can use them inside of the class with method
public void method() {
anyName ea = new anyName();
ea.x=100;
}
you cannot use your veriables private if you want to access them.Secondly if you want to use this libraries you cant use innerclass. Inside of innerclass you cannot access libraries because java sees it in diffrent package. If you make it public class and import Math you can use it otherwise you should make method for your ellipse, random .

is This Data Abstration Example right or not?

i had given the following code in an interview. I want to know whether it is right or not..
public class DataAbstraction
{
public static void main (String args[])
{
MyDetails obj = new MyDetails();
obj.setNumebr(10);
obj.incrementBy(20);
int num = obj.getMumber();
System.out.println(num);
}
}
class MyDetails
{
private int n;
public void setNumebr(int i)
{
n = i;
}
public void incrementBy(int i)
{
n = n + i;
}
public int getMumber()
{
return n;
}
}
So please check it and correct me if i was wrong
There are many forms of abstractions in software. I would say that this is an example of data abstraction (though I would usually call it encapsulation). You could, if you would like to, change the member variable n to be of type... String(!), without changing the public interface of MyDetails.
Put differently: The details in the MyDetails class are hidden from the client code. The fact that MyDetails stores an int is abstracted away and it could be changed, for instance like this:
class MyDetails
{
private String n; // changed internal detail
public void setNumebr(int i)
{
n = "" + i;
}
public void incrementBy(int i)
{
n = "" + getMumber() + i;
}
public int getMumber()
{
return Integer.parseInt(n);
}
}
Have a look at the Wikipedia article on data abstraction for further details:
Abstraction > Data abstraction
Since there aren't enough details in the question its guessing time again:
1) No, its wrong. it contains various spelling errors like "getMumber" and "setNumebr".
2) Yes, if we ignore the spelling errors the methods seem to do what one would expect from their names.
2) No, it doesn't launch the rocket and it doesn't scale to multi processor machines (assuming these where the requirements).

Luse Constructor With Variable Inside

I'm learning about constructors.
When I try to compile the following code, I get the error "variable input and shape are not initialized."
Could anyone tell me why and how to solve it?
public class Try {
public static void main(String[] args)
{
String input;//user key in the height and width
int shape;//triangle or square
Count gen = new Count(input , shape);//is this the right way to code?
gen.solve();
}
}
public class Count {
public Count(String inp, int shp) {
String input_value = inp;
shape_type = shp;
}
public void solve () {
if shape_type==3{
//count the triangle
}
else if shape_type==4{
//count the square
}
}
}
You haven't given shape or input values yet before you try using them. Either you can give them dummy values for now, like
String input = "test";
int shape = 3;
Or get the string and integer from the user; in that case, you might want to take a look at how to use a Scanner.
By leaving input and shape without values, at:
String input;
int shape;
they are uninitialized, so Java doesn't know what their values really are.
I assume this is some kind of homework. I took the liberty of reformating and fixing your code a little.
You have to initialize any variable you are going to use. The only exception is when you are using class members (those are initialized automatically to some default value). See below that the members of the Count class aren't explicitly initialized.
This is some working code. Also note that i change the solve method a little (the if blocks should have had () around the expression. But what you are trying to do is usually better done with a switch block as shown below. Also I declared two members inside the Count class to remember the values provided at construction time in order to be able to use them when calling the solve() method.
public class Try {
public static void main(String[] args) {
String input = null; //user key in the height and width
int shape = 0; //triangle or square
Count gen = new Count(input, shape);//is this the right way to code?
gen.solve();
}
}
class Count {
String input_value;
int shape_type;
public Count(String inp, int shp) {
this.input_value = inp;
this.shape_type = shp;
}
public void solve() {
switch (this.shape_type) {
case 3:
// count the triangle
break;
case 4:
// count the square
break;
}
}
}
Proper formatting of the code usually helps :).

Categories