我有一个方法,我想将三个不同的值返回到我的main方法

JDN*_*JDN 0 java

可以说我在下面有这个程序.现在我想将用户的名字和姓氏传递给方法而不再调用它并更改参数并让用户重新键入名字和姓氏.

我知道我可以使用两种不同的方法来查找名字和姓氏,但我想知道是否有办法做到这一点只是一种方法.

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
}
Run Code Online (Sandbox Code Playgroud)

}

Mat*_*all 5

创建一个包含要返回的值的小包装类,并返回该类的实例.

class Name
{
    final String firstName;
    final String lastName;

    Name(String first, String last)
    {
        firstName = first;
        lastName = last;
    }
}
Run Code Online (Sandbox Code Playgroud)

如何使用它:

public static void main(String[] args)
{
    Name name = getName();
    String first = name.firstName;
    String last = name.lastName;
}

public static Name getName()
{
    Scanner x = new Scanner(System.in);

    System.out.print("Please enter your first name: ");
    String firstName = x.nextLine();

    System.out.print("\nPlease enter your last name: ");
    String lastName = x.nextLine();

    return new Name(firstName, lastName);
}
Run Code Online (Sandbox Code Playgroud)