How to use a variable in two classes? - java

I need to be able to see in all of these classes if the variable is true.
public void performAction() {
if (door.intersects(HERO)) {
System.out.println("ActionPerformed!");
HeroX = 0;
HeroY = 0;
inside = true;
}
}
This is every time I press SPACE and now I want to draw the inside of the House.
In the Main class where I draw everything I want to say something like:
public void paintComponent(Graphics g) {
if (!inside) {
g.drawImage(Background, 0, 0, null);
achilles.Draw(g);
}else if (inside) {
g.drawImage(HouseInside, 0, 0, null);
}
}
I don't know how to change the "inside" in the Hero class and use it in the Main class. I have tried so many things and I don't know what to do.

inside is a property of a HERO object, so, if the property is public, you can access it with heroname.inside
If the property is private (which it generally should be), you have to use a public access function inside the HERO class, such as HERO.isInside, and set it with a setting function like HERO.setInside and HERO.setOutside.
this is often called "getters and setters"

What you probably want are global variables
public class Global{
public static int value;
}
You can then access them from anywhere:
Global.value;

If you Main class has a reference to all instances of the Hero class, then the usual best practice would be for the Hero class to expose a method like this:
public boolean isInside () {
return (inside);
}
If there is only ever one instance of the Hero class (unlikely, but ok), then one option is to make inside a public static variable like this:
public static boolean inside;
referenced from Main like this:
if (! Hero.inside) {
or make inside a private static variable with a getter like this:
private static boolean inside;
public static boolean isInside () {
return (inside);
}
referenced from Main like this:
if (! Hero.isInside ()) {

Try using a getter to get the inside attribute outside of Hero, and a setter to change it:
public class Hero {
private boolean inside;
...
public boolean isInside() {
return this.inside;
}
public void setInside(boolean inside) {
this.inside = inside;
}
}
I'd also recommend reading more about encapsulation; it'll give you a better idea about how to work with objects in Java.

You could model it differently:
public class House {
Location currentLocation=Location.OUTSIDE;
Map<Location, String> layout=new HashMap<>();
public House(){
layout.put(Location.INSIDE,"Draw the inner parts");
layout.put(Location.INSIDE,"Draw the outer parts");
}
public void enterDoor(){
currentLocation=(currentLocation==Location.OUTSIDE)?Location.INSIDE:Location.OUTSIDE;
}
public void draw(){
System.out.println(layout.get(currentLocation));
}
}
Here enterDoor is something, which could be fired by an event in your game-environment. So your House knows how to draw itself depending on its state.
Say your character moves to some coordinates (x|y), where the door is, the enterDooris called upon House, which in turn switches the layout.

Related

How do you pass an updated global class variable from one method into another?

I update a variable (which is global in the class) in one method and I cannot seem to be able to then pass that updated variable into another method.
Any help would be appreciated, thank you.
Here's my shortened code:
public class Game{
private int randomIndexX;
protected String spawn(){
randomIndexX = randomGenerator.nextInt(10);
return null;
}
protected String test(){
System.out.println(this.randomIndexX);
return null;
}
}
public class Player extends Game{
protected String getNextAction(String command) {
switch(command){
case "test":
test();
break;
}
}
}
public static void main(String[] args) {
Game game = new Game();
Player player = new Player();
game.spawn();
player.getInputFromConsole();
}
EDIT: so when i call test() from the Player class i want it to print out randomIndexX but it still doesn't seem to be working even with this.randomIndexX in the method test()
EDIT: so when i call test() from the Player class i want it to print out randomIndexX but it still doesn't seem to be working even with this.randomIndexX in the method test().
So test() is instance method, which means you'll have to make an instance of Class Game in order to call that method, your randomIndexX is instance member so you need to think well what you want to do, IF randomIndexX is common for all the objects of Game class, you should declare it static as in:
private static in randomIndexX;
As it's value won't change depending on an object instance.
So in order to access that variable from outside of the class since it's private you declare a public method to retrieve that value (getter or also known as accessor):
public static int getRandomIndex(){
return randomIndexX;
}
So when in main, you don't even have to make an instance of the Game class to access value that's being held in randomIndexX, you just call the getter method like this:
System.out.println(Game.getRandomIndex());
The line above will print 0 to the console as 0 is default value for members of type int, now if you want to be able to change it, you just make a setter or mutator method in Game class as well:
public static void setRandomIndex(int n){
randomIndexX = n;
}
And there you go, you can now set and retrieve "randomIndexX" field from outside of the Game class.
For example, the code below will set value of randomIndexX to 5 and then print it in the console:
Game.setRandomIndex(5);
System.out.println(Game.getRandomIndex());
The first problem I can see is that you don't have a constructor.(Optional)
(If you don't make one the compiler makes what is called a "Default" constructor which is a constructor without any parameters. Its usually good practice to explicitly create a class constructor.
The second problem I can see is that you missing the end bracket.
Fix shown below.
public class Game
{
private int randomIndexX;
protected String spawn()
{
randomIndexX = 0;
return null;
}
protected String test()
{
System.out.println(randomIndexX);
return null;
}
}
You can construct it and trigger any methods you wish:
Game game = new Game();
game.spawn();
game.test()

Making a static duplicate of non-static integer

For my programming class in first year engineering I have to make a D-game in Java, with only very little knowledge of Java.
In one class I am generating a random integer via
public int rbug = (int)(Math.random() * 18);
every so many ticks. I have to use this integer in another class (in the requirements for an if-loop), and apparently it needs to be static. But when I change the variable to public int static, the value doesn't change any more.
Is there an easy way to solve this problem?
Edit: part of code added:
public int rbug = (int)(Math.random() * 18);
which is used in
public void render(Graphics g){
g.drawImage(bugs.get(rbug), (int)x, (int)y, null);
And in another class:
if(Physics.Collision(this, game.eb, i, BadBug.rbug)){
}
As error for BadBug.rbug I get the message
Cannot make a static reference to a non-static field
Using static to make things easier to access is not a very good ideal for design. You would want to make variables have a "getter" to access them from another class' instance, and possibly even a "setter". An example of this:
public class Test {
String sample = 1337;
public Test(int value) {
this.sample = value;
}
public Test(){}
public int getSample() {
return this.sample;
}
public void setSample(int setter) {
this.sample = setter;
}
}
An example of how these are used:
Test example = new Test();
System.out.println(example.getSample()); // Prints: 1337
example = new Test(-1);
System.out.println(example.getSample()); // Prints: -1
example.setSample(12345);
System.out.println(example.getSample()); // Prints: 12345
Now you might be thinking "How do I get a string from the class that made the instance variable within the class?". That's simple as well, when you construct a class, you can pass a value of the class instance itself to the constructor of the class:
public class Project {
private TestTwo example;
public void onEnable() {
this.example = new TestTwo(this);
this.example.printFromProject();
}
public int getSample() {
return 1337;
}
}
public class TestTwo {
private final Project project;
public TestTwo(Project project) {
this.project = project;
}
public void printFromProject() {
System.out.println(this.project.getSample());
}
}
This allows you to keep single instances of classes by passing around your main class instance.
To answer the question about the "static accessor", that can also be done like this:
public class Test {
public static int someGlobal = /* default value */;
}
Which allows setting and getting values through Test.someGlobal. Note however that I would still say that this is a horrible practice.
Do you want to get a new number every time that you want BadBug.rbug? Then convert it from a variable to a method.

How to access an object from a different class and package?

So, I am a learning programmer and I started to learn Java 2 months ago as a course at my university. I really like to program in my spare time and I'm currently trying to make a game. There is one problem at the moment which I just can't solve.
I have a class called Move, and I declare in my class called Start:
Move move1 = new Move();
Now when I'm back in my Move class, I would like to access this move1 but it doesn't let me. It says:classname cannot be resolved.
To clarify:
public class Move {
private String s = null;
public void setName(String s) {
name = s;
}
public String getName() {
return name;
}
public void setList() {
System.out.println(move1.getName() + move2.getName()); // This won't work
}
}
And the start class:
public class Start {
public static void main(String[] args) {
Move move1 = new Move();
Move move2 = new Move();
move1.setName(kick);
move2.setName(punch);
}
}
It would be awesome if someone could help me out!
-edit
OK! I got a few reactions but I didn't really get the answer I need. I know now i can use this instead of the object name but what if I want to use a second object? I changed code the above.
The problem you have is that the names move1 and move2 are out of scope in the setList method. They're defined in Start.main as local variables, so they are only visible there.
There are a innumerable ways you can solve this. The most straight-forward way is to move the setList method to Start. Because you're calling it from main, which is a static method, setList will also have to be static.
public class Start {
public static void main(String[] args) {
Move move1 = new Move();
Move move2 = new Move();
move1.setName(kick);
move2.setName(punch);
setList(move1, move2);
}
public static void setList(Move move1, Move move2) {
System.out.println(move1.getName() + move2.getName());
}
}
If you think setList should be in the Move class, you'll need to pass the second move as a parameter.
public class Move {
...
public void setList(Move other) {
System.out.println(this.getName() + other.getName());
}
}
You don't need to say move1.getName(). You can say this.getName() instead. The keyword this refers to whatever object is calling the method - in this case, move1.
This is because the object move1 only exists in the scope of the main method in Start. Therefore, "move1" is meaningless anywhere other than main.
In reality, the keyword this can be omitted; you could just say getName() without putting anything in front of it.
move1 is the object of Move class define in the Start class so you cant access it.You can simply access the method of Move class with below line.
System.out.println(getName()); // THis will work
The correct way to access current move object (move1) is using this key word. You could say System.out.println(this.getName()); in Move class.
Maybe you didn't add import of class Move? It necessary when you access an object from a different package.

How can I access a Local Variable which is an object from within another class? - Java

My understanding is that you can't do what I'm asking. If you look at the starred (*) commented errors in the code below, you can see what I'm trying to access. I feel like I need to be able to do this so that I can use a method to dynamically create many objects and then access all of those objects from other objects.
Is there a way to do this that I'm missing, or am I just messing something up? If not, how should I go about doing this to enable me to get the same functionality as below? If there's any way to do this other than passing the objects around, it would be appreciated (passing objects seems like so much work - especially with multi-dimensional arrays of objects - there should be an easy way to instantiate package-private objects that can be accessed anywhere else in the package). But if passing is the only way, please let me know the best way to do it, especially when I'm passing a two-dimensional array of a bunch of objects. Thanks!
package simpleclasswithinclasstest;
class Game {
static int boardSize;
Engine gameEngine;
Game() {
}
public void run() {
gameEngine = new Engine();
gameEngine.play();
}
public int getBoardSize() {
return boardSize;
}
}
class Engine {
int boardSize;
Engine() {
}
public void play() {
this.boardSize = currentGame.getBoardSize(); // *****1 Error is here.
// *****It doesn't recognize currentGame, but I want it to.
}
void doNothing() {
}
}
class Board {
Board() {
}
void Test() {
gameEngine.doNothing(); // 2 *****Error is here.
// *****It doesn't recognize gameEngine.
}
}
public class SimpleClassWithinClassTest {
static Game currentGame;
public static void main(String[] args) {
currentGame = new Game();
currentGame.run();
}
}
You will get access to gameEngine through your Board class by passing it as a parameter to Board. When you instantiate your Board, you could do something like this:
class Engine {
int boardSize;
Engine () {
Board board = new Board(this);
}
public void play() {
}
void doNothing() {
// magic stuff in here
}
}
class Board {
Engine engine;
Board (Engine gameEngine) {
this.engine = gameEngine
}
void Test() {
engine.doNothing(); // No error here :-) and this engine is your main one
}
}
Take a look at the concept of message-driven communication. Things might get clearer for you by reading this answer.
In the following picture, which I took from the answer linked above, you can imagine f as your engine object within the Engine class, and c as your engine within the Board class. You are actually manipulating the same object.
As for your other problem (the first one): it can't recognize currentGame because you don't have any variable with that name in your scope.
There is no variable of any type named 'currentGame' in scope at that point in the code.
Furthermore, while boardSize is a static package-protected variable, the method getBoardSize() is an instance variable. One possible solution is to make the method static and package protected, then you can do this:
public void play() {
this.boardSize = Game.getBoardSize();
}
This is like initializing an int variable in 1 function and trying to access it from another function.The objects(you are trying to access) are out of scope in the part of the code where you are trying to access.You can resolve this issue by sending this
as a parameter and recieving it as an object in the corresponding method.
We can use class reference to call static methods only. So you can make the play a static method.
class Engine {
int boardSize;
Engine() {
}
public void play() {
this.boardSize = currentGame.getBoardSize(); // *****1 Error is here.
// *****It doesn't recognize currentGame, but I want it to.
}
static void doNothing() {
}
}
class Board {
Board() {
}
void Test() {
Engine.doNothing();
}
}
The other way is to make an Object from the class and access the non static methods within that object.
class Engine {
int boardSize;
Engine() {
}
public void play() {
this.boardSize = currentGame.getBoardSize(); // *****1 Error is here.
// *****It doesn't recognize currentGame, but I want it to.
}
void doNothing() {
}
}
class Board {
Board() {
}
void Test() {
Engine gameEngine = new Engine();
gameEngine.doNothing();
}
}

How do I call a constructor?

I am currently done making a sokoban game with GUI and everything and I am working on optimzation, I would like to keep the objects as sensible as possible and therefore need to be able to call the constructor from a method in the class/object. Suppose:
public class BoardGame() {
public BoardGame)() {
this(1)
}
public BoardGame(int level){
//Do stuff, like calling filelevel-to-board loaderclass
}
How do I create a method that calls the constructor of this object/class in the object/class itself? Eg:
public BoardGame nextLevel() {
return BoardGame(currentLevel+1);
}
The above is apparently undefined!
Such that if I want to use this object in another class I should be able to do:
GameBoard sokoban = new GameBoard(); //lvl1
draw(GameBoard);
draw(GameBoard.nextLevel()); //draws lvl2
You need to use the new keyword to call the constructor.
public BoardGame nextLevel() {
return new BoardGame(currentLevel + 1);
}
Calling the constructor requires the new keyword and always creates a new instance. For instance, in your example code
GameBoard sokoban = new GameBoard(); //lvl1
draw(sokoban );
draw(sokoban.nextLevel()); //draws lvl2
sokoban <-- still level 1
Maybe you want the GameBoard to be mutable:
public class GameBoard {
public GameBoard() {
setLevel(1);
}
private void setLevel(int i) {
currentLevel = i;
....
}
public void nextLevel() {
setLevel(currentLevel+1);
}
}

Categories

Resources