Redeclaration is possible in many languages but not in JAVA. The JAVA compiler knows that retVal already exists within the same scope and is declared of type String. So it will not redeclare it, neither with same data type or different. You can either have a separate variable for this purpose or simply override the data in retVal. So, the below code must fulfil your needs.
public String findWord(String string, String word){
String[] text = string.split(" *");
String retVal = "Not found";
for(int i=0; i<text.length; i++){
if(text[i].equals(word)){
retVal = text[i];
}
}
return retVal;
}
Now the syntax for string.split is
public String[] split(String regex,
int limit)
so your delimiter should be a valid expression. So you can either separate the words in your sentence using a space like this
public String findWord(String string, String word){
String[] text = string.split(" ");
String retVal = "Not found";
for(int i=0; i<text.length; i++){
if(text[i].equals(word)){
retVal = text[i];
}
}
return retVal;
}
void main()
{
System.out.println(findWord("Hello how are you","are"));
}
But if you want to use *, you can use this code.
public String findWord(String string, String word){
String[] text = string.split("\\*");
String retVal = "Not found";
for(int i=0; i<text.length; i++){
if(text[i].equals(word)){
retVal = text[i];
}
}
return retVal;
}
void main()
{
System.out.println(findWord("Hello*how*are*you","are"));
}
The output in both the cases will be- are
You can go through the following documentation about regex expressions https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#sum
retVal = text[i];
notString retVal = text[i];