Path: csiph.com!usenet.pasdenom.info!gegeweb.org!eternal-september.org!feeder.eternal-september.org!mx04.eternal-september.org!.POSTED!not-for-mail From: Stuart Newsgroups: comp.lang.java.programmer Subject: Re: can't return value Date: Thu, 13 Sep 2012 09:45:46 +0200 Organization: A noiseless patient Spider Lines: 54 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Thu, 13 Sep 2012 07:45:47 +0000 (UTC) Injection-Info: mx04.eternal-september.org; posting-host="21aac22f8896a48c2c25e23bfecada7e"; logging-data="20325"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18iqzfYuRNSCi6y1Ww3ii8yoteuPxsOUYs=" User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:15.0) Gecko/20120824 Thunderbird/15.0 In-Reply-To: Cancel-Lock: sha1:Sz7e/yENuOLBTH03L68gnhU8xEo= Xref: csiph.com comp.lang.java.programmer:18730 bilsch wrote in his first posting: > I want to get variable lastName for use in the main method (the whole > program isn't shown). I want to return it from inside the IF block within > the FOR loop. [snipped various replies] On 9/13/12 bilsch wrote: > Based on what Jukka said I got it to work without using the for loop. > OK. Now I see what Jukka meant by initializing to NULL. But I don't > know what exception to throw for 'misssing return statement'. Also I > don't know how to put it in. What Jukka probably meant to say is that you could throw an exception in case your method could not extract a surname from the passed string. Like so: public static String lastName(String wholeName){ for (int i = 0; i < wholeName.length(); i++){ if (wholeName.charAt(i)== ' '){ return wholeName.substring(i + 1); } } // If we reach this line, the parameter // wholeName cannot have contained a // blank, so we cannot extract the last // name. throw new exception ("cannot find lastname"); } Alternatively, your method can simply return null: public static String lastName(String wholeName){ for (int i = 0; i < wholeName.length(); i++){ if (wholeName.charAt(i)== ' '){ return wholeName.substring(i + 1); } } // If we reach this line, the parameter // wholeName cannot have contained a // blank, so we cannot extract the last // name. return null; } Which of these variants suits you better depends on how you want to use lastName. Both have their advantages and disadvantages. Regards, Stuart