java.lang.NullPointerException when filling an array of objects - java

There's something I'm missing here. with this code I get a java.lang.NullPointerException:
public static void main(String[] args) {
Board board = new Board();
board.Initialise();
}
public class Board {
private Obj[][] tableau;
public void Board() {
tableau = new Obj[8][8];
}
public void Fill_Board() {
tableau[0][0]= new Obj('B');
}
}
But with this other code I get no error. What I am doing wrong, and how to initialize properly this array of object?
public class Board {
private Obj[][] tableau = new Obj[8][8];
public void Board() {
}
public void Fill_Board() {
tableau[0][0]= new Obj('B');
}
}

Board() ends up being a member function and not a constructor, and therefore never gets called. The problem is the void keyword, which needs to be removed:
public Board() { /* removed the `void' */
tableau = new Obj[8][8];
}

I get no error when I run this code (changing Obj to an actual class), perhaps you can provide a more concrete example with a main method of what you're trying to do?
If you're looking at making a constructor then it needs to be the same name as your class, i.e. Tab and have no return type.
So you would need to add:
public Tab() {
// initialization code here
}
You're constructor will run whenever you create a new instance of that class. You want to use it to initialize all of your variables.
Tab t = new Tab(); // Constructor runs
Edit:
You're main method uses class Board but you have given us a class called Tab. I can assume that you really want class Board so you should change all Tab to Board in the above example, if that's what you're looking for.

Related

Selenium Java - How to call a class from different class

I am new to Selenium and I need help whatever I can get. I will try to provide detailed info as much as I can. I need to call the object imgBtn01 or imgBtn02 inside the FIRST Class (ImagesRepo) from the SECOND Class. The reason I want to separate it, I want all to store all the image objects from a different class.
Selenium + Sikuli > Java > Maven Project
First Class from different Package
public class ImagesRepo {
public void imageRepoApp() {
//Images assigning object
Screen screen = new Screen();
Pattern imgBtn01 = new Pattern("/Images/Btn_ButtonName01.png");
Pattern imgBtn02 = new Pattern("/Images/Btn_ButtonName02.png");
}
Second class, from a different package:
public class testBed {
public static void callRepoImages() throws FindFailed {
ReporImages();
}
#Test
public static void ReporImages() {
Screen screen = new Screen();
screen.click(imgBtn01); //the imgBtn01 has a redline
screen.click(imgBtn02); //the imgBtn02 has a redline
return;
}
}
This looks to be more of a how to code in java type question.
One way to do this is to create public variables to your first class and fetch these from the second class.
Change 1st class to something like;
public class ImagesRepo {
public Pattern imgBtn01;
public Pattern imgBtn02;
public void imageRepoApp() {
//Images assigning object
Screen screen = new Screen();
imgBtn01 = new Pattern("/Images/Btn_ButtonName01.png");
imgBtn02 = new Pattern("/Images/Btn_ButtonName02.png");
}
You can then get these public variables in Second class as;
public class testBed{
public static void callRepoImages() throws FindFailed {
ReporImages();
}
#Test
public static void ReporImages() {
ImagesRepo imgrepo = new ImagesRepo();
imgrepo.imageRepoApp(); //So that pattern assignment is done.
Screen screen = new Screen();
screen.click(imgrepo.imgBtn01); //the imgBtn01 has a redline
screen.click(imgrepo.imgBtn02); //the imgBtn02 has a redline
return;
}
}
Also, add import for the class ImagesRepo appropriately in the class testBed
Code untested.
There are better ways to do it, but this seems the way to go with minimal changes to your code.

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()

Java in BlueJ does not execute main class

I am using the BlueJ IDE. I have a main class entitled ProgramOne, and another class StarTurtle (intended to serve an instance method).
Here is the code of ProgramOne:
public class ProgramOne
{
public static void main (String[ ] args) {
StarTurtle turtle1 = new StarTurtle();
int result = turtle1.StartTurtle(5);
}
}
Here is the code of StarTurtle:
public class StarTurtle
{
private int points;
public int StartTurtle(int x)
{
points = x;
Turtle sue;
sue = new Turtle();
sue.paint (90, 40);
}
}
(The turtle method you see is from two other classes that I have not pasted here for the sake of brevity. These classes are found in the http://www.cs.ccsu.edu/~jones/book.htm manual)
The code only compiles, and there is no option to execute. However, there is no option to execute void main (String[ ] args), which there should be to execute the main class. Does anyone know what is the cause of this? I am assuming that there is a problem in the code itself. The StarTurtle class does execute, but the main class ProgramOne does not, which leads me to believe that the problem lies in the ProgramOne class.
When I mean "option to execute", I am referring to this BlueJ functionality:
When you call the main method from the class ProgramOne, you have created an instance of StarTurtle turtle1. But when you assign value in result variable by calling turtle1.StartTurtle(5) method, nothing is stored in that variable. The problem is that you have issue in this function in your StarTurtle class. You have defined public int StartTurtle(int x) function as return type but actually it is not returning any thing. Therefore, you need to add a return statement on that block of code.
public class StarTurtle {
private int points;
public int StartTurtle(int x){
points = x;
Turtle sue;
sue = new Turtle();
sue.paint (90, 40);
return points;
}
}
However, on the other hand, your class and functions are incorrect though they are working. You classes should be like this.
public class ProgramOne{
public static void main (String[ ] args) {
StarTurtle turtle1 = new StarTurtle();
turtle1.StartTurtle();
}
}
public class StarTurtle {
//Void type of method instead of previous return type
public void StartTurtle(){
Turtle sue;
sue = new Turtle();
sue.paint (900, 550);
}
}

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