Arrays in Java

Posted: February 10, 2011 in Java

Array:

  1. uses the new operator to dynamically allocate an array of 10 elements which are initially zero, then it prints the array in tabular format.

// initializing an array

import java.awt.Graphics;

import java.applet.Applet;

public class InitArray extends Applet {

int n[];        // declare an array of integers

// initialize instance variables

public void init()

{

n = new int[ 10 ];  // dynamically allocate array

}

// paint the applet

public void paint( Graphics g )

{

int yPosition = 25;  // starting y position on applet

g.drawString( “Element”, 25, yPosition );

g.drawString( “Value”, 100, yPosition );

for ( int i = 0; i < n.length; i++ ) {

yPosition += 15;

g.drawString( String.valueOf( i ), 25, yPosition );

g.drawString( String.valueOf( n[ i ] ),

100, yPosition );

}

}

}

  1. Initializes an integer array with ten values and prints the array in tabular format.

// initializing an array with a declaration

import java.awt.Graphics;

import java.applet.Applet;

public class InitArray extends Applet {

int n[] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };

// paint the applet

public void paint( Graphics g )

{

int yPosition = 25;   // starting y position on applet

g.drawString( “Element”, 25, yPosition );

g.drawString( “Value”, 100, yPosition );

for ( int i = 0; i < n.length; i++ ) {

yPosition += 15;

g.drawString( String.valueOf( i ), 25, yPosition );

g.drawString( String.valueOf( n[ i ] ),

100, yPosition );

}

}

}

example 3 :  compute the sum of the elements of the array.

// Compute the sum of the elements of the array

import java.awt.Graphics;

import java.applet.Applet;

public class SumArray extends Applet {

int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

int total;

// initialize instance variables

public void init()

{

total = 0;

for ( int i = 0; i < a.length; i++ )

total += a[ i ];

}

// paint the applet

public void paint( Graphics g )

{

g.drawString( “Total of array elements: ” + total,

25, 25 );

}

}

  1. Example 4

public class DemoArray

{

public static void main (String[] args)

{

double[] salary = new double[4];

salary[0] = 5.25;

salary[1] = 6.55;

salary[2] = 10.25;

salary[3] = 16.85;

System.out.println(“Salaries one by one are : “);

System.out.println(salary[0]);

System.out.println(salary[1]);

System.out.println(salary[2]);

System.out.println(salary[3]);

}

}

Example 5

public class DemoArray3

{

public static void main (String[] args)

{

double[] salary = {5.25, 6.55, 10.25, 16.85};

System.out.println(“Salaries one by one are : “);

System.out.println(salary[0]);

System.out.println(salary[1]);

System.out.println(salary[2]);

System.out.println(salary[3]);

}

}

Example 6:

public class DemoArray4

{

public static void main (String[] args)

{

double[] salary = {5.25, 6.55, 10.25, 16.85};

System.out.println(“Salaries one by one are : “);

for ( int x = 0; x < 4; ++x)

System.out.println(salary[x]);

}

}

B.           String

  1. Declare and Initial an array  which contains 10,20,30,40, and 50.

Print the contents from the beginning, and print from the last element.

import java.applet.* ;

import java.awt.*;

public class IntArray extends Applet

{

public void paint(Graphics g)

{

int[] numbers = {10, 20, 30, 40, 50};

int i;

int dis=30;

for (i = 0; i<5; i++)

{

g.drawString(String.valueOf(numbers[i]),dis, 30);

dis += 20;

}

dis = 30;

for (i = 4; i>=0; i–)

{

g.drawString(String.valueOf(numbers[i]),dis, 70);

dis += 20;

}

}

}

2.  Example of  function compareTo

public class Try

{

public static void main(String[] args)

{

String myFriend = new String(“Ginny”);

System.out.println(myFriend.compareTo(“Gabby”));

System.out.println(myFriend.compareTo(“Gabriella”));

System.out.println(myFriend.compareTo(“Ghazala”));

System.out.println(myFriend.compareTo(“Hammie”));

}

}

( 8, 8, 1,-1)

3. Example of  replace.

public class Try1

{

public static void main(String[] args)

{

String myFriend = new String(“Ginny”);

String newName;

newName =myFriend.replace(‘n’,’B’);

System.out.println(newName);

}

}

  1. Example of  SubString

public class Try2

{

public static void main(String[] args)

{

String newName=”Rio Hondo College”;

String anotherName;

anotherName = newName.substring(4,10);

System.out.println(anotherName);

}

}

        example  #5 (Pg235-6): SecretPhrase.java
..............................................
To compare a String to each element in an array:
...............................................
*/
public class SecretPhrase
{
        public static void main (String[] args)throws Exception
        {
           String targetPhrase = "Plan with Us";
           String displayPhrase = "P*** W*** U*";
           char guess;
           int position;
           System.out.println("Play our game - guess our motto");
           System.out.println(displayPhrase);
           while (displayPhrase.indexOf('*') !=-1)
           {
                System.out.println("Enter a letter");
                guess = (char)System.in.read();
                System.in.read(); System.in.read();        //Absorbs Enter key
                position = targetPhrase.indexOf(guess);        //Determines position
of guess
                if (position == -1)             //if guess is not in target phrase
                    System.out.println("Sorry - guess again");
                else                     //if guess is in target phrase
                {        displayPhrase = displayPhrase.substring(0,position)
                                + guess + displayPhrase.substring(position+1,
 displayPhrase.length());
                    System.out.println(displayPhrase);
                }
           }
           System.out.println("Congratulations!");    
        }
}
/*     
        Example #6 (Pg237-8): NumInput.java
..............................................
Program that accepts integer input
...............................................
*/
public class NumInput
{
        public static void main (String[] args)throws Exception
        {
           String inputString = new String();
           char newChar;
           int inputNumber;
           System.out.println("Enter the number of guests at your event");
           newChar = (char)System.in.read();
           while (newChar >= '0' && newChar <= '9')
           {
                inputString = inputString + newChar;
                newChar = (char)System.in.read();
           }
           System.in.read();           //absorb the Enter key

           inputNumber = Integer.parseInt(inputString);
           if (inputNumber > 100 )
                System.out.println("A surcharge will apply!");
        }
}

Example 7:

// This program demonstrates the String class constructors.

import java.awt.Graphics;

import java.applet.Applet;

public class StringConstructors extends Applet {

char charArray[] = { ‘b’, ‘i’, ‘r’, ‘t’, ‘h’, ‘ ‘,

‘d’, ‘a’, ‘y’ };

byte byteArray[] = { ‘n’, ‘e’, ‘w’, ‘ ‘,

‘y’, ‘e’, ‘a’, ‘r’ };

StringBuffer buffer;

String s, s1, s2, s3, s4, s5, s6, s7;

public void init()

{

s = new String( “hello” );

buffer = new StringBuffer();

buffer.append( “Welcome to Java Programming!” );

// use the String constructors

s1 = new String();

s2 = new String( s );

s3 = new String( charArray );

s4 = new String( charArray, 6, 3 );

s5 = new String( byteArray, 0, 4, 4 );

s6 = new String( byteArray, 0 );

s7 = new String( buffer );

}

public void paint( Graphics g )

{

g.drawString( “s1 = ” + s1, 25, 25 );

g.drawString( “s2 = ” + s2, 25, 40 );

g.drawString( “s3 = ” + s3, 25, 55 );

g.drawString( “s4 = ” + s4, 25, 70 );

g.drawString( “s5 = ” + s5, 25, 85 );

g.drawString( “s6 = ” + s6, 25, 100 );

g.drawString( “s7 = ” + s7, 25, 115 );

}

}

Example 8

// Fig. 8.3: StringCompare

// This program demonstrates the methods equals,

// equalsIgnoreCase, compareTo, and regionMatches

// of the String class.

import java.awt.Graphics;

import java.applet.Applet;

public class StringCompare extends Applet {

String s1, s2, s3, s4;

public void init()

{

s1 = new String( “hello” );

s2 = new String( “good bye” );

s3 = new String( “Happy Birthday” );

s4 = new String( “happy birthday” );

}

public void paint( Graphics g )

{

g.drawString( “s1 = ” + s1, 25, 25 );

g.drawString( “s2 = ” + s2, 25, 40 );

g.drawString( “s3 = ” + s3, 25, 55 );

g.drawString( “s4 = ” + s4, 25, 70 );

// test for equality

if ( s1.equals( “hello” ) )

g.drawString( “s1 equals \”hello\””, 25, 100 );

else

g.drawString( “s1 does not equal \”hello\””,

25, 100 );

// test for equality with ==

if ( s1 == “hello” )

g.drawString( “s1 equals \”hello\””, 25, 115 );

else

g.drawString( “s1 does not equal \”hello\””,

25, 115 );

// test for equality–ignore case

if ( s3.equalsIgnoreCase( s4 ) )

g.drawString( “s3 equals s4”, 25, 130 );

else

g.drawString( “s3 does not equal s4”, 25, 130 );

// test compareTo

g.drawString( “s1.compareTo( s2 ) is ” +

s1.compareTo( s2 ), 25, 160 );

g.drawString( “s2.compareTo( s1 ) is ” +

s2.compareTo( s1 ), 25, 175 );

g.drawString( “s1.compareTo( s1 ) is ” +

s1.compareTo( s1 ), 25, 190 );

g.drawString( “s3.compareTo( s4 ) is ” +

s3.compareTo( s4 ), 25, 205 );

g.drawString( “s4.compareTo( s3 ) is ” +

s4.compareTo( s3 ), 25, 220 );

// test regionMatches (case sensitive)

if ( s3.regionMatches( 0, s4, 0, 5 ) )

g.drawString(

“First 5 characters of s3 and s4 match”,

25, 250 );

else

g.drawString(

“First 5 characters of s3 and s4 do not match”,

25, 250 );

// test regionMatches (ignore case)

if ( s3.regionMatches( true, 0, s4, 0, 5 ) )

g.drawString(

“First 5 characters of s3 and s4 match”,

25, 265 );

else

g.drawString(

“First 5 characters of s3 and s4 do not match”,

25, 265 );

}

}

Reference

http://faculty.riohondo.edu/sliu/CIT%20135/Lec_5_135.htm

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s