Search code examples
javaarraysfunctionmethodssubroutine

How can I not specify any return type and yet print my arrays in a tabular form?


The goal of this program is to declare three separate arrays and then write a function to display them in a tabular form. Here's my code:

import java.util.Scanner;

public class MultiDArray {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner input = new Scanner(System.in);
        System.out.println("How many rows?");
        int length = input.nextInt();

        int [] ID = new int[length];
        for(int counter = 0; counter<length; counter++) {
            System.out.println("Enter ID number "+(counter+1));
            ID[counter] = input.nextInt();
        }

        Scanner scan = new Scanner(System.in);
        System.out.println("How many names?");
        int words = scan.nextInt();

        String [] Name = new String[words];
        for(int counter = 0; counter<words; counter++) {
            System.out.println("Enter Name "+(counter+1));
            Name[counter] = scan.next();
        }

        Scanner figure = new Scanner(System.in);
        System.out.println("How many Salaries?");
        int sal = figure.nextInt();

        int []Salary = new int[sal];
        for(int counter = 0; counter<sal; counter++) {
            System.out.println("Enter Salary "+(counter+1));
            Salary[counter] = figure.nextInt();
        }

        input.close();
        scan.close();
        figure.close();

        System.out.println("ID"+" "+"Name"+" "+"Salary");
        System.out.println("Content of Array: " + (display(ID, Name, Salary)));
}

public static String display(int x[], String y[], int z[]) {
    for (int i = 0; i<x.length; i++) {
        System.out.println(x[i]+"   "+y[i]+"   "+z[i]);
    }
    return null;
}
}

Which prints out my system input in this way:

ID Name Salary
1   JK   3000
2   MK   4000
3   CK   5000
null

However, what I would like to see instead is the same without the "null" part.

ID Name Salary
1   JK   3000
2   MK   4000
3   CK   5000

If I do not specify any return type, I get errors.


Solution

  • You are returning null and then concatenating it in your calling println statement

     System.out.println("Content of Array: " + (display(ID, Name, Salary)));
    

    You could do something like

    System.out.print("Content of Array: ");
    String ret = display(ID, Name, Salary);
    

    If you are trying to write a method without a return type, use void. You shouldn't be concatenating a void return to a string though.

    public static void display(int x[], String y[], int z[]) {
        for (int i = 0; i<x.length; i++) {
            System.out.println(x[i]+"   "+y[i]+"   "+z[i]);
        }
    }