Home > Enterprise >  Returning the result of another method in a separate method
Returning the result of another method in a separate method

Time:11-27

I have a method (shown below) which works fine. The purpose of this method is to confirm if a specific item is available in a shop, with a return value of true or false.

I have a second method, which returns a description, but I can't see to work out how to get this method to pull through the first method response with 'true' showing as 'Yes' or 'false' showing as 'No'. I'm assuming it is something to do with method calling and string concatenation.

My overall problem pulls through 2 methods, but I wanted to just try and understand how to pull one method first and then I'll hopefully work out the rest!

Method 1

public void isFree()
{
if (sweet.isEmpty()){
System.out.println("True");
}
else {
System.out.println("False");
}
}`

Method 2

public void information()
{
System.out.println (isFree  " this item is available for purchase.");
}

CodePudding user response:

Return type of your first method is void so you are not returning anything, you are just printing Yes or False in new line. To concatanate "True" or "False" to another String you need to return String from isFree method

You may try something like this

public String isFree(){
  return sweet.isEmpty() ? "True" : "False";
}`

public void information(){
 System.out.println (isFree()   " this item is available for purchase.");
}

In second method message doesnt make much sense with False but this is up to you to adjust it

You can also reutrn boolean directly

public boolean isFree() {
   return sweet.isEmpty();
}

Keep in mind that in this case it will be revolved to "true" or "false" and not "True"/"False"

Of course if "true"/"false" is ok in your case you can remove isFree method completly and just use sweet.isEmpty() directly in information

CodePudding user response:

Is there any specific reason to use two methods, rather isEmpty in the collection will return the boolean (true, false) for you and you can directly use the second method removing the first completely.

public void information() {
System.out.println (sweet.isEmpty()  " this item is available for purchase.");

}

CodePudding user response:

You can achieve this from several ways:

  1. Call first isFree from information, and then print the second string. For this, you would have to edit both methods, since you are using println.
public void isFree() {
    sweet.isEmpty() ? System.out.printf("True") : System.out.printf("False");
}

public void information() {
    isFree();
    System.out.printf(" this item is available for purchase.\n");
}
  1. Make isFree return a String.
public String isFree() {
    sweet.isEmpty() ? "True" : "False";
}

public void information() {
    System.out.println(isFree()   " this item is available for purchase.");
}
  • Related