简体   繁体   中英

How do i return 2 values from a single method

import java.util.Scanner;

public class fmax
{
public static void main(String[] args)
{
int max;
max = maxnum();
System.out.println("The max number is: " + max);
}

public static int maxnum()
{
int max = 0, element = 0;
Scanner keyboard = new Scanner(System.in);
int []fmax = new int[10];

  for(int i = 0; i < fmax.length; i++)
  {
  System.out.print("Enter number " + (i+1) + ":");
  fmax[i] = keyboard.nextInt();

     if(fmax[i] > max)
     {
     max = fmax[i];
     element = i; //the variable i want to be returned
     }

  }
  return max;
  }
}

Okay, I am able to return a max value in this program, however, I would like to return the value of the element/index assigned to the max value that I return. How would i go about doing that?

to return two values pack it into some object and return it ;)

public class ReturnedObject{
    private Object val1;
    private Object val2;
    //getters setters
}

public ReturnedObject yourMethod(){
    ReturnedObject returnedObject = new ReturnedObject();
    returnedObject.setVal1("yourVal1");
    returnedObject.setVal2("yourVal2");

    return returnedObject;
}

You can pass the values into arrays/objects. (I am not saying that you can return an array).If you pass array into the method as one of the parameters, the values of the array shall remain. You can access the values from there.

Note : If you find yourself in need of returning more than one value using one method, you should consider re-designing your codes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM