# JAVA: need to return String[]



## d34thr3c0n

I am writing an address book program in JAVA using Eclipse and the following method is supposed to read from the supplied file to occupy the contacts list.

When I try to compile the code, it says that it wants me to return a String[] instead of just a String. If I change it from


Code:


public static String[] occupyList() {

to


Code:


public static String occupyList() {

it tells me it can't change String[] to String. To me, this indicates that it accepts that listContents is a String[].

What can I do tho solve this problem?



Code:


public static String[] occupyList() {
		try {
			BufferedReader listFile = new BufferedReader(new FileReader("contacts/contacts.lst"));
			try {
				int q = Integer.parseInt(listFile.readLine()); //Read first line of contacts.lst | int representing number of contacts to follow
				String[] listContents = new String[q]; //Create >>>String[]<<< with q cells
				
				for(int n=0;n<=q-1;n++) { //reads contacts from contacts.lst into >>>String[]<<< listContents
					listContents[n] = listFile.readLine();
				}
				
				return listContents;
				
			} catch(IOException r){ //catch IOException thrown by readLine()
				System.out.println("IOException was thrown when reading from \"contacts/contacts.lst\"" + r);
			}
		} catch(FileNotFoundException f) { //catch FileNotFoundException thrown by FileReader()
			System.out.println("FileNotFoundException was thrown by the method \"loadContact(String name)\"\n" + f);
		}
	} //End occupyList()


----------



## stirling

Don't rally see what you're getting at. You're returning listContents which you've declared as a string array - so why would you expect your function to be happy to return a string? The clue's in the message - how can a string array be "cast" into a string?


----------



## d34thr3c0n

no... i want to return a string array. when the return type is set as String[] it says "must return String[] not String" but if i change it to return type String, it says "must return String not String[]"


----------



## stirling

ok - I didn't really see what you were getting at. I've looked at your code in a little more detail (bearing in mind it's been a while since I did any java but then hey - no-one else is answering) Your code looks fine except maybe one thing... if either catch is executed then the return is undefined - can't remeber if this is allowed (like it would be in C for example - bad practice but allowable) sorry like I say it's been a while.


----------



## d34thr3c0n

so if i made it throw the exceptions (kinda bad, i know...) so it didnt require try...catch would that work right? or would that make more problems arise than it would fix?

it is reading from a file that, unless altered by outside means, should exist and carry the layout it is looking for (created by the program itself)


----------

