• Post Reply Bookmark Topic Watch Topic
  • New Topic

Finding array index number through for loop  RSS feed

 
Ranch Hand
Posts: 32
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, please take a look at this:



What program needs to find is the most biggest number. It does the job, but another task of the program is to find the index of that number . The second loop should do just that, but for some reason, as the loop goes further, it passes through the if statement even though answer "a[i]" is not equal to "answer". The idea is that if a[i] and answer are equal, the "i" should represent the index number.
 
Bartender
Posts: 2087
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. This could be done in one loop. You don't need two separate loops (one to search numer, second to search its index).
2. Check logic in your first loop. It checks if an array element is bigger than previous element. It should check it agains the current biggest number (store it in variable!). Also your program modifies the array (in first loop - line 25)! So what's the point in searching for index later!?
3. If you write a program that has two steps (like yours) always check/test if first step works correctly before trying to write second one.
4. In line 19 you assign a[i] to a[i]. This is useless in every case because you are assigning an element to itself.
5. Please, make sure you use proper indenting of your code. It makes the code more readable.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!