Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #18666 > unrolled thread

can't return value

Started by"bilsch" <king621@comcast.net>
First post2012-09-12 00:36 -0700
Last post2012-09-12 20:54 -0700
Articles 14 — 8 participants

Back to article view | Back to comp.lang.java.programmer


Contents

  can't return value "bilsch" <king621@comcast.net> - 2012-09-12 00:36 -0700
    Re: can't return value Eric Sosman <esosman@ieee-dot-org.invalid> - 2012-09-12 07:11 -0400
      Re: can't return value bilsch <bilsch01@gmail.com> - 2012-09-12 22:15 -0700
        Re: can't return value Eric Sosman <esosman@ieee-dot-org.invalid> - 2012-09-13 08:53 -0400
    Re: can't return value Jukka Lahtinen <jtfjdehf@hotmail.com.invalid> - 2012-09-12 15:32 +0300
      Re: can't return value bilsch <bilsch01@gmail.com> - 2012-09-12 22:37 -0700
        Re: can't return value Lew <lewbloch@gmail.com> - 2012-09-12 23:17 -0700
          Re: can't return value markspace <-@.> - 2012-09-13 01:11 -0700
            Re: can't return value Lew <lewbloch@gmail.com> - 2012-09-13 10:53 -0700
        Re: can't return value Stuart <DerTopper@web.de> - 2012-09-13 09:45 +0200
          Re: can't return value "bilsch" <king621@comcast.net> - 2012-09-13 03:55 -0700
          Re: can't return value Jukka Lahtinen <jtfjdehf@hotmail.com.invalid> - 2012-09-13 15:06 +0300
            Re: can't return value Stuart <DerTopper@web.de> - 2012-09-13 20:53 +0200
    Re: can't return value Roedy Green <see_website@mindprod.com.invalid> - 2012-09-12 20:54 -0700

#18666 — can't return value

From"bilsch" <king621@comcast.net>
Date2012-09-12 00:36 -0700
Subjectcan't return value
Message-ID<k2pe2b$lp4$1@dont-email.me>
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.  The compiler complains there is no RETURN statement when I 
have it there.  It stops complaining if I put RETURN two brackets lower 
(notice it is commented out there).  The variable lastName isn't visible to 
the RETURN statement that's located two brackets lower. The variable 
lastName is only visible inside the FOR / IF block.

I thought passing variables was a way to get around the visibility problem - 
but I'm stuck anyway.  Does anyone have a suggestion?  TIA  Bill S.

public class Name01{

    public static String lastName(String wholeName){
     for (int i = 0; i <= wholeName.length(); i++){
         if (wholeName.charAt(i)== ' '){
            String lastName = wholeName.substring(i,wholeName.length()-1);
            //System.out.println(lastName);
            return lastName;
         }
     }
     //return lastName;
    }


    public static void main(String[] args){
String  wholeName = "Bill Jones", last;
    last = lastName(wholeName);
    System.out.println("lastname is: " + last);
}
} 

[toc] | [next] | [standalone]


#18667

FromEric Sosman <esosman@ieee-dot-org.invalid>
Date2012-09-12 07:11 -0400
Message-ID<k2pql5$o74$1@dont-email.me>
In reply to#18666
On 9/12/2012 3:36 AM, bilsch wrote:
> 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.  The compiler complains there is no RETURN statement when I
> have it there.  It stops complaining if I put RETURN two brackets lower
> (notice it is commented out there).  The variable lastName isn't visible to
> the RETURN statement that's located two brackets lower. The variable
> lastName is only visible inside the FOR / IF block.
>
> I thought passing variables was a way to get around the visibility problem -
> but I'm stuck anyway.  Does anyone have a suggestion?  TIA  Bill S.

     Although your method contains a `return' statement, the
compiler has noticed that the `return' might not always be
executed.  Since you only execute the `return' after detecting
a space character in `wholeName', what happens if `wholeName'
contains no spaces?  Answer: The `for' loop completes[*]
without ever reaching the `return', and then where are you?

     You need to decide what to do if there is no space in
`wholeName': throw an exception, return `null', whatever you
like -- but the compiler will not allow you to just ignore
the possibility.

     [*] Actually, the loop will not complete.  If there is
no space in `wholeName', you will eventually get an exception
when you call charAt() with an argument that's beyond the
end of the string.  In fact, then, the analysis I've given
above is not quite correct: execution will never get to where
the commented-out `return' is.  But (1) the compiler cannot
"see" the fact that charAt() will throw, and (2) if you fix
the error in the `for' loop the analysis becomes correct again.

     Aside: There are at least two easier ways to find the
pieces of `wholeName'.  The String class has indexOf() and
lastIndexOf() methods that can find the space character for
you, and also has a split() method that can both find the
spaces and chop the string into space-separated pieces.

     Aside II: Re-read the documentation of the substring()
