在方法中使用双 "return"

Use a double "return" in a method

我正在创建一个必须填充两个不同数组的方法。一个是人名,一个是人姓

为此,我使用了这个程序: 这样,我在两个不同的方法中创建了两个数组,然后我可以在其他方法中使用它们。

public static void main(String[] args) {
    Scanner in=new Scanner(System.in);
    int person;
    System.out.println("How many people are there?");
    person=in.nextInt();
    String [] names=names(person);
    String [] surnames=surnames(person);
}

public static String [] names (int person) {
    Scanner in=new Scanner(System.in);
    String names []=new String [person];
    System.out.println("Enter the names of the people");
    for (int i=0; i<names.length; i++)
        names[i]=in.next();
    return names;
}
public static String [] surnames (int person) {
    Scanner in=new Scanner(System.in);
    String surnames []=new String [person];
    System.out.println("Enter the surnames of the people");
    for (int i=0; i<surnames.length; i++)
        surnames[i]=in.next();
    return surnames;
}

不过,我想用同一个方法创建这两个数组,然后在其他方法中使用它们。

肯定有一些更快更直观的方法。谁能帮帮我?谢谢

假设您不喜欢使用 Person 对象(或类似的东西)- 考虑使用包含两个数组的包装器对象。

类似的东西:

class Wrapper{

     String [] names
     String [] surnames

    // getters & setters
}

并且您的组合方法将 return wrapper 对象。

您需要重构发送给客户端的消息(字符串):

public static String [] names (int person, String message) {
    Scanner in=new Scanner(System.in);
    String names []=new String [person];
    System.out.println(message);
    for (int i=0; i<names.length; i++)
        names[i]=in.next();
    return names;
}

并调用同一个方法两次:

String [] names=names("Enter the names of the people");
String [] surnames=names("Enter the surnames of the people");

您可以将 return 语句与 if 条件或 switch case 一起使用到 return 不同的值,但您必须记住,一个函数只能调用一次 return 语句.. 一旦调用了 return 语句,函数就结束了。

另一种方法是在调用函数时发送一个参数,这样您就知道要问什么了。

public static String [] getNameOrSurname(int person, String value) {
    Scanner in=new Scanner(System.in);
    String retrunValue[]=new String [person];
    System.out.println("Enter the +"value"+ of the people");
    for (int i=0; i<returnValue.length; i++)
        returnValue[i]=in.next();
    return returnValue;
}

当你需要调用函数获取名字时

String [] names = getNameOrSurname(person , 'Name')

当需要调用获取姓氏的函数时

String [] surnames = getNameOrSurname(person , 'Surname')

最好的方法是使用 getter 和 setter :

设置函数:

public static String [] setNames (int persons, String message) {
    Scanner in=new Scanner(System.in);
    String names []=new String [persons];
    System.out.println(message); 
    for (int i=0; i<names.length; i++)
        names[i]=in.next();
    return names;
}

获取函数:

显示数组

所以每个函数都做一件事,一个取值到数组并填充它。 第二个函数显示它。