2
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?

2
  • 2
    There are lot of ways. you can use int[], POJO class with just two fields, a concatenating string, a collection object or what ever. Commented Apr 12, 2014 at 22:19
  • also check: stackoverflow.com/questions/2832472/… Commented Apr 12, 2014 at 22:33

2 Answers 2

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.