繁体   English   中英

我有一个方法,我想向我的主方法返回三个不同的值

[英]I have a method and I want to return three different values to my main 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
}

}

创建一个小的包装器类,其中包含要返回的值,然后返回该类的实例。

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

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

是的,返回一个对象,一个映射或一个数组(ew)。 Java没有返回多个值而不将它们包装到单个对象中的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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