platypus87 platypus87 - 1 year ago 55
Java Question

In Java, how do I use part of an array element to invoke a particular method?

I read a text file with 20 lines and assigned it to "tempsArray" A typical element of the array will look like this: "2014 Employee Doe, John 5000" I need to do a couple things with that data: I need to create a multi-dimensional array that has the year 2014 and 2015 as the initial dimension and then has the rest of the data as the second dimension i.e.

would be "Employee Doe, John 5000" from the year 2014. There are 10 items in the file that are 2014 and 10 that are 2015. Next, I need to be able to use part of the second part of the array as a parameter in a method. For example; I need to use the 5000 in the above example as the parameter of
. The code that I have for it so far is below:

public class TestEmployee {

public static void main(String[] args) throws IOException {

String token = "";
Scanner inFile = new Scanner(new File("employeeInfo.txt")).useDelimiter("\n"); //uses the 'new line' character as the delimiter,

List<String> temps = new ArrayList<String>();

while (inFile.hasNext()) {
token =;
String[] tempsArray = temps.toArray(new String[0]);

for (String s : tempsArray) {

}//end main

}//end TestEmployee

Answer Source

Try this code and replace your for loop with this one.

for (String s : tempsArray)
        String splitted[]=s.split(" ");
        int first_element=Integer.parseInt(splitted[0]);//Use this for the dimension
        int salary=Integer.parseInt(splitted[splitted.length-1].trim());//Use this as argument of a method. Here .trim() is used to remove space if its present at the end of line