Categories

Tools

bitdefender

1&1 Web Hosting

An example of how to use arrays in Java, how to sort the items and how to mix them


Code:

import java.util.*;

public class ArrayTest 
{
	public static void main (String [] args)
	{
		// Declare an array of String
		String[] customers = {   
			"Arianne",
			"Bill", 
			"David", 
			"Manuel", 
			"Veronic", 
			"Asia", 
			"Daniel", 
			"Renate", 
			"Vincent", 
			"Alexia" 
			};
		
		Print(customers, "List of customers:");
		
		// Order the array
		Arrays.sort(customers);
		Print(customers, "List of customers, after order:");
		
		// Shuffle the array
		Shuffle(customers);
		Print(customers, "List of customers, after shuffle:");
			
		System.exit(0);
	}
	
	// Print content of the array
	private static void Print(String[] a, String t)
	{
		System.out.println( t );
		for(int n=0; n<a.length; n++)
			System.out.println("["+n+"] " + a[n] );
		System.out.println( );	
	}

	// Shuffle all elements of the array
	private static void Shuffle(String[] a) 
	{
		int n = a.length;
		for (int i = 0; i < n; i++) 
		{
		int s = i + (int) (Math.random() * (n-i));
		Swap(a, i, s);
		}
	}
	
	// Swap the content of two elements of the array
	private static void Swap(String[] a, int i, int j)
  { String swap = a[i]; a[i] = a[j]; a[j] = swap; } }

Result:

>java -cp . ArrayTest
List of customers:
[0] Arianne
[1] Bill
[2] David
[3] Manuel
[4] Veronic
[5] Asia
[6] Daniel
[7] Renate
[8] Vincent
[9] Alexia

List of customers, after order:
[0] Alexia
[1] Arianne
[2] Asia
[3] Bill
[4] Daniel
[5] David
[6] Manuel
[7] Renate
[8] Veronic
[9] Vincent

List of customers, after shuffle:
[0] Manuel
[1] Bill
[2] Daniel
[3] Alexia
[4] Renate
[5] Veronic
[6] Asia
[7] Arianne
[8] Vincent
[9] David

>Exit code: 0

Posted in Java by MdmSoft

If our work has been of help, you can help us with a small donation...
Our programmers will thank you!



All information contained in this web site are the property of MdmSoft. The information is provided "as is", MdmSoft will not be liable for any misuse of the code contained in these pages, nor can it be for inaccuracies, grammatical errors or other factors that may have caused damage or lost earnings. MdmSoft is not responsible for the content of comments posted by users.
The examples in this area have the educational and demonstration purposes only, and may be copied only for your reference, but cannot be used for commercial purposes, or for any other purpose, without the express written consent of MdmSoft.
MdmSoft also reserves the right to change, without notice, to your liking this web site, the pages and its sections, and may suspend temporarily or definitely the various services included on this site.
While using this site, you agree to have read and accepted our Terms of Service and Privacy Policy.