How to use object from main method in another method - java

I'm trying to use RandomGrid rGrid in the compareGrids method of my project, however I can't seem to figure out how to do so. I origionally had the RandomGrid constructor outside the main method, but I got a stack overflow error whenever I tried to run it. I have another class very similar to this one with a ButtonGrid constructor outside of the main method and it works fine. Thanks for any help!
public static void main(String[] args) {
new ButtonGrid(WIDTH, LENGTH);
RandomGrid rGrid = new RandomGrid(WIDTH, LENGTH);
}
public int compareGrids() {
String[] args = {};
ButtonGrid.main(args);
int numCorrect = 0;
for (int i = 0; i < WIDTH; i++) {
for (int j = 0; j < LENGTH; j++) {
if (grid[i][j].getBackground() == ButtonGrid.main(rGrid).grid[i][j].getBackground()) {
numCorrect++;
}
}
}
System.out.println(numCorrect);
return numCorrect;
}

Simple answer:
Make compareGrids() static and add arguments
public static int compareGrids(Grid grid1, Grid grid2) {
...
}
This is an entry level question, You may want to consult a simple java tutorial to understand basic class elements and modifiers

To use rGrid in compareGrids it has to be class level variable .
Declare
RandomGrid rGrid = new RandomGrid(WIDTH, LENGTH);
outside main.
It should solve your issue.
Presently scope of rgrid ends as soon as main method finishes
Please paste stack overflow error that you mentioned

Related

Why am I getting "Local variables referenced from an inner class must be final"?

I'm not even sure if this code will do anything even if it works, but I don't know what to do to get rid of the "Local variables referenced from an inner class must be final or effectively final" error message, which shows up on the three lines that start with "fireballRight[i]".
Sprite[] fireballRight = new Sprite[50];
public void fireRight() {
for(int i = 0; i < 50; i++) {
new AnimationTimer() {
public void handle() {
fireballRight[i].setImage("puercosloco/fireballright.png");
rightx++;
fireballRight[i].setPosition(rightx, righty);
fireballRight[i].render(gc, 80, 55);
}
}.start();
}
}
Any guidance would be appreciated, google doesn't seem to be helping me for this one.
You haven't shown all the code, but I suspect that adding:
final int i0 = i;
inside your loop and using i0 instead of i as the index for your arrays should fix the error.
Alternatively, as commented by #James_D, you can also add Sprite sprite = fireballRight[i]; before the anonymous class and use sprite inside the handle method.
Note that the final modifier is optional in this case with Java 8+.
As it says, the var i needs to have the final prefix. Change the code to something like this:-
for(int i = 0; i < 50; i++) {
final int i2 = i;
new AnimationTimer()
{
public void handle()
{
fireballRight[i2].setImage("puercosloco/fireballright.png"); // Use i2 instead of i.
You can do the field private and static.

How to access the local variables outside the method in same class in java

I am doing coding in android studio. I want to access the variable totalCuisine++ outside this method. Also totalCuisines is declared globally in claass i.e int totalCuisines = 0;
It is a part of big program but main problem is here in front of u, rest of all programs are executing successfully
public class CuisinesFilterDialog extends DialogFragment{
int totalCuisines = 0;
ArrayList<CuisinesModel> data = new ArrayList<>();
{
private void updateFilterStats() {
ArrayList allData = new ArrayList();
if(data != null && data.size() > 0){
for(int i=0; i<data.size(); i++){
if(data.get(i).isSelected()) {
allData.add(data.get(i).getName());
totalCuisines++;// I want to access it outside this method
}
}
DataStore.putString(getContext(), ZConstants.SortFilter.KEY_EXTRAS_FILTER_CUISINES,
TextUtils.join(",",allData));
}else{
DataStore.putString(getContext(), ZConstants.SortFilter.KEY_EXTRAS_FILTER_CUISINES,
ZConstants.EMPTY_STRING);
}
dismiss();
}
}
totalCuisines++ is not a variable. It means totalCuisines+1. However, You can access totalCuisines by several ways. The easiest way to declare totalCuisines as public variable. Like,
public int totalCuisines = 0;

non-static method move(int,int) cannot be referenced from a static context [duplicate]

This question already has answers here:
What is the reason behind "non-static method cannot be referenced from a static context"? [duplicate]
(13 answers)
Closed 9 years ago.
When i try to use the move i.e. Slide.move(1,0) i get the error: non-static method move(int,int) cannot be referenced from a static context
This is my code at the moment, which i have no idea whats wrong.
public void move(int row, int col) {
char [][] temp= new char [cells.length][];
for (int i= 0; i< cells.length; i++) {
int destRow = (i+row)%cells.length;
temp[destRow] = new char [cells[i].length];
for (int j= 0; j < cells[i].length; j++)
temp[destRow][(j+col)%cells[i].length] = cells[i][j];
}
cells= temp;
}
}
The error means exactly what it says.
Your move method is not static. It requires an instance of an object to be called, e.g.:
Slide s = new Slide();
s.move(...);
You are calling it, as it says, from a static context, i.e. a place with no this, perhaps another static method or directly via Slide.move(...). You will need to not do that.
These fail:
Slide.move(...); // error: move requires an instance
// and
class Slide {
void move (...) {
...
}
static void method () {
move(...); // error: method is static, there is no instance
}
}
These do not fail:
Slide s = new Slide();
s.move(...);
// or
class Slide {
void move (...) {
...
}
void method () {
move(...);
}
}
// or
class Slide {
static void move (...) {
...
}
static void method () {
move(...);
}
}
So either call it from a non-static context, or make it a static method.
As for recommending somewhere to read more about these things (which you asked in a comment), try the official Java tutorial at http://docs.oracle.com/javase/tutorial/ (take a look at the "Learning the Java Language" trail (in particular: http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html).
As for your output problems, since that's a separate question, you'd want to post a separate question for it.
Well that is because you defined the move method as a non-static method by saying public void to make it static you need to write public static void instead.
Also be aware that variable names are case sensitive, if you write Slide.move() you clearly call upon your Slide class because your variable was named slide.

Loop through array of objects inside the class

I am having some trouble looping through an array with objects, inside the class. I wrote a little demo here so you can follow:
Tank tanks[] = new Tank[2];
tanks[0] = new Tank();
tanks[1] = new Tank();
tanks[0].doStuff(tanks);
doStuff(Tank[] tanks) {
for (int i = 0; i < tanks.length; i++) {
if (tanks[i].equals(this)) continue;
// Do stuff
}
}
So, I have an array with the type Tank. Then I call the method doStuff inside the Tank class. The method takes the array and loops through it. And then I want to do stuff to every tank that is not the current instance of the class. I hope you can make sense out of my code and this description.
The problem is that I get nullPointerException for if (tanks[i].equals(this))
What am I doing wrong here?
That means that tanks[i] is null. (or that your overridden equals() method has a bug)
You need to check for that.
if you want to compare the IDs of your object you can use == instead of .equals()
doStuff(Tank tanks) {
for (int i = 0; i < tanks.length; i++) {
if (tanks[i] == this) {
continue;
}
// Do stuff
}
}
When I run this code:
public class Tank {
public static void main(String[] args) {
Tank tanks[] = new Tank[2];
tanks[0] = new Tank();
tanks[1] = new Tank();
tanks[0].doStuff(tanks);
}
public void doStuff(Tank[] tanks) {
for (int i = 0; i < tanks.length; i++) {
if (tanks[i].equals(this)) continue;
// Do stuff
}
}
}
No error happens. Therefore, you've probably overridden .equals, and that is where the NullPointerException is occurring. The other possibility is that your simple example doesn't accurately reflect where your bug is occurring.

error on calling static method from void java

Need help on calling a method from main class.
I need to call a method, thus I made an object to handle it.
below I quote my main method
public static void main(String[] args) {
// TODO code application logic here
SLRatio sl= new SLRatio();
sl.clustering(apa);
}
and here's the method I need to call
public class SLRatio {
public static String [][]clustering(String[][]apa) {
System.out.println("Cluster 1");
int a = apa.length/3;
String [][] cluster1=new String [a][apa[0].length];
for (int i =0; i<a; i++) {
for (int j=0;j<apa[0].length;j++) {
cluster1 [i][j] = apa[i][j];
}
}
for (int b = 0; b < cluster1.length; b++) {
for (int c = 0; c < cluster1[0].length; c++) {
System.out.print(cluster1[b][c] + "\t");
}
System.out.println("");
}
System.out.println("\n");
return cluster1;
}
}
and I got error message:
"Cannot find symbol,Accessing static method clustering"
What can I do to solve it? I have tried to change the syntax but it didn't work.
Thank you so much.
you didn't define method Allocation() in SLRatio
Note: static method should be called with classname (to avoid confision between instance method and static)
If it is static method, you don't need to call it through instance.
SLRatio .clustering(...);
should be enough.
And it seems you forgot to implement Allocation method.
Another suggestion, java naming convention, method name starts with small case letters.
Do not use static unless you are sure it is appropriate.
This is a popular programming error, partially because eclipse keeps on suggesting to make variables and methods static when they cannot be accessed. But usually, this is not the correct solution. While it fixes the compilation problem, it often breaks the application logic.
Right now, your problem probably is that apa has type String[][], but you are passing a String[] parameter to it. So it cannot be compiled, because there is no method clustering(String[] args).
Seriously, you need to learn more Java basics. Maybe from a book.

Categories

Resources