d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Easy Java Question
Add Reply New Topic New Poll
Member
Posts: 5,167
Joined: Nov 23 2006
Gold: 11.01
Sep 8 2014 03:03pm
Having some issues with this... I've never done any java before but have an assignment to take a .txt and put it into an ArrayList and print it (plus other functions but I'll do those myself).

My code to put it into the arraylist


Code
public static ArrayList<String> initArrayOfStrings(String filePath, int num) {
int size = num;
ArrayList<String> lines = new ArrayList<String>();
File names = new File(filePath);
try {
Scanner scanner = new Scanner(names);
while (scanner.hasNextLine()) {
lines.add(scanner.nextLine());
// String line = scanner.nextLine(); - not in arraylist
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("Can't find file");
}

return lines;
}

This just returns an ArrayList which is then passed to a function to print and I just have a standard system.out.println(arrayListname); to print it out.

The output I'm getting should have a string on every line... but instead it looks like this: all on one line and two spaces between each name.
name1 name2 name3 name4 etc etc

This post was edited by HoneyBadger on Sep 8 2014 03:04pm
Member
Posts: 32,925
Joined: Jul 23 2006
Gold: 3,804.50
Sep 8 2014 05:32pm
system.out.println(arrayListname)

don't do that. that relies on ArrayList's toString() method. if you want your own format, write your own logic.

if you want one line per entry:
for (String line : arraylist){
System.out.println(line);
}
Member
Posts: 18,375
Joined: May 22 2009
Gold: 58.00
Sep 18 2014 10:56pm
the problem is that you have got the proper return, but you didn't format the output properly. system.out.println() only prints the arraylist without the newline character. to print the output with the newline you have to iterate through the list and output newline character after every iteration.
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll