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