method; there's a surprise awaiting you.

> public class Name01{
>
>      public static String lastName(String wholeName){
>       for (int i = 0; i <= wholeName.length(); i++){
>           if (wholeName.charAt(i)== ' '){
>              String lastName = wholeName.substring(i,wholeName.length()-1);
>              //System.out.println(lastName);
>              return lastName;
>           }
>       }
>       //return lastName;
>      }
>
>
>      public static void main(String[] args){
> String  wholeName = "Bill Jones", last;
>      last = lastName(wholeName);
>      System.out.println("lastname is: " + last);
> }
> }
>
>


-- 
Eric Sosman
esosman@ieee-dot-org.invalid
"The speed at which the system fails is usually not important."

[toc] | [prev] | [next] | [standalone]


#18722

Frombilsch <bilsch01@gmail.com>
Date2012-09-12 22:15 -0700
Message-ID<k2rq4k$c2g$1@dont-email.me>
In reply to#18667
On 9/12/2012 4:11 AM, Eric Sosman wrote:
> On 9/12/2012 3:36 AM, bilsch wrote:
>> 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. The compiler complains there is no RETURN statement when I
>> have it there. It stops complaining if I put RETURN two brackets lower
>> (notice it is commented out there). The variable lastName isn't
>> visible to
>> the RETURN statement that's located two brackets lower. The variable
>> lastName is only visible inside the FOR / IF block.
>>
>> I thought passing variables was a way to get around the visibility
>> problem -
>> but I'm stuck anyway. Does anyone have a suggestion? TIA Bill S.
>
> Although your method contains a `return' statement, the
> compiler has noticed that the `return' might not always be
> executed. Since you only execute the `return' after detecting
> a space character in `wholeName', what happens if `wholeName'
> contains no spaces? Answer: The `for' loop completes[*]
> without ever reaching the `return', and then where are you?
>
> You need to decide what to do if there is no space in
> `wholeName': throw an exception, return `null', whatever you
> like -- but the compiler will not allow you to just ignore
> the possibility.
>
> [*] Actually, the loop will not complete. If there is
> no space in `wholeName', you will eventually get an exception
> when you call charAt() with an argument that's beyond the
> end of the string. In fact, then, the analysis I've given
> above is not quite correct: execution will never get to where
> the commented-out `return' is. But (1) the compiler cannot
> "see" the fact that charAt() will throw, and (2) if you fix
> the error in the `for' loop the analysis becomes correct again.
>
> Aside: There are at least two easier ways to find the
> pieces of `wholeName'. The String class has indexOf() and
> lastIndexOf() methods that can find the space character for
> you, and also has a split() method that can both find the
> spaces and chop the string into space-separated pieces.
>
> Aside II: Re-read the documentation of the substring()
> method; there's a surprise awaiting you.
>
>> public class Name01{
>>
>> public static String lastName(String wholeName){
>> for (int i = 0; i <= wholeName.length(); i++){
>> if (wholeName.charAt(i)== ' '){
>> String lastName = wholeName.substring(i,wholeName.length()-1);
>> //System.out.println(lastName);
>> return lastName;
>> }
>> }
>> //return lastName;
>> }
>>
>>
>> public static void main(String[] args){
>> String wholeName = "Bill Jones", last;
>> last = lastName(wholeName);
>> System.out.println("lastname is: " + last);
>> }
>> }
>>
>>
>
>
thanks for your reply.  I got it to work two different ways. Could you 
explain returning NULL? Also, I don't know what exception to throw or 
how to do it.

[toc] | [prev] | [next] | [standalone]


#18734

FromEric Sosman <esosman@ieee-dot-org.invalid>
Date2012-09-13 08:53 -0400
Message-ID<k2sl06$o4f$1@dont-email.me>
In reply to#18722
On 9/13/2012 1:15 AM, bilsch wrote:
> On 9/12/2012 4:11 AM, Eric Sosman wrote:
>> On 9/12/2012 3:36 AM, bilsch wrote:
>>>[...]
>> You need to decide what to do if there is no space in
>> `wholeName': throw an exception, return `null', whatever you
>> like -- but the compiler will not allow you to just ignore
>> the possibility.
>> [...]
> thanks for your reply.  I got it to work two different ways. Could you
> explain returning NULL? Also, I don't know what exception to throw or
> how to do it.

     Any variable that refers to an object -- a String, a List,
