error on calling static method from void java - 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.

Related

Trying to print a method using another method

Not sure where I'm going wrong with this. I've asked someone in my class and they said there should be an argument with "toonRijSterren". when I do this I just get more errors, could someone have a look and tell me where I'm going wrong?
public static void main(String[] args) {
int aantal = 0;
toonRijSterren(aantal);
toonSterrenVierkant(aantal);
}
public static void toonRijSterren(int mpAantal) {
while (mpAantal < 6) {
System.out.print(" * ");
mpAantal++;
}
}
public static void toonSterrenVierkant(int mpAantal) {
for (int mpAatal = 0; mpAantal < 6; mpAantal++) {
System.out.println(toonRijSterren());
}
}
ther error line is in the brackets of the last toonRijSterren());
toonRijSterren is void method which means it does not return any value and therefore you can not put it inside System.out.println() or you can not assign it to some variable.
toonRijSterren expects an int argument which you have missed while calling it.
Given below is an example of how you should call toonRijSterren:
public static void toonSterrenVierkant(int mpAantal) {
for (int mpAatal = 0; mpAatal < 6; mpAatal++) {
toonRijSterren(mpAantal);
}
}
You are not passing the argument when you call your method.
Try this:
System.out.println(toonRijSterren(mpAatal));
First of all, your function toonRijSterren takes an int type parameter (according to its declaration), so you need to pass to it another argument. For example:
toonRijSterren(mpAantal)
Second, the function toonRijSterren returns void. That means, it just does an operation (in this case, printing) without returning anything. What you're trying to do is to use its return value (which doesn't exist) as an argument to System.out.println, which causes an error (because println expects an argument of some type).
You could achieve what I think you're trying to do with the line:
toonRijSterren(mpAantal);.
The function itself prints the values, so the println here is unnecessary and causes an error.
You are missing the parameter in your toonSterrenVierkant() function where you calling toonRijSterren.
Here is the corrected version of your code:
public static void toonSterrenVierkant(int mpAantal) {
for (; mpAantal < 6; mpAantal++) {
toonRijSterren(mpAatal);
}
}
As your methed toonSterrenVierkant(int mpAantal) has a int parameter, you must pass an int value as an argument in the last toonRijSterren(). For example, replace the line System.out.println(toonRijSterren()); with System.out.println(toonRijSterren(1));

How to use object from main method in another method

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

Using an array as a parameter

I do not understand the details of using an array as a parameter:
I have created an int array and a method and I do not understand why it's possible to rename the parameter as seen below from "note" to "veraenderung".
How does Java deal with parameters? Do I need a parameter even if I call the method(note)?
public class ArrayParameter {
public static void main(String[] args) {
int[] note = {3,2,1,4,5}; //Array
int[] note2 = {3,2,1,4,5};
korrektur(note);
korrektur2(note2);
}
//Der Methode "korrektur" wird der int Array (note) übergeben!
public static void korrektur (int note[]) {
for (int i = 0; i<note.length; i++) {
//Sobald die for Schleife aufgerufen wird, werden die jeweiligen Werte um -1 reduziert
note[i]-=1;
System.out.println(note[i]);
}
}
//int "veraenderung" ist ein Parameter
public static void korrektur2 (int veraenderung[]) {
for (int i = 0; i<veraenderung.length; i++) {
//Sobald die for Schleife aufgerufen wird, werden die jeweiligen Werte um -1 reduziert
veraenderung[i]-=1;
System.out.println(veraenderung[i]);
}
}
}
i do not understand why it is possible to rename the parameter
korrektur and korrektur2 are just 2 different methods each of them having 2 independent signatures. They are not related whatsoever (even if the programmer can name them alike, just as you did);
The name of the parameters are just local names useful in the method block;
How do java deal with parameter? Do i need a parameter even if i call the method(note)?
Those methods parameters are mandatory ones. Hence you need to insert them in your method call.
I will try to break it down as small as possible for you to understand :)...
When you creating the method. example: public static void korrektur2 (int veraenderung[]) the int veraenderung[] can be named whatever you want...the main thing is that you put the "int []" somewhere within the brackets so that you tell java that "hey my method take an integer array".
The name veraenderung itself is only used locally (within that method) as a reference to tell java whatever you parse into that method will act.
For example when you call the method above and said korrektur(note); . note was declared as an array before, so when you put 'note' inside the method korrektur it is the same as replacing veraenderung with note. In other words java replaces your local variable with the one you passed into the method.
And to answer your question....for now...since you created the method which takes an integer array...YES you must always "put an integer array inside" it when calling the method. I.e. every time you call the method korrektur2 or korrekturand you do not put an integer array inside it, Java would be like "hey I was created to take an integer array and do stuff with it...why are you leaving me empty ?!?!?"
I hope this solved your questions :)
If you have seen the .class file, you'll find the parameters are the same.
you should understand the conception 'vars Scope' (may be this). Parameter 'paramArrayOfInt' have the influence korrektur(), then it be destroied. In next method ,it just new one. It's my understanding. May be wrong, welcome to discuss.
public class ArrayParameter
{
public static void main(String[] paramArrayOfString)
{
int[] arrayOfInt1 = { 3, 2, 1, 4, 5 };
int[] arrayOfInt2 = { 3, 2, 1, 4, 5 };
korrektur(arrayOfInt1);
korrektur2(arrayOfInt2);
}
public static void korrektur(int[] paramArrayOfInt)
{
for (int i = 0; i < paramArrayOfInt.length; i++)
{
paramArrayOfInt[i] -= 1;
System.out.println(paramArrayOfInt[i]);
}
}
public static void korrektur2(int[] paramArrayOfInt)
{
for (int i = 0; i < paramArrayOfInt.length; i++)
{
paramArrayOfInt[i] -= 1;
System.out.println(paramArrayOfInt[i]);
}
}
}

