Lets say I have this program below. Now I want to pass both the users first name AND last name into the method without calling it again and changing the parameter and making the user retype there first name and last name again.
I know I can make two different methods for finding the first name and last name but I was wondering if there was a way to do this is just one method.
import java.util.Scanner;
public class Document3 {
public static void main(String[] args) {
String name;
name = getName("lastName"); //But how would I get my lastName WITHOUT recalling the method with "lastName" in the parameters?
System.out.println(name); //I want to also get the other name into in my main method somehow
}
public static String getName(String nameOption) {
Scanner x = new Scanner(System.in);
String firstName = "";
String lastName = "";
String nameChoice = "";
System.out.print("Please enter your first name: ");
firstName = x.nextLine();
System.out.print("\nPlease enter your last name: ");
lastName = x.nextLine();
if (nameOption.equals("firstName")) {
nameChoice = firstName;
}
if (nameOption.equals("lastName")) {
nameChoice = lastName;
}
return nameChoice; //how do I return both variables (firtName and lastName) and how would I access them
}
}
Create a small wrapper class which holds the values you want to return, and return an instance of that class.
How to use it: