Home > OS >  How to return two seperate arrays from a method in Java
How to return two seperate arrays from a method in Java

Time:03-10

I'm practicing on my java and using a book I came across something similar to this so I am trying to put my own spin on it and have ran into a question I hoped to get answered. I want to create a method that asks the user for the students name and the students grade. I'm going to create another method that will need the scores from my studentInfo() method but I will also have another method that will sort the score array at the same time I sort the name array. The problem is I can't seem to figure out how I will get each separate array from my studentInfor() method.

 // imports
 
 import java.util.Scanner;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;


 public class Main {
     public static Scanner input = new Scanner(System.in);
     public static void main(String[] args) {
         int n;
         n = numOfStudents();

         input.nextLine();

         studentInfo(n);

     }

public static int numOfStudents(){

    int students = 0;
    System.out.print("Enter the number of students: ");
    students = input.nextInt();

    while (students < 1) {
        System.out.print("Number of students must be greater than 0: ");
        students = input.nextInt();
    }
    return students;
}

public static String[] studentInfo(int num){


    String[] arr;
    arr = new String[num];

    String[] score;
    score = new String[num];

    String[] names;
    names = new String[num];

    String strPattern = "-?\\d (\\.\\d )?";

    for(int i = 0; i < num; i  ) {


        System.out.print("Enter a name and test score: ");
        arr[i] =input.nextLine();

        Pattern pattern = Pattern.compile(strPattern);
        Matcher matcher = pattern.matcher(arr[i]);

        while (matcher.find()) {
            score[i] = matcher.group();
        }
        
        names[i] = arr[i].replaceAll(strPattern, "");

    }
    for (String element: score){
        System.out.println("Name is "   element   "\n");

    }
    // Not possible, need possible solution
    return (names,score);
  }

 }

CodePudding user response:

You can return two arrays from a method like this

return new Object[]{array1, array2};

You can then access them where you capture the return like this obj[0], and obj[1]. Where obj[0], obj[1] represent array names, and scores respectively.

CodePudding user response:

Since you want to return two values, you can create a new "pair" class and change the return type of your method to return object of this type

class Pair<T, U> {
    public final T first;
    public final U second;

    public Pair(T first, U second) {
        this.first = first;
        this.second = second;
    }
}

Change method return type as

public Pair<String[], String[]> someMethodName()
  • Related