• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

int variable that changes

 
Ranch Hand
Posts: 42
Netbeans IDE Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Netbeans IDE Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Bartender
Posts: 689
17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
To avoid criticism do nothing, say nothing, be nothing. -Elbert Hubbard. Please critique this tiny ad:
Garden Master Course kickstarter
https://coderanch.com/t/754577/Garden-Master-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic