可以說我有這個程序下面。現在我想將用戶的名字和姓氏都傳遞給方法,而不用再次調用它並更改參數並使用戶重新鍵入那裏的名字和姓氏。我有一個方法,我想返回三個不同的值,我的主要方法
我知道我可以做兩種不同的方法來找到名字和姓氏,但我想知道是否有辦法做到這一點只是一種方法。
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
}
}
我結束了創建一個數組,現在我可以從main方法使用nameArray [0]或nameArray [1]來訪問我需要的不同事物。 – JDN