gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:37:31 27 4
gpt4 key购买 nike

假设我有下面这个程序。现在我想将用户的名字和姓氏传递到该方法中,而无需再次调用它并更改参数并使用户再次重新输入名字和姓氏。

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

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

关于java - 我有一个方法,我想向我的主方法返回三个不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7621279/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com