• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

display array

 
Walt Bryant
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Howdy,
I am taking a java class. We are to the point of learning about arrays. In the textbook there is an example given to sort an array in descending order. I can get the code to compile but I can't figure out how to display the sorted array. The code is:



I have tried System.out.println(usersNumbers [b] );
With this output statement I get the number 7.
I am trying to get 88 14 7 3 2

Thanks for any help.

[edit]Add code tags. CR[/edit]
[ November 15, 2008: Message edited by: Campbell Ritchie ]
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Walt,

Welcome to JavaRanch!

In Java 1.5 and up (which you're almost certainly using) there are some handy "toString()" routines in the java.util.Arrays class:

System.out.println(Arrays.toString(usersNumbers));

would do the trick. But you might want to do it yourself, just for learning's sake, in which case the right thing to do is write a little method that uses a "for" loop to print the value of each array element, one at a time, following each by a space.
 
Walt Bryant
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your help. I think I'm getting close. This is what I've got so far:



The array does not appear to be going through the code that sorts it into descending order. The output from the method is:
The array sorted in descending order is: 7 14 3 88 2
Is it because of where the method call is placed?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This line:

for (b = 0; b > usersNumbers.length - 1; ++b)

says "set b to 0; then, while b is larger than usersNumbers.length - 1, do the following..." Should be "<", not ">", yes?

In any case, it's pretty confusing that the code to sort the data is there in main(), but there's a method called "sortDescending()" which, rather than sorting anything, displays the array's contents. Shouldn't the method be called, "display()" or "printArray()" or something along those lines?
 
Walt Bryant
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you, Thank You, Thank You. Should be "<", not ">" was the problem. I also changed sortDescending ( ) to printArray ( ). I think I understand now. I really do appreciate your help.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic