Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Whats wrong with this code? public int method

 
Sara Lyons
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Whats wrong with this code? I haven't a clue about public int method
Don't change anything inside the method.
When I tried to compile it it said :

Study.java:17: error: missing return statement
}
^
1 error

class Study
{
private int strange;
public int strange(String sentence)
{
boolean isSpace = false;
int count = 0;
for (int i = 1; i < sentence. length ( ) ; i++)
{
isSpace = (sentence.charAt(i) == ' ');
if(isSpace&&sentence.charAt(i-1) == 'e')
{
count = count + 1;
return count;
}
}
}//this is line 17
}
Thanks
 
Ulf Dittmer
Rancher
Pie
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The method is declared to return an "int" - so it must return an int under all circumstances. As it is, it may reach the end of the for loop - where there is no return statement, so the JVM doesn't know what to return. You need to add a statement that returns some value. I'm not sure what the code is supposed to do, so I don't know whether that should be an error code of some kind or something else. But yes - you will need to change the body of the method, there's no way around that.
 
Sara Lyons
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ulf Dittmer wrote:The method is declared to return an "int" - so it must return an int under all circumstances. As it is, it may reach the end of the for loop - where there is no return statement, so the JVM doesn't know what to return. You need to add a statement that returns some value. I'm not sure what the code is supposed to do, so I don't know whether that should be an error code of some kind or something else. But yes - you will need to change the body of the method, there's no way around that.

Well I was looking at some past exam paper questions and one of the questions says what is the value of the following method calls: strange("one two three four") and strange("is there a bee in there") for this code:
public int strange(String sentence)
{
boolean isSpace = false;
int count = 0;
for (int i = 1; i < sentence. length ( ) ; i++)
{
isSpace = (sentence.charAt(i) == ' ');
if(isSpace&&sentence.charAt(i-1) == 'e')
{
count = count + 1;
return count;
}
}
So I was trying to compile it one my computer but not really sure what code goes before and after it since I don't have a clue about that int method
 
Dennis Grimbergen
Ranch Hand
Posts: 159
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sara Lyons wrote:

I guess you just need to put the return statement somewhere else
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic