i

mport javax.swing.*;

public class ReverseArray {
	public static void reverse(int b[]){
		int left = 0;
		int right = b.length -1;
		
		while(left<right){
			//exchange the left and right elements
			int temp = b[left];
			b[left] = b[right];
			b[right] = temp;
			
			left++;
			right--;
		}
	}
	
	public static void main(String a[]){
		
	}
}

how should i write the main function..sorry i know it sound stupid ><''

Recommended Answers

All 3 Replies

Perhaps:

public static void main(String[] a) {
    int[] test = new int[] {0, 1, 2, 3, 4};

    reverse(test);

    for (int i = 0; i < test.length; i++)
        System.out.print(test[i] + " ");
    System.out.println();
}

If all you're doing is testing the reverse method, there's really little need to do more. Though some edge cases like null and small/zero sized arrays couldn't hurt to really test it thoroughly.

Depends where you're getting the numbers that you're reversing. Easiest thing to demonstrate that your reverse works would be to declare an int array, print it, then print the result of reverse() applied to that array.
If you want user input, you can get it from the command line, from some interactive process in the CLI, or from a GUI, in order of ease of use.

From the command line: this is what the (String[] args) part of main(String[] args) means. Everything following the class name on the command line when you call the program is passed in as part of an array of String, and main has it.

So if you were to enter java ReverseArray 22 33 44 55 66 77 88 , you'd have an array {"22", "33", "44", "55", "66", "77", 88"} in args. Use Integer.parseInt() to turn those into their numeric values, make a new aray of ints from all that, and pass it to reverse().

CLI, interactive:
This is more complicated, but not too bad. You need to use something like the Scanner class (see the java API for that, Sun has tutorials on this stuff so I won't explain it here) to get some numbers from the user, stuff the numbers into an array, and pass that to reverse()

GUI:
Ugh. Make a JFrame, put some stuff in it, use the methods provided to retrieve some numbers, stuff the numbers into an array, and pass the array to your reverse() method. Again, the best place to start with this is in the Sun tutorials.

Perhaps:

public static void main(String[] a) {
    int[] test = new int[] {0, 1, 2, 3, 4};

    reverse(test);

    for (int i = 0; i < test.length; i++)
        System.out.print(test[i] + " ");
    System.out.println();
}

If all you're doing is testing the reverse method, there's really little need to do more. Though some edge cases like null and small/zero sized arrays couldn't hurt to really test it thoroughly.

it works! thanks for your help!

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.