i am writing a method that returns an array full of students names. The students names are given in a file, so my method called ReadFile, reads the file and adds each line(name) to the array i'm not sure my code is correct, plus i'm not familiar with writing methods that return and array. If someone could comment on this code, i would really appreciate it.
To return an array from a method is simple. You use the type with the array operator (). So to return an array of type int:
Make sure the type after the return keyword at the end of the method (or anywhere there is a return inside the method) is the same as the return type in the method declaration (at the top).
This example assumes there is only one name per line in the text file. There are a lot of ways to do these kind of things. Here we just read the names and add them to a string using a comma as sepatator and after the file reading is finished convert the string to an array.
im a bit confused, you said that you would commas as the separator, well what if in the text file, there are no commas separating the names for example John Doe Sue McGonnal just spaces, and also in the readFile method, what exactly does the .Split method do?
In the example code above I am reading each line of the text file (and assuming one name per line) adding each name followed by a comma (as delimiter). You can see this in the while loop:
After the while loop the String names holds all the names read from the file, separated by commas (that I added as I gathered the names). Then I remove the last (trailing) comma in preparation for converting the string to an array.
You can find the split method in the String api. It creates and returns an array of strings demarked by the delimeter specified in the argument ("," here).
I added some System.out.println statements to readFile to show what names looks like during the process. The output of names at the end is the same as the text file that contains the names (one name per line).
my data file contains a list of the names but the list has no commas after each name. I tried making the delimeter ""+"" two spaces but it didnt work. so how would i accomplish making the delimeter equal to some kind of space?
also id like to thank the people in this post who helped. I really appreciate the help!