This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

int variable that changes  RSS feed

 
Scott M Summers
Ranch Hand
Posts: 42
Java Netbeans IDE Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In my project I have a string array filled with names. My main method asks the user to type in a name to search for. If the name is in the array it will say, "the name is found in the array." and how many comparisons it took to find that name within the array. Then vice versa if the name is not found. I need to also print out the average number of comparisons once the program ends, this being the sum of the comparisons divided by the number of searches.
I have a variable that keeps track of the number of searches, int numberOfSearches, and I have a variable, int comparisons, that is the comparisons for one search. Is there a way to have a variable, int totalComparisons, that is the sum of my comparisons?

 
Scott M Summers
Ranch Hand
Posts: 42
Java Netbeans IDE Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
totalComparisons = (totalComparisons + comparisons + 1);

This is the answer I came up with to my problem, and it seems to work.
 
Mike. J. Thompson
Bartender
Posts: 689
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It seems unintuitive to have totalComparisons = totalComparisons + comparisons + 1.

If I see a variable named comparisons I would expect it to contain the number of comparisons that were made, not the number of comparisons - 1.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!