• Post Reply Bookmark Topic Watch Topic
  • New Topic

Recursive mehtod returning different results in codingbat.com than in eclipse?  RSS feed

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

The recursive method below returns correct results when run in Eclipse, but when run in codingbat.com ( http://codingbat.com/prob/p101409), it runs, but returns wrong results. I've posted the code for both. Can someone tell my why this differences occurs?

Thank you,

Paul

The problem:
Given a non-negative int n, return the count of the occurrences of 7 as a digit, so for example 717 yields 2. (no loops). Note that mod (%) by 10 yields the rightmost digit (126 % 10 is 6), while divide (/) by 10 removes the rightmost digit (126 / 10 is 12).

count7(717) → 2
count7(7) → 1
count7(123) → 0
-------------------------------------
The method as I enter it in coding bat - returns 9 answer should be 3

      
---------------------------------
Same method but run in eclipse: returns 3 --the correct answer

 
Edward Spencer Spencer
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Update:

I tried this same method in BlueJ and it worked there also.
 
Sheriff
Posts: 22846
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The CodingBat online application isn't resetting the "count" variable to zero each time before each time the count7() method is called at the top level (in your case, in the main() method). Your code doesn't either but your code only tests one value, whereas CodingBat tests more than one value and thus exposes the error. Try this instead:

 
Edward Spencer Spencer
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
Thanks the variable is indeed the issue but I changed the code to not using one and it works;
 
Paul Clapham
Sheriff
Posts: 22846
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Excellent! But... what does count7(700) return?
 
Marshal
Posts: 56610
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is that really supposed to be a recursive method? In that it calls itself, it is, but surely you shou‍ld be adding the result of count7(n / 10) to the current count?
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!