or whatever -- can have the special value `null' (not `NULL')
to indicate that it "refers to nothing" at the moment.  Methods
that return object references can return `null' to indicate
"I've got nothing to give you."  If your method returns, it
must return some value; I'm suggesting that if your method
could not do its job, `null' is a value you might consider
returning.  It's just a special value you might decide should
mean "I couldn't find a last name in `wholeName'."

     Another possibility is to throw an exception: The method
tries to find a last name, discovers that `wholeName' doesn't
contain one, and says "Hey, stupid caller: You fed me garbage!"
In the case at hand, IllegalArgumentException seems a likely
candidate, so the method could announce its displeasure with

	throw new IllegalArgumentException(
	    "no last name in " + wholeName);

When a method terminates by throwing an exception it does not
need to return a value, because in truth it doesn't "return"
at all: It abruptly stops what it was doing, and what all its
callers were doing, up to the point where some caller has a
`try {...} catch' for the type of exception thrown.

     Bilsch, this is very elementary stuff, the sort of thing
you will find in any introductory textbook or tutorial on Java.
I suggest you consult one; trying to learn the language one
corrected blunder at a time is not very efficient.  You might
also think about using comp.lang.java.help for elementary
questions; comp.lang.java.programmer is (in theory) a forum
for people who already know the basics and are tackling more
advanced issues.  (Note the "in theory.")

     CC'ed, and follow-ups set.

-- 
Eric Sosman
esosman@ieee-dot-org.invalid
"The speed at which the system fails is usually not important."

[toc] | [prev] | [next] | [standalone]


#18668

FromJukka Lahtinen <jtfjdehf@hotmail.com.invalid>
Date2012-09-12 15:32 +0300
Message-ID<m3pq5r4e18.fsf@ipa.eternal-september.org>
In reply to#18666
"bilsch" <king621@comcast.net> writes:

