wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Reverse an array in java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Reverse an array in java" Watch "Reverse an array in java" New topic
Author

Reverse an array in java

Michael Pickens
Greenhorn

Joined: Mar 01, 2012
Posts: 24
I am working on yet another homework assignment. This assignment is asking me to write a program which creates an array with its size determined by users and filled with random numbers between 1 and 100.

I must obtain the number of random numbers from the user through a GUI dialog box.
The 2 guidelines that my professor is requiring are:
1) My program should have at least two methods, "displayArray" and "reverse"
2) I am not allowed to create a new array within the method "reverse" to perform the task.

I have this code completely written, and I am having trouble reversing ALL the digits.

Output of my program: 7 random digits
myArray[0] = 5
myArray[1] = 14
myArray[2] = 88
myArray[3] = 18
myArray[4] = 20
myArray[5] = 8
myArray[6] = 46
myArray[7] = 100
After reversing the array
myArray[0] = 100
myArray[1] = 46
myArray[2] = 8
myArray[3] = 20
myArray[4] = 20
myArray[5] = 8
myArray[6] = 46
myArray[7] = 46

And since I am not allowed to simply make a new array, the code posted below is how I am handling the reverse.



Thanks again for the help.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18495
    
  40

Michael Pickens wrote:I am working on yet another homework assignment. This assignment is asking me to write a program which creates an array with its size determined by users and filled with random numbers between 1 and 100.

I must obtain the number of random numbers from the user through a GUI dialog box.
The 2 guidelines that my professor is requiring are:
1) My program should have at least two methods, "displayArray" and "reverse"
2) I am not allowed to create a new array within the method "reverse" to perform the task.

I have this code completely written, and I am having trouble reversing ALL the digits.

Output of my program: 7 random digits
myArray[0] = 5
myArray[1] = 14
myArray[2] = 88
myArray[3] = 18
myArray[4] = 20
myArray[5] = 8
myArray[6] = 46
myArray[7] = 100
After reversing the array
myArray[0] = 100
myArray[1] = 46
myArray[2] = 8
myArray[3] = 20
myArray[4] = 20
myArray[5] = 8
myArray[6] = 46
myArray[7] = 46

And since I am not allowed to simply make a new array, the code posted below is how I am handling the reverse.



Thanks again for the help.


Take out some paper and a pen, and play compuiter -- follow your code, with some data, and you will quickly see what you are doing wrong.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Michael Pickens
Greenhorn

Joined: Mar 01, 2012
Posts: 24
I have run through this with pencil and paper several times. I am not catching the error. I thought that since I really only need to go through half of the array that I could do arrayOne.length / 2, but that of course only gives me half of the array, but chops off the non reversed section.

Thanks.
John Jai
Bartender

Joined: May 31, 2011
Posts: 1776

If the intention is to copy a content using temp variable I will do like
A = temp;
A = B;
B = temp;
Is your B holder the same in both the places?
Michael Pickens
Greenhorn

Joined: Mar 01, 2012
Posts: 24
I changed that code to match:

John Jai
Bartender

Joined: May 31, 2011
Posts: 1776
Ok what happened when you tried by length / 2 in the changed code? Can you show us what you tried?
Michael Pickens
Greenhorn

Joined: Mar 01, 2012
Posts: 24
I changed the code to try to adjust the length. I see from doing a series of println statements .. that I am only switching the first and last statements, then switching them back.



What started out for me as a logical process has now turned into a big guessing game . when i added the /2 to the length, it only prints out like this:
myArray[0] = 36
myArray[1] = 91
myArray[2] = 56
myArray[3] = 22
myArray[4] = 14
myArray[5] = 37
myArray[6] = 49
After reversing the array
myArray[0] = 49
myArray[1] = 37
myArray[2] = 14

thus you can see I am missing 4 out of 7 indexes.. i suppose that is because arrayOne.length/2 = 3 (7/2=3).
John Jai
Bartender

Joined: May 31, 2011
Posts: 1776
I guess you got the logic correct in reversing the array. The problem should be in the print statement within the for loop. It only prints as long as the loop checks the value of i.

