PDA

View Full Version : Resolved Return Issues



magicgavin
11-24-2008, 09:10 PM
I'm trying to pass a string into the method and have it return the results from mydata2. It keep getting the error "missing return statement".



// Main method
public static String readData (String arg1)
{
// Stream to read file
FileInputStream fin;

try
{
// Open an input stream
String mydata2="";
fin = new FileInputStream (arg1);

// Read a line of text
mydata2 = new DataInputStream(fin).readLine();
// Close our input stream
fin.close();
return mydata2;
}
// Catches any error conditions
catch (IOException e)
{
//System.err.println ("Unable to read from file");
System.exit(-1);
}
}

magicyte
11-24-2008, 10:03 PM
// Main method
public void static String readData (String arg1)
{
// Stream to read file
FileInputStream fin;

try
{
// Open an input stream
String mydata2="";
fin = new FileInputStream (arg1);

// Read a line of text
mydata2 = new DataInputStream(fin).readLine();
// Close our input stream
fin.close();
return mydata2;
}
// Catches any error conditions
catch (IOException e)
{
//System.err.println ("Unable to read from file");
System.exit(-1);
}
}

Might this work?

-magicyte

magicgavin
11-25-2008, 03:37 PM
Thanks for your help. I removed void because I though string replaced it.

Twey
11-26-2008, 07:07 AM
It does. I doubt that will even compile it's a nonsensical type signature.

What you should have done is:

public static String readData(String arg1) {
// Stream to read file
FileInputStream fin;
String r;

try {
// Open an input stream
fin = new FileInputStream(arg1);

// Read a line of text
r = (new DataInputStream(fin)).readLine();

// Close our input stream
fin.close();
} catch (IOException e) {
// Catches any error conditions
System.err.println("Unable to read from file");
System.exit(-1);
}

return r;
}Style notes: spaces do not go between method names and their arguments (you seemed a bit on the fence about this one); keep as much out of the try block as you can (catching exceptions is expensive); braces go on the same line as the keyword that opens the block in Java (the style you were using for the braces was a form of K&R C style).