2

I'm having trouble (in Java) trying to figure out how to use variables that are returned from one method and then calling another method with those returned variables. Here's what I have:

public static void main(String[] args) {
    sortFile(args[0]); // this returns 3 variables, nWords, nSyllables, nSentences
    getFRE(nWords, nSyllables, nSentences); // these "cannot be resolved to a variable"
}

Is what I'm trying to do not possible? I'm sure it's something really simple. Thanks

Freek de Bruijn
  • 3,552
  • 2
  • 22
  • 28
user3405010
  • 21
  • 1
  • 4
  • 1
    Can you please mention the language? – tod May 06 '14 at 11:40
  • A method can return only one value, tag the language – Marco Acierno May 06 '14 at 11:41
  • Can we see the code for sortFile? In general to save the result of a method call you have to assign it to a variable in local scope: int words = sortFile(...);. You cannot trivially return three variables from a method though. You probably want to use a class to store the results. – gandaliter May 06 '14 at 11:42
  • this is the code for sortFile [link](http://gyazo.com/1a1d4f395afa6e75bc3a5f5250d1124c) – user3405010 May 06 '14 at 11:48
  • Would you mind closing this question? – Aaditya Gavandalkar Dec 28 '15 at 09:17
  • I think this question is a duplicate of http://stackoverflow.com/questions/7470861/return-multiple-values-from-a-java-method-why-no-n-tuple-objects and has very good answers there (especially: http://stackoverflow.com/a/7471030/1694043). The question is also very similar to http://stackoverflow.com/questions/457629/how-to-return-multiple-objects-from-a-java-method and http://stackoverflow.com/questions/16609269/best-practice-for-returning-multiple-values-in-java. – Freek de Bruijn Dec 30 '15 at 22:35

11 Answers11

4

You should assign the returned value to a local variable and then use that in your next method.

Marc Deleuran
  • 344
  • 2
  • 6
2

Approach 1:

You can also look at JavaTuples library that may suit your need and provide a quite elegant solution. Using a Triplet

More details on this can be found here

Approach 2:

Another approach would be to encapsulate all the three values under a single object of a wrapper class as suggested by others. and then return it as a result of first method call. Which later can be passed to second method as a single argument like:

// assuming all three variables are integers for example
// can be used for other variable types too

    private class valueHolder{
          private final int nWords,nSyllables, nSentences;
          public valueHolder(int nWords, int nSyllables, int nSentences){
                  this.nWords = nWords;
                  this.nSyllables = nSyllables;
                  this.nSentences = nSentences;
          }
           public final int getNWords(){
                 return nWords;
           }
           public final int getNSentences(){
                 return nSentences;
           }
           public final int getNSyllables(){
                 return nSyllables;
           }
    }

Object of the above class can now be used like (second method definition change would be required):

public static void main(String[] args) {
    valueHolder values = sortFile(args[0]); // this returns 3 variables, nWords, nSyllables, nSentences
    getFRE(values); // these "cannot be resolved to a variable"
}

More details in SO question here

Community
  • 1
  • 1
  • A third approach could be to add three fields (`nWords`, `nSyllables`, and `nSentences`) to the class where the `sortFile` and `getFRE` methods are defined. (As an aside: I would consider making these methods non-static and creating an instance of the class in the main method to call the methods on; this way the fields could be non-static as well.) – Freek de Bruijn Dec 30 '15 at 22:44
1

The problem in your case is that you want to return three values from sortFile(), However you cannot return more than one value from a method that returns an int. One way to solve this problem is to instead of returning an int from sortFile(), return an int array with those three values,

public static void main(String[] args) {
    int [] myArray = sortFile(args[0]); // this returns an int array with 3 variables, nWords, nSyllables, nSentences
    getFRE(myArray); 
}


You also need to change getFre() so that it accepts an array as a parameter.
However, as some other people has mentioned, wrapping your values in a class is another option:

 public class Words {

    // declare variables;
    private int nWords, nSyllables, nSentences;


    // getters and setters
    public void setnWords(int nWords) {
        this.nWords = nWords;
    }

    public void setnSyllables(int nSyllables) {
        this.nSyllables = nSyllables;
    }

    public void setnSentences(int nSentences) {
        this.nSentences = nSentences;
    }



    public int getnWords() {
        return nWords;
    }

    public int getnSyllables() {
        return nSyllables;
    }

    public int getnSentences() {
        return nSentences;
    }
}


Make sortFile() return an instance of Words and make your getFre() accept an instance of Words as a parameter. Your main class would look like :

public static void main(String[] args) {
       Words myWords = sortFile(args[0]); // this returns an instance of the Words class
        getFRE(myWords); 
    }
corroleaus
  • 41
  • 2
0

A method can only return a single object.

If you want to return multiple values, you could create a class with a property for each value.

Rik
  • 28,507
  • 14
  • 48
  • 67
0

There are two main problems with your code:

  1. You cannot return more than one value from a method - if you need all three, you may want to embed them in a class, and return an object of that class's type

  2. When a method returns a variable, it doesn't just appear in your function - rather, you need to use a line such as Object o = foo(bar) to store your value and subsequently use it.

Invictus
  • 181
  • 9
0

In Java method return a single varible/object. You may put your three sting variable in a Array and return that array. Or you can use A object to be returned with same properties.

like

public String[] sortFile(args[0]){

String[] array;
//your logic goes here
  return array
}
Macrosoft-Dev
  • 2,195
  • 1
  • 12
  • 15
0

First you need to check what is the return type of sortFile(args[0]) method and store the return value in the same data type(Any method can return only one value or Object at a time but that returned Object can hold multiples value within it.).So use appropriate data structure(like Array, List..etc as return type) or any other Object to store these three values and return from that sortFile(args[0]) function. Finally pass that variable in your next method call getFRE(returnedObject).

Kanahaiya
  • 406
  • 2
  • 11
0

in your code the variables returned from ,yoour methods are not stores anywhere so your calling the other methods with a non existing variables try regrouping the in one structure a collection or a class and make your methode return that type of structure example :

public class ReturnedWords{

   int nWords,Sylables ,nSentences;


public int getW(){

 return nWords;
}
 public int getS(){

 return nSylabelles;
}

public int getSe(){



return nWords;
} //yyou get it by now and  then do



public static void main(String[] args){

ReturnedWords r = sort(arg[0]);

getFRE(r.getN(),r.getS(),r.getSe());

}



}
Méhdi Màick
  • 157
  • 3
  • 7
0

Approaches mentioned by others will definitely work.

Another approach is, you can use static variables also as shown in below example

public class Test
{
    static int i=0;
    static int j=0;
    static int k=0;

    public static void main(String[] args) {
        update();
        System.out.println(i);
        System.out.println(j);
        System.out.println(k);          
    }

    public static void  update() {
        i++;
        j++;
        k++;
    }
}
Ravindra Devadiga
  • 692
  • 1
  • 6
  • 14
0

If all your code is inside one class file, transform the local variables nWords, nSyllables and nSentences into global. So, they will be visible from both methods.

static int nWords, nSyllables, nSentences;

public static void sortFile(String fileName) {
    //do not declare nWords, nSyllables, nSentences here, just modify them, as they are global
    //rest of the code goes normally
}

public static void getFRE() { //no need for arguments, as they are now global
    //no change, just set nWords, nSyllables, nSentences as needed
}

public static void main(String[] args) {
    sortFile(args[0]); //will set the global variables
    getFRE(); //will get the global variables
}

You may think that what I am proposing is a bad practice (and it is!), but, as your counting program does not seem to be a ever-evolving project, it will make it work with minimal intervention.

Eduardo Poço
  • 2,819
  • 1
  • 19
  • 27
0

You can return a Map as:

Map<String,Integer> nMap = new HashMap<String, Integer>();
nMap.put("nWords", 1);
nMap.put("nSyllables", 1);
nMap.put("nSentences", 1);

from sortFile() mehod

Map<String,Integer> nMap = sortFile(args[0]);

and can use as:

getFRE(nMap); // or
getFRE(nMap.get("nWords"), nMap.get("nSyllables"), nMap.get("nSentences"));

depends on your getFRE() method implementation

Shekhar Khairnar
  • 2,643
  • 3
  • 26
  • 44