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

时间:2011-10-01 15:52:59

标签: 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
}

}

3 个答案:

答案 0 :(得分:5)

创建一个小包装类,它保存您想要返回的值,并返回该类的实例。

class Name
{
    final String firstName;
    final String lastName;

    Name(String first, String last)
    {
        firstName = first;
        lastName = last;
    }
}

如何使用它:

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);
}

答案 1 :(得分:1)

您可以创建另一个名为Fullname的类,其中包含两个属性,名字和姓氏。然后在getName函数中,返回Fullname对象。

答案 2 :(得分:0)

是,返回一个对象,一个地图或一个数组(ew)。 Java无法在不将它们包装到单个对象的情况下返回多个值。