Is there any function in java that lets you jump to another method?
This is an example how it should work:
if (boolean expression(){
jump to public void something;
if (boolean expression) {
jump to public void something2;
} else{
jump to public void 3;
}
This is needed for a program that checks 3 numbers, and they have different methods linked to them.
If by jump, you mean calling a method:
if (boolean expression(){
something();
if (boolean expression(){
something2();
}
else{
something3();
}
Simply invoke it, in your example
if (boolean expression(){
something();
} else if (boolean expression(){
something2();
} else{
something3();
}
instead of jump to public void something just call something()
There is no syntax called "jump to" although you can easily call a method by firstly making a method.
public void myMethod(){
// do something
}
now when you have done this, you call it from another method by invoking it's name myMethod();. You might know that a method can either return a variable or return nothing (void) if you give it a return-type you MUST return a variable with the same type as your method.
For example:
public int oneplusone(){
int integer = 1 + 1;
return integer;
}
and a void would be like this:
public void oneplusone(){
int integer = 1 + 1;
System.out.println(integer);
}
When you've specified your method you need to call it by invoking its name from another place in your program. Final example:
public class Snippet(){
public static void main(String args[]){ // THIS IS THE MAIN METHOD OF YOUR PROGRAM!
Snippet snippet = new Snippet();
System.out.println(snippet.oneplusone());
}
public int oneplusone(){
int integer = 1 + 1;
return integer;
}
}
I suggest you should check out thenewboston java tutorials explaning java for beginners. Good luck!
if you have the mothod call in the class just call the method like
something(int i);
if your method is in another class make sure you have an object of that class if the method isn't static and call your method
Foo foo = new Foo();
foo.something(10);
Related
I have several methods in class Test which have the same code except one specific method call. Is there a possibility to merge these methods together (bellow into function foo) and call foo and tell it which method to call without doing a bigger switch or if/else statement? An important note is that foo is only called from inside the class Test (therefore foo is private) and the function foo itself calls different methods from one class Bar. Class Bar and Test are not in the same inheritance tree.
class Test {
/* ... */
private void foo("Parameter that specifies which method to call from class Bar")
{
/* merged code which was equal */
Bar bar = new Bar();
bar.whichMethod(); // Call the method (from Class Bar) specified in the Parameter
/* merged code which was equal*/
}
/* ... */
}
Sure straight forward I'd add some kind of switch("which Method to call") statement. But is there a better way to do this?
You can pass the method to call as an argument. Let's assume that the method to call has the following signature:
private void m() {...}
You could write:
private void foo(Runnable methodToRun) {
//...
methodToRun.run();
//...
}
and your various foo methods would be like:
private void foo1() { foo(new Runnable() { public void run() { someMethod(); } }); }
With Java 8 you could also pass a lambda or a method reference.
As assylias said, you can use Method References with Java 8.
public void testAdds() {
doTest(this::addOne);
doTest(this::addTwo);
}
private void doTest(Function<Integer,Integer> func) {
System.out.println("Func(41) returns " + func.apply(41));
}
public int addOne(int num) {
return num + 1;
}
public int addTwo(int num) {
return num + 2;
}
I have a question about boolean values in Java. Let's say I have a program like this:
boolean test = false;
...
foo(test)
foo2(test)
foo(Boolean test){
test = true;
}
foo2(Boolean test){
if(test)
//Doesn't go in here
}
I noticed that in foo2, the boolean test does not change and thereby doesn't go into the if statement. How would I go about changing it then? I looked into Boolean values but I couldn't find a function that would "set" test from true to false. If anyone could help me out that would be great.
You're passing the value of a primitive boolean to your function, there is no "reference". So you're only shadowing the value within your foo method. Instead, you might want to use one of the following -
A Holder
public static class BooleanHolder {
public Boolean value;
}
private static void foo(BooleanHolder test) {
test.value = true;
}
private static void foo2(BooleanHolder test) {
if (test.value)
System.out.println("In test");
else
System.out.println("in else");
}
public static void main(String[] args) {
BooleanHolder test = new BooleanHolder();
test.value = false;
foo(test);
foo2(test);
}
Which outputs "In test".
Or, by using a
member variable
private boolean value = false;
public void foo() {
this.value = true;
}
public void foo2() {
if (this.value)
System.out.println("In test");
else
System.out.println("in else");
}
public static void main(String[] args) {
BooleanQuestion b = new BooleanQuestion();
b.foo();
b.foo2();
}
Which, also outputs "In test".
You named your parameter the same as an instance variable. Here, the parameter is the one referenced, not the instance variable. This is called "shadowing", where the simple name test as a parameter name shadows the instance variable also called test.
In foo, you changed the parameter test to true, not the instance variable test, which was unchanged. That explains why it doesn't go into the if block in foo2.
To assign the value, get rid of the parameter on foo, or use this.test to reference the instance variable.
this.test = true;
and
if (this.test)
You need to be aware that:
In Java, arguments are pass-by-value.
Boolean, the wrapper type of boolean, is immutable.
Because of 1 and 2, you have no way to change the state of the Boolean pass in the method.
You mostly have 2 choice:
Choice 1: Have a mutable holder for boolean like:
class BooleanHolder {
public boolean value; // better make getter/setter/ctor for this, just to demonstrate
}
so in your code it should look like:
void foo(BooleanHolder test) {
test.value=true;
}
Choice 2: A more reasonable choice: return the value from your method:
boolean foo(boolean test) {
return true; // or you may do something else base on test or other states
}
the caller should use it like:
boolean value= false;
value = foo(value);
foo2(value);
This approach is preferrable as it fit better with normal Java coding practices, and by the method signature it gives hint to the caller that it is going to return you a new value base on your input
Here is a good explanation.
http://www.javadude.com/articles/passbyvalue.htm
Java has pointers, and the value of the pointer is passed in. There's
no way to actually pass an object itself as a parameter. You can only
pass a pointer (value) to an object.
And my solution
public static class MutableBoolean {
public boolean value;
public MutableBoolean(boolean value) {
this.value = value;
}
}
usage:
MutableBoolean needStop = new MutableBoolean(false);
call( new Listener(needStop){
void onCallback(){
needStop.value = true;
}
})
Your foo method changed the value of test to true. It looks like what you want is to use instance variables for each function.
boolean test = false;
...
foo(test)
foo2(test)
foo(Boolean test){
this.test = true;
}
foo2(Boolean test){
if(this.test)
//Doesn't go in here
}
This way, your method only changes the value of test inside of that method, but your public test parameter stays with a false value.
class FishingHour
{
public static void main(String args[])
{
public void fishing(){
int totalHoursFishing = 0;
int hoursAllowedFishing = 4;
for(int i=1;i<25;++i)
{
totalHoursFishing = ++totalHoursFishing;
if(hoursAllowedFishing>totalHoursFishing)
break;
System.out.println("Fishing for hours"+i+".");
}
}
}
}
hey guys....i'm just a starter in java language.....
my problem is, that this program is not compiling......& giving me "Illegal start of an Expression" error.......can any'one help me....??/
You have your method fishing() inside the main() method. Methods don't nest that way.
you can not write one method inside another another method.Java does not support nested methods.Move your fishing() outside the main method.
basic structure
class x
{
public static void main(String args[])
{
//codes
}
public void method()
{
//codes
}
}
There is a method inside a method.
you can't do this
fishing() is inside main(). you can't have nested method.
You can not have a method inside another one in Java. So you must put fishing() method outside main() method. For example put it above the main() method in your class.
Methods cannot be nested! main() is a special type of method from which the program starts. Separate fishing() method.
public class NewClassa {
public void fishing(){
int totalHoursFishing = 0;
int hoursAllowedFishing = 4;
for(int i=1;i<25;++i)
{
totalHoursFishing = ++totalHoursFishing;
if(hoursAllowedFishing>totalHoursFishing)
break;
System.out.println("Fishing for hours"+i+".");
}
}
public static void main(String args[])
{
NewClassa classa=new NewClassa();
classa.fishing();
}
}
main is a function and you have written a new function inside main function that was the error.
any way the code is note correct because the if condition is satisfied in the first loop itself and it control goes out of the loop.
break means stop looping
use continue then it will skip the current iteration and move to the next iteration
It is not the correct way to declare a method inside another instead go for method calling and declared outside the main() but inside your class "FishingHour"...
I want to make an if statement that checks to see which method made the call to a secondary method.
I will write what i want in pseudo code so you can see what I mean.
public static void methodOne() {
methodToCall();
}
public static void methodTwo() {
methodToCall();
}
public static void methodThree() {
methodToCall();
}
public static void methodToCall() {
if (methodOne made the call == true) {
execute this
} else if (methodTwo made the call == true){
execute this
} else if (methodThree made the call == true){
execute this
} else {
System.out.println("How did you get here?");
}
}
That's about the gist of it. I want a simple check to see which method made the call so I can choose which operation is relevant to the call.
Is this possible?
If it is not possible, is there a work around?
This is called 'state orientation', and it was debated extensively in the 1970s, possibly even the 1960s. The conclusion was that if you need to know this sort of thing you are already doing something seriously wrong, by introducing a two-way dependency into the code. What happens for example when you add another caller?
Use three short methods, instead of combining the logic of three short methods into one larger method. Once the short methods are created Just call the appropriate method from each calling method.
public static void methodOne() {
methodToCall1();
}
public static void methodTwo() {
methodToCall2();
}
public static void methodThree() {
methodToCall3();
}
public static void methodToCall1() {
int x = 0;
x = x - 3; //some custom logic to prep argument
commonLogic(x);
}
public static void methodToCall2() {
//Method 2 logic
int x = 0;
x = x + 3; //some custom logic to prep argument
commonLogic(x);
}
public static void methodToCall3() {
//Method 3 logic
int x = 0;
x = x * 3; //some custom logic to prep argument
commonLogic(x);
}
public static void commonLogic(int arg1){
//peform common logic
}
If these three methods would contain duplicate code, abstract the duplicate code into another method then call that method from within each of the smaller methods. The idea is to prepare the arguments to call the common function in each of the three smaller functions, then call the common function with those arguments.
A great deal of the abstraction afforded by methods comes from the fact that they do not need to know who is calling them, so the answer to your question is "no". It does not mean that you cannot make it work, though: make the callers pass some sort of a token (say, an enum value) identifying themselves to the callee. This would let you dispatch on that identity inside your method's implementation:
enum CallerContext {CALLER1, CALLER2, CALLER3};
...
public static void methodToCall(CallerContext context) {
...
}
This is not the most Object-Oriented way of doing things, however: very often, a better approach would be letting the callers supply the logic to be executed, rather than supplying a token identifies that logic. See Visitor Pattern for details on that approach.
You can do it by examining the call stack via Thread.getStackTrace():
public static void methodToCall(Action action) {
String callingMethod = Thread.currentThread().getStackTrace()[2].getMethodName();
if (callingMethod.equals("methodOne")) {
execute this0
} else if (callingMethod.equals("methodTwo")) {
execute this
} else if (callingMethod.equals("methodThree")) {
execute this
} else {
System.out.println("How did you get here?");
}
}
but you shouldn't - it's a bit anti-OO. Instead, change your method signature to something like this:
public enum Action {ONE, TWO, THREE}
public static void methodToCall(Action action) {
if (action == ONE) {
execute this
} else if (action == TWO) {
execute this
} else if (action == THREE) {
execute this
} else {
System.out.println("How did you get here?");
}
}
If you end up using an enum, then make sure to take advantage of the fact that enums in Java are no less than singleton instances of classes. Therefore you can declare the method as abstract in the enum definition and then override it in each instance, instead of passing the enum as a paramater to some method defined outside of the enum's context.
So it would look something like:
enum Method {
Mode1 {
#Override
void call() {
// do stuff
}
}, Mode2 {
#Override
void call() {
// do stuff differently
}
}, Mode3 {
#Override
void call() {
// do stuff even more differently
}
};
abstract void call();
}
And then you either don't need your wrapping methods, or, if they were supposed to do anything more, you write:
public static void methodOne() {
// some code
Method.Mode1.call();
// some code
}
I have the following method that returns void and I need to use it in another method that also returns void.
Can I do the following?
public void doSomething(){}
public void myMethod()
{
return doSomething();
}
Thanks for all your comments, but let me be more specific
I only doSomething if something happens, otherwise I do other things
public void doSomething(){}
public void myMethod()
{
for(...)
if(somethingHappens)
{
doSomething();
return;
}
doOtherStuff();
}
Instead of the code above, can I just write return doSomething(); inside the if statement?
No, just do this:
public void doSomething() { }
public void myMethod()
{
doSomething();
}
or in the second case:
public void doSomething() { }
public void myMethod()
{
// ...
if (somethingHappens)
{
doSomething();
return;
}
// ...
}
"Returning void" means returning nothing. If you would like to "jump" out of myMethod's body, use return; The compiler does not allow writing return void; ("illegal start of expression") or return doSomething(); ("cannot return a value from method whose result type is void"). I understand it seems logical to return "void" or the "void result" of a method call, but such a code would be misleading. I mean most programmers who read something like return doSomething(); would think there is something to return.
void functions don't/can't return anything as such. Simply call the function.
No, returns are unnecessary in Java void functione. Instead, do this:
public void myMethod(){
doSomething();
}
You could put a return after doSomething() if you wanted, but as I said it'd be unnecessary.
You either have to just use doSoemthing like the others have pointed out OR
public (insert data type like int, double, string, etc) myMethod()
{
return doSomething();
}
If do something returns an int
// if you wanted to take 2 numbers and add them
public void myMethod()
{
valueOfX+Y = doSomething();
}
public int doSomething()
{
x = 2;
y = 2;
return X+Y;
}
hope that clears it up
If
the condition (somethingHappens) actually depends on what doSomething() did
and doSomething() is a method you can modify
then you should consider making it return the boolean (or any suitable type) value which tells the callee method if it happened or not.
Code would then look somewhat like this:
public boolean doSomething() {
// internal working
if (internalCondition) {
// something done here
return true;
}
// not done ;
return false;
}
public void myMethod()
{
for(...)
if (doSomething())
{
return;
}
// didn't hit 'doSomething() == true'
doOtherStuff();
}