can't return value

B

bilsch

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);
}
}
 
E

Eric Sosman

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);
}
}
 
J

Jukka Lahtinen

bilsch said:
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.
 
R

Roedy Green

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.
 
B

bilsch

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.
 
B

bilsch

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.
 
L

Lew

bilsch said:
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.
 
S

Stuart

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]

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
 
M

markspace

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.
 
B

bilsch

Stuart said:
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]

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.
 
J

Jukka Lahtinen

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.
 
E

Eric Sosman

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.
 
L

Lew

markspace said:
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."
 
S

Stuart

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,813
Latest member
lawrwtwinkle111

Latest Threads

Top