hi.i realy need help am a new beginner in java.so i have been trying to do a code in java that returns the largest counter,refering to my libraries.so i was trying to invoke the method comparTo,so i dont know how to use it to compare all counter arrays so that i could the largest one

                   for( i=1;i<n;i++)

                         System.out.println(arr[i] + "largst count");

Recommended Answers

All 3 Replies

we don't know what type your objects are, so not going to talk about how to compare them.
but, comparing them to 0? let's say all your elements are -1, then you'll get a wrong result. let's assume on the other hand, all your elements are positive, then each element will be printed.

try this logic instead:
* keep a temporary variable instantiated before starting the loop, with the same value as the first value of your array
* iterate over your array. if the element you iteration passes is bigger compared to the one in your temporary variable, replace the value of the temporary value with that of the current element
* after succesfully iteration over the entire array, print
tempVariable + ' is the greatest counter'.

An even simpler way would be to sort the array, and to print the last (or first, depending on how you sort) element

thanx great idea,will use bubble sort in ascending order then (1,2,3)the last counter will be the largest.

Sorting the array is massive overkill for just finding the largest entry, and permanently changes the array, which may also be undesirable.

stultuske's "try this logic instead" approach is by far the best.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.