Java String function can not be called because it's not static

Let me explain further. I have a String function (called stringReversal) that returns a reversed string, it has no errors in the function. But, when I try to print using System.out.println() from the main function, it gives me the error "Can not make a static reference to the non static method stringReversal (string s) from the type StringReverse".
I tried giving my stringReversal a static modifier, but after doing so, it gave me run time errors.
Here's what my code looks like:
public class StringReverse {
public String stringReversal(String s){
if(s == null){
return null;
}
else if(s.length()% 2 == 0){
int size = s.length();
for(int i =0; i<s.length(); i++){
s.replace(s.charAt(i), s.charAt(size));
size--;
if(i == (s.length()/2) || size==0)
break;
}
}
else{
for(int i =0; i<s.length(); i++){
int size = s.length();
s.replace(s.charAt(i), s.charAt(size));
size--;
if(i == ((s.length()/2) +1) || size==0 )
break;
}
}
return s;
}
public static void main(String[] args) {
String str = "Hello";
String rev = stringReversal(str);
System.out.println();
}
}
You have to instantiate your class to call object members, or you need to make your function static, indicating it's not part of object oriented paradigm
In your case you can do
StringReverse sr = new StringReverse();
String rev = sr.stringReversal("hello");
or declare your method differently
public static String stringReversal(String s)
In fact the class name StringReverse itself does not sound like some kind of object, so the second way is preferred impo
The deeper problem you have is the confusion on how Java handle OO and entrance function in general. Java is primarily an OO language so most of the time everything shall be an object or a member of a object. But when you telling the VM to run some java code, there got to be a place to start, which is the main method. There has to be one main method and it must be under some class, but it really has nothing to do with the class that contains it. Within the main method, you either start your OO life by instantiating objects and invoking their members (method 1) or stay in the spaghetti world for a bit longer, by calling other static members as procedures (method 2).
You have two options:
Keep the method non static and then create an instance of your class to call the method:
public static void main(String[] args) {
String str = "Hello";
StringReverse sr = new StringReverse(); // instance of class
String rev = sr.stringReversal(str);
System.out.println(); // just prints a blank line lol...
}
Make the method static (you should do this):
public static String stringReversal(String s) {
// ...
}
public static void main(String[] args) {
String str = "Hello";
String rev = stringReversal(str);
System.out.println(); // just prints a blank line lol...
}
Either way, you have to fix your "run time errors". You can't get around that. If your method doesn't work, keeping it not static won't make it work either.
By the way, I think you meant to do System.out.println(rev); instead of System.out.println();
For the record, here is how to easily reverse a string (both methods work):
public static String stringReversal(String s) {
StringBuffer reverseString = new StringBuffer();
// reverse the string
for (int i = s.length() - 1; i > -1; i--) {
reverseString.append(s.charAt(i));
}
return reverseString.toString();
}
/* using the reverse() method in the StringBuffer class
instead of reversing the string through iterations */
public static String stringReversal2(String s) {
return new StringBuffer(s).reverse().toString();
}
This is happening because your Main method is static, but the class that it's in is not. In order to call a non-static method, you need to create an instance of the class. Alternatively, the method can be made static, but in order to refer to it you need to include the class name in your call (as if to use the class itself like an object containing the method - see below).
There are three solutions to this problem:
Make an instance of the class and call the method from your object (recommended).
make the method static and use StringReverse.stringReversal().
Make the class AND the method static.

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.

Categories

Resources