Have the print statement as a separate and try to print all contents of the array & check.
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 7484
    
  18

Michael Pickens wrote:What started out for me as a logical process has now turned into a big guessing game . when i added the /2 to the length, it only prints out like this:

I suspect it's because you haven't "played computer" enough yet. You really do need to understand the problem before you can code it, so my advice to you is:
TURN YOUR COMPUTER OFF.
And, rather than writing Java code, try to describe the reversing process in English (or your native language).

What exactly are you doing inside the loop (ie, on each iteration)?
It might make it clearer if you actually put it into a separate method; and if you did, what would you call it?

thus you can see I am missing 4 out of 7 indexes.. i suppose that is because arrayOne.length/2 = 3 (7/2=3).

Again, I think you're getting a bit bogged down in the detail.
Tip: You are NOT restricted to only one index inside a for loop. It's quite permissible to do something like:
for (int i = 0, j = 10; {some condition}; i++, j++) { ...
(NOTE: The above is for illustration only)

HIH

Winston


Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37879
    
  22
I would also suggest you do it the object-oriented way, which is not to create new objects. Not in this instance. You write yourself a utility class, which has all static members. You give it a private constructor, so nobody can instantiate that class. You give it some methods. In this case you require two methods. You can add more methods as you find more uses for that class. This is what it looks like.You can overload those methods to take all 9 kinds of array as parameters.
Get the swapTwoElementsInArray method working first, then you can consider the reverseArray method. The reverseArray method will of course use the swap method.
Note you have the iffy design feature of output parameters. Rather than creating new objects, you are manipulating the object whose memory location is passed as an argument. Something you need to be careful about.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11149
    
  16

a method should do one thing, and one thing only, and should be named accordingly. So a method named "reverse" should not print anything. it should reverse something.

If you want to print an array, write a method called 'printArray'.

The idea is to write small, simple methods that can be tested into oblivion so that you are SURE they work...then you use them whenever you need to, however you need to.

If someone worked for me wrote a method that tried to both print and reverse an array, I'd delete it and tell them to start over.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

fred rosenberger wrote:
The idea is to write small, simple methods that can be tested into oblivion so that you are SURE they work...then you use them whenever you need to, however you need to.


And, in case it's not clear, you test them independently of each other.

So you write your reverse() method, you fix the syntax errors so it compiles, then you write a tiny little main() method that does nothing but reverse a hard-coded array. You look at the results to make sure they are what they should be. Only when that works perfectly do you move on.

Totally independently of that, you write a printArray() method. You fix the syntax errors so it compiles. Then you write a tiny little main() method that does nothing but print a hard-coded array. You look at the results to make sure they are what they should be. Only when that works perfectly do you move on.

Then you combine those two methods. You write a tiny little main() that reverses a hardcoded array and then prints out the results. You compare those results to what you know they should be. Only when this part works, do you move on.

Maybe you have a requirement to generate a random array for reversal and printing, or take input from a user to put into an array for reversal an printing. Whatever this other requirement is, you follow the same procedure: Design, code, test, debug completely on its own, and then put it together with the other pieces that you know are already working.
Michael Pickens
Greenhorn

Joined: Mar 01, 2012
Posts: 24
Thanks for all your help. I didnt turn on my computer, read the post on my phone, and started jamming on paper. Then it occurred to me.. why am I swapping, why don't i Just reverse it through a for loop..

I want to rewrite this later with a separate final print method, but I could not get it to work right.



here is my final snippet of code.

I appreciate the help, some of the help was above my understanding currently, but at least it gives me something to think about..

Cheers.



Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37879
    
  22
You haven’t reversed anything. You have simply displayed your array in reverse. Are you sure that is what you are supposed to do? The original post wasn’t at all clear on that point.
Michael Pickens
Greenhorn

Joined: Mar 01, 2012
Posts: 24
That is a good question..... I didn't realize that I was just doing that.. sigh.

and now that i look.. the indexes are also reversed..

myArray[0] = 40
myArray[1] = 37
myArray[2] = 62
myArray[3] = 60
myArray[4] = 3
myArray[5] = 79
myArray[6] = 43
myArray[7] = 65
After reversing the array
myArray [7] = 65
myArray [6] = 43
myArray [5] = 79
myArray [4] = 3
myArray [3] = 60
myArray [2] = 62
myArray [1] = 37
myArray [0] = 40

I dont know what to do. Pen and paper "playing computer" doesn't make sense to me. When I do it, i pretend that my array size is 5 and trace it through. I see that when I swap, that I end up swapping back with the third swap... I do not understand how to fix the problem. I have also made it so the last numbers will reverse, but it is either the first half of numbers or the 2nd half of numbers. I tried writing 2 methods.. one that would reverse the fist half and one that would reverse the 2nd half.. but of course, as you guessed, didn't compile and I did not no how to fix that. We have not studied objects as of yet.. that is the last chapter we are doing this semester. I have a mid term tomorrow in this class on loops, methods, and arrays (to give you an idea of where I am at.)
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 7484
    
  18

Michael Pickens wrote:I dont know what to do. Pen and paper "playing computer" doesn't make sense to me. When I do it, i pretend that my array size is 5 and trace it through. I see that when I swap, that I end up swapping back with the third swap... I do not understand how to fix the problem.

That's because you're fixated on doing it one particular way. As I said above you are NOT constrained to using just one index.

Think some more about it.

Winston
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11149
    
  16

Think about the problem in real world terms. I like to think of arrays as egg cartons, and the elements as eggs.

So, let's say you have an egg carton that can hold up to 12 eggs. The eggs, for whatever reason, have numbers written on them so you can identify them (but for the purpose of this exercise, the specific numbers don't matter). The slots in the carton are also numbered, so you can say "look at the egg in slot #4" or "look at the egg in slot #10 and read the number on it".