> I thought passing variables was a way to get around the visibility problem - 
> but I'm stuck anyway.  Does anyone have a suggestion?  TIA  Bill S.
>
> public class Name01{
>
>     public static String lastName(String wholeName){
>      for (int i = 0; i <= wholeName.length(); i++){
>          if (wholeName.charAt(i)== ' '){
>             String lastName = wholeName.substring(i,wholeName.length()-1);
>             //System.out.println(lastName);
>             return lastName;
>          }
>      }
>      //return lastName;
>     }

What Eric wrote in his followup, and you could also define lastName
before the for loop and initialize it to null.

   public static String lastName(String wholeName) {
     String lastName = null;
     for (int i = 0; i < wholeName.length(); i++) {
...

Also notice that you probably should change the <= operator to < in the
for loop condition to avoid StringIndexOutOfBoundsException if there's
no space in the parameter String.
And like Eric wrote, there are handier ways to split a String, but
that's not where your current problem is.

-- 
Jukka Lahtinen

[toc] | [prev] | [next] | [standalone]


#18724

Frombilsch <bilsch01@gmail.com>
Date2012-09-12 22:37 -0700
Message-ID<k2rreo$hqj$1@dont-email.me>
In reply to#18668
On 9/12/2012 5:32 AM, Jukka Lahtinen wrote:
> "bilsch"<king621@comcast.net>  writes:
>
>> I thought passing variables was a way to get around the visibility problem -
>> but I'm stuck anyway.  Does anyone have a suggestion?  TIA  Bill S.
>>
>> public class Name01{
>>
>>      public static String lastName(String wholeName){
>>       for (int i = 0; i<= wholeName.length(); i++){
>>           if (wholeName.charAt(i)== ' '){
>>              String lastName = wholeName.substring(i,wholeName.length()-1);
>>              //System.out.println(lastName);
>>              return lastName;
>>           }
>>       }
>>       //return lastName;
>>      }
>
> What Eric wrote in his followup, and you could also define lastName
> before the for loop and initialize it to null.
>
>     public static String lastName(String wholeName) {
>       String lastName = null;
>       for (int i = 0; i<  wholeName.length(); i++) {
> ...
>
> Also notice that you probably should change the<= operator to<  in the
> for loop condition to avoid StringIndexOutOfBoundsException if there's
> no space in the parameter String.
> And like Eric wrote, there are handier ways to split a String, but
> that's not where your current problem is.


Thanks for your reply.
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.

[toc] | [prev] | [next] | [standalone]


#18728

FromLew <lewbloch@gmail.com>
Date2012-09-12 23:17 -0700
Message-ID<127f013d-c689-47f9-bb69-4e558d072d61@googlegroups.com>
In reply to#18724
bilsch wrote:
> 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.

That's a meaningless request. You can't throw an exception if 
the program cannot run, or even compile.

Once you fix the compilation error, you won't be missing a 
'return'.

And there are no 'RETURN' statements in Java. 

If you read the Java tutorials on the Oracle site, they 
explain the basics of Java syntax and what constitutes 
a legal Java program.

-- 
Lew

[toc] | [prev] | [next] | [standalone]


#18731

Frommarkspace <-@.>
Date2012-09-13 01:11 -0700
Message-ID<k2s4f0$rn9$1@dont-email.me>
In reply to#18728
On 9/12/2012 11:17 PM, Lew wrote:
> bilsch wrote:
>> 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.

>
> And there are no 'RETURN' statements in Java.


Not sure where this came from, I didn't see anyone upthread quote return 
as 'RETURN'.  However, the null literal in Java is properly spelled 
'null', not NULL.  Perhaps that's what you meant to comment on.

[toc] | [prev] | [next] | [standalone]


#18739

FromLew <lewbloch@gmail.com>
Date2012-09-13 10:53 -0700
Message-ID<2be1e398-65ad-47d3-a8b0-6fccad04c075@googlegroups.com>
In reply to#18731
markspace wrote:
> Lew wrote:
>> bilsch wrote:
>>> 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.
> 
>> And there are no 'RETURN' statements in Java.
> 
> Not sure where this came from, I didn't see anyone upthread quote return 
> as 'RETURN'.  However, the null literal in Java is properly spelled 
> 'null', not NULL.  Perhaps that's what you meant to comment on.

No, I was commenting on the OP's very first post that started this thread:
"The variable lastName isn't visible to the RETURN statement 
that's located two brackets lower."

-- 
Lew

[toc] | [prev] | [next] | [standalone]


#18730

FromStuart <DerTopper@web.de>
Date2012-09-13 09:45 +0200
Message-ID<k2s2vb$jr5$1@dont-email.me>
In reply to#18724
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

[toc] | [prev] | [next] | [standalone]


#18732

From"bilsch" <king621@comcast.net>
Date2012-09-13 03:55 -0700
Message-ID<k2se2q$fm9$1@dont-email.me>
In reply to#18730
"Stuart" <DerTopper@web.de> wrote in message 
news:k2s2vb$jr5$1@dont-email.me...
> 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

Thanks for the info.  I can't experiment with it right now.  I'll post 
later. 

[toc] | [prev] | [next] | [standalone]


#18733

FromJukka Lahtinen <jtfjdehf@hotmail.com.invalid>
Date2012-09-13 15:06 +0300
Message-ID<m3ligegm9x.fsf@ipa.eternal-september.org>
In reply to#18730
Stuart <DerTopper@web.de> writes:
> 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

> 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

No, I just meant that the original code WILL throw an
ArrayIndexOutOfBoundsException if it doesn't find a space.
Right here in the String#charAt method, when i reaches wholeName.length():

      for (int i = 0; i <= wholeName.length(); i++){
          if (wholeName.charAt(i)== ' '){

and bilsh probably wants to avoid it.

-- 
Jukka Lahtinen

[toc] | [prev] | [next] | [standalone]


#18744

FromStuart <DerTopper@web.de>
Date2012-09-13 20:53 +0200
Message-ID<k2ta3r$69u$1@dont-email.me>
In reply to#18733
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

Stuart writes:
>> 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

On 9/13/12  Jukka Lahtinen wrote:
> No, I just meant that the original code WILL throw an
> ArrayIndexOutOfBoundsException if it doesn't find a space.
> Right here in the String#charAt method, when i reaches wholeName.length():
>
>        for (int i = 0; i <= wholeName.length(); i++){
>            if (wholeName.charAt(i)== ' '){
>
> and bilsh probably wants to avoid it.

Now I'm glad that I -- as an afterthought -- slipped the word "probably" 
into my sentence. Well, that's what one gets if one doesn't bother to 
check out the context (which was unfortunately missing).

Regards,
Stuart

[toc] | [prev] | [next] | [standalone]


#18720

FromRoedy Green <see_website@mindprod.com.invalid>
Date2012-09-12 20:54 -0700
Message-ID<k3m258d21dv8ot4d3iu35rf6i674vm1iim@4ax.com>
In reply to#18666
On Wed, 12 Sep 2012 00:36:41 -0700, "bilsch" <king621@comcast.net>
wrote, quoted or indirectly quoted someone who said :

> there is no RETURN statemen

you have to make sure there is a some sort of return on every possible
way to exit.  Look at both branches of your IF. Whether you leave
early or fall out the bottom of the loop. Make sure there is no way
you can even theoretically exit without a value.
-- 
Roedy Green Canadian Mind Products http://mindprod.com
A new scientific truth does not triumph by convincing its opponents and making them see the light,
but rather because its opponents eventually die, and a new generation grows up that is familiar with it.
~ Max Planck 1858-04-23 1947-10-04 

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.java.programmer


csiph-web