Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialMaxwell Nelson
9,465 PointsString[] args in a method.
Hello!
I am trying to understand using String[] args within a method. Below is a load method for a txt file utilized in the Karaoke project.
public void importFrom(String fileName) {
try (
FileInputStream fos = new FileInputStream(fileName);
BufferedReader reader = new BufferedReader(new InputStreamReader(fos));
) {
String line;
while((line = reader.readLine()) != null) {
String [] args = line.split("\\|");
addSong(new Song(args[0], args[1], args[2]));
}
} catch(IOException ioe) {
System.out.printf("Problem loading %s %n", fileName);
ioe.printStackTrace();
}
}
in the middle of the code block, there is
String line;
while((line = reader.readLine()) != null) {
String [] args = line.split("\\|");
addSong(new Song(args[0], args[1], args[2]));
}
Can someone explain what is going on here? I understand everything before and after but would appreciate a more detailed explanation than the one given in the video.
Thank you!
1 Answer
nihouse
7,160 PointsWith the square brackets you tell the JVM that you don't just need one string, but an ARRAY of strings (multiple Strings, so that you can access those independently).
Info: You can also place the brackets after the array's name: String args[]
Here you can get more Info: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html http://alvinalexander.com/java/java-string-array-reference-java-5-for-loop-syntax
Maxwell Nelson
9,465 PointsMaxwell Nelson
9,465 PointsThanks for the input and additional info! Huge help.