How would you, using your hands, reverse the order of the eggs? Note that a slot can only hold one egg. You can't put an egg into a slot that is already occupied, or else you will smash it, and loose that egg forever.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37879
    
  22
And I have already told you how you can use a swap method to reverse the whole thing.
Michael Pickens
Greenhorn

Joined: Mar 01, 2012
Posts: 24
After thinking all day and jotting stuff down on paper I decided to add the second variable to the method and to create a separate method to print the reversed array.

There is an error that says j cannot be resolved or is not a field.. I don't understand what it means or wants me to do. Here is the code I came up with to swap these indexes.



they way I wrote this out on sever sheets of paper, i hope it works.

Thanks again for all the help. The egg carton example and realizing that i was indeed fixated on writing the code one way really helped. Though I did not know you could put 2 variables into a for loop with 2 sets of parameters, and 2 increments. I am obviously doing it wrong. Can i just separate the two for statements within the same method so I don't get the errors, using the first one to swap the first half of the indexes, and the 2nd one to swap the 2nd half of the indexes?
Michael Pickens
Greenhorn

Joined: Mar 01, 2012
Posts: 24
WOO again as I was typing the last reply, I found my answer!!



You guys are awesome. I love hanging out on the ranch!

Thanks again for all your help, sorry I am so frustrating to help!
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37879
    
  22
You got there in the end. There are some people who never seem to get there at all.

You have, however, I think managed to do it the hard way. You only need one loop. The first half of the loop reverses the array, and the second half reverses it again. Twice!
It is a very common problem, thinking that you use commas inside the () after for. You don’t; you use semicolons.

Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 7484
    
  18

Michael Pickens wrote:WOO again as I was typing the last reply, I found my answer!!

Well done! And now that you've done it for yourself, here's the way to combine the two loops:See what I mean about using two indexes?

Also, as Campbell mentioned above, if you take out the body of the loop and put it in a swap() method, you don't have to repeat the code for your two loops.

Thanks again for all your help, sorry I am so frustrating to help!

Not at all. Glad you got there in the end.

Winston
 
Consider Paul's rocket mass heater.
 
subject: Reverse an array in java
 
Similar Threads
Constructing multidimensional arrays
Multidimensional Arrays
reverse array
How to get a method to call a method
Printing Int Array to File using PrintWriter