Error of static and non-static - java

I'm confused between when to use public static void xxx() and public void xxx(). The error I'm getting is in the main class.
generateRandomNumber();
The error : (error: non-static method generateRandomNumber() cannot be
referenced from a static context)
getUserInput();
he error : (error: non-static method getUserInput() cannot be
referenced from a static context)
getResult();
The error : (error: non-static method getResult() cannot be referenced
from a static context)
public class HighLowGame {
int randomNumber;
int guess;
public void generateRandomNumber(){
randomNumber = (0+(int)(Math.random() * ((0 - 99) + 1)));
}
public void getUserInput(){
guess = Integer.parseInt(JOptionPane.showInputDialog(
null,
"Plaese input"));
}
public String getResult(){
if(randomNumber<guess){
return "Your number is bigger than magic number";
}
else if (randomNumber>guess) {
return "Your number is smaller than magic number";
}
else {
return "You are correct! "+randomNumber;
}
}
public static void main(String[] args){
generateRandomNumber();
getUserInput();
getResult();
}
}

you cannot access a non-static instance method/variable from static context directly. you will need an instance of your class to access them .
public static void main(String[] args){
HighLowGame ref = new HighLowGame ();
ref. generateRandomNumber();
ref.getUserInput();
ref.getResult();
}
or you can make all these methods static and access them directly. make methods static when you think all the instances of that class should share the date/methods.

You're attempting to call a method which needs an instance of HighLowGame to work.
Change your main method to:-
public static void main(String[] args){
HighLowGame game = new HighLowGame();
game.generateRandomNumber();
game.getUserInput();
game.getResult();
}

You have to call the Methods on an instance of HighLowGame.
public static void main(String[] args){
HighLowGame game = new HighLowGame();
game.generateRandomNumber();
game.getUserInput();
game.getResult();
}
or declare your Methods static like
public static void generateRandomNumber(){ ..}

Related

How do I call a method that has a variable passed through it?

I'm trying to call a method from within another method. I'm understanding this simply enough, until one of those methods needs a variable carried through, and then nothing I try works.
I know that I could do this in one method, but my coursework needs me to lay it out in such a way. Why doesn't this work?
public class test2 {
public static void testMethod() {
int randomNumber = 1;
}
public static void anotherTestMethod(int randomNumber) {
System.out.println(randomNumber);
}
public static void main(String[] args) {
anotherTestMethod();
}
}
You are calling a method that has an int parameter in its signature. You should pass that parameter when calling the method. I think you are trying to use a global variable, in that case, you should declare it outside any method, as a part of the class.
public class test2 {
public static int testMethod() {
int randomNumber = 1;
return randomNumber;
}
public static void anotherTestMethod() {
System.out.println(testMethod());
}
public static void main(String[] args) {
anotherTestMethod();
}
}

How to call a behavioral method from main method in java?

I have a non static method abc() in the class that contains main() method. Now how to call this method abc() from main. Can i create an instance of the class in the same class?
public class A
{
public static void main(String[] args)
{
//how to call abc() here?
}
private int abc()
{
return 2;
}
}
You have to instanciate current class, use this code:
public static void main(String[] args)
{
A a = new A();
int value = a.abc();
}

Nesting calls to static methods

I want to do something like below, but it does not work. My objective is to be able to nest function calls to static helper classes to get more brevity.
public class StaticHelper {
public static Class<StaticHelper> doSomthing() {
System.out.println("I just did something !!");
return StaticHelper.class;
}
public static Class<StaticHelper> doSomthingElse() {
System.out.println("I just did something else !!");
return StaticHelper.class;
}
public static void main(String[] args) {
// Does not compiles
StaticHelper.doSomthing().doSomthingElse();
}
}
Is this possible? If so a simple example as above will be very helpful.
I guess you want something like this.
public class StaticHelper {
private final static StaticHelper INSTANCE = new StaticHelper();
public static StaticHelper doSomthing(){
System.out.println("I just did something !!");
return INSTANCE;
}
public static StaticHelper doSomthingElse(){
System.out.println("I just did something else !!");
return INSTANCE;
}
public static void main(String[] args) {
StaticHelper.doSomthing().doSomthingElse();
}
}
or another way
public class StaticHelper {
public static SomeClass doSomthing(){
return new SomeClass().doSomthing();
}
public static SomeClass doSomthingElse(){
return new SomeClass().doSomthingElse();
}
public static void main(String[] args) {
StaticHelper.doSomthing().doSomthingElse();
}
private static class SomeClass {
public SomeClass doSomthing(){
System.out.println("I just did something !!");
return this;
}
public SomeClass doSomthingElse(){
System.out.println("I just did something else !!");
return this;
}
}
}
That is not possible, but using static imports is.
public class StaticHelper {
public static void doSomething() {
System.out.println("I just did something !!");
}
public static void doSomethingElse() {
System.out.println("I just did something else !!");
}
}
in another class:
import static StaticHelper.*;
class Other {
public static void main(String[] args) {
doSomething(); // calls static methods from StaticHelper
doSomethingElse();
}
}
or - if the methods are logically connected - you can have one static factory method and the rest are instance methods:
public class StaticHelper {
public static void beginDoingSomething() {
// static factory method - you can pass parameters to it if needed
System.out.println("I just did something !!");
return new StaticHelper();
// if needed, initialize the instance with the parameters
}
public StaticHelper andDoSomethingElse() {
// instance method
// can use the instance parameters (passed to the constructor in the static factory method)
// or use parameters passed to this method
System.out.println("I just did something else !!");
return this;
// returns this for chaining
}
}
in another class:
import static StaticHelper.*;
class Other {
public static void main(String[] args) {
doSomething().andDoSomethingElse().andDoSomethingElse();
}
}
If you name the methods nicely, you can form a sentence:
validate(object).checkEmail().checkName().checkTelephoneStartsWith("+11");
where validate(object) is a static factory method constructing a new validator instance for the given object.

Declaration for an array being called into main from a method (Java)

I am fairly new to java, and am having what I assume is a simple problem with my program.
For the method arrayTest2, I cannot import it into main due to an error on compilation:
"Cannot find symbol, symbol: variable dataStorage".
I have tried also tried the declarations:
arrayTest2(dataStorage[][])
and
arrayTest2(dataStorage[5][5])`
but they don't work.
Any help would be greatly appreciated.
Cheers
import io.*;
public class TrialArray
{
public static void main(String [] args)
{
arrayTest();
arrayTest2(dataStorage);
}
public static void arrayTest()
{
int[][] dataStorage = new int[5][5];
dataStorage[1][2] = 1;
System.out.printf("THIS PART WORKS");
}
public static void arrayTest2(int[][] dataStorage)
{
dataStorage[2][2] = 3;
System.out.printf("THIS DOESNT");
}
}
The problem here is the scope: Something defined in one function is not visible in another. What you will normally do to solve this is to return the value. Something like this:
import io.*;
public class TrialArray
{
public static void main(String [] args)
{
int[][] dataStorage = arrayTest();
arrayTest2(dataStorage);
}
public static int[][] arrayTest()
{
int[][] dataStorage = new int[5][5];
dataStorage[1][2] = 1;
System.out.printf("THIS PART WORKS");
return dataStorage;
}
public static void arrayTest2(int[][] dataStorage)
{
dataStorage[2][2] = 3;
System.out.printf("THIS DOESNT");
}
}
Alternatively you could have your dataStorage field as a global variable, this is however potentially very confusing. To do that you'd define
public class TrialArray
{
private static int[][] dataStorage;
// ...
public static void arrayTest() {
dataStorage = new int[5][5];
dataStorage[1][2] = 1;
System.out.printf("THIS PART WORKS");
}
// ...
}
on this line
arrayTest2(dataStorage);
You are passing parameter to method, that has one argument "dataStorage", but you don't declare it.
You try to pass dataStorage to your arrayTest-function, but dataStorage is not a field of the class, neither is it a local variable of main (aka dataStorage does not exist in main).
public static void main(String [] args) {
arrayTest();
arrayTest2(dataStorage); //<------- What is dataStorage?
}
Here is a little tutorial on variable scopes in Java. You probably want to return the array you created in arrayTest() and use it, but I am just guessing what you want to do.
You cant access variables in declared inside other methods.
To make it work, you would have to do this:
public class TrialArray
{
int[][] dataStorage;
public static void main(String [] args)
{
dataStorage = new int[5][5];
arrayTest();
arrayTest2(dataStorage);
}
public static void arrayTest()
{
dataStorage[1][2] = 1;
System.out.printf("THIS PART WORKS");
}
public static void arrayTest2(int[][] dataStorage)
{
dataStorage[2][2] = 3;
System.out.printf("THIS DOESNT");
}
}

Variable Accessible by All Methods Without Parameters?

Is it possible to have a "global" variable, i.e., "balance", which all methods can access without parameters?
Something like:
public static void main(String[] args{
makevariablehere
}
Could be called in another method:
public static int someMethod() {
variable = newVariable;
}
You can define it as a static field on the class. See the example below, which stores the number of args passed to the main method in a static field, so that it may be returned by the getNumberOfArgs() method.
public class MyClass {
private static int argCount;
public static void main(String[] args) {
argCount = args.length;
}
public static int getNumberOfArgs() {
return argCount;
}
}

Categories

Resources