Title: Arrays Part2 Misc
Course: CPS 161: An Intro to Programming with Java - DL MM MASTER

Arrays Part2 Miscellaneous

Enumerated Types

EnumDemo.java



public class EnumDemo
{
    enum WorkDay {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY};

    public static void main(String[] args)
    {
        WorkDay startDay = WorkDay.MONDAY;
        WorkDay endDay = WorkDay.FRIDAY;

        System.out.println("Work starts on " + startDay);
        System.out.println("Work ends on " + endDay);
    }
}


EnumDemoOld.java

// The following is how I would have done this before Enumerated types became available
// around Java release 1.5:

public class EnumDemoOld {
	
	static final int  MONDAY=0;
	static final int  TUESDAY=1;
	static final int  WEDNESDAY=2;
	static final int  THURSDAY=3;
	static final int  FRIDAY=4;

	public static void main(String[] args) {

		int startDay = MONDAY;
		int endDay = FRIDAY;

		System.out.println("Work starts on " + startDay);
		System.out.println("Work ends on " + endDay);


	}

}



EnumValuesDemo.java


import java.util.Scanner;

public class EnumValuesDemo
{

    enum WorkDay {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY};

    public static void main(String[] args)
    {
        WorkDay[] day = WorkDay.values( );

        Scanner keyboard = new Scanner(System.in);
        double hours = 0, sum = 0;

        for (int i = 0; i < day.length; i++)
        {
            System.out.println("Enter hours worked for " + day[i]);
            hours = keyboard.nextDouble( );
             sum = sum + hours;
        }

        System.out.println("Total hours work = " + sum);
    }
}


EnumSwitchDemo.java



import java.util.Scanner;

public class EnumSwitchDemo
{
    enum Flavor {VANILLA, CHOCOLATE, STRAWBERRY};

    public static void main(String[] args)
    {
        Flavor favorite = null;
        Scanner keyboard = new Scanner(System.in);

        System.out.println("What is your favorite flavor?");
        String answer = keyboard.next();
        answer = answer.toUpperCase();
        favorite = Flavor.valueOf(answer);

        switch (favorite)
        {
            case VANILLA:
                System.out.println("Classic");
                break;
            case CHOCOLATE:
                System.out.println("Rich");
                break;
            default:
                System.out.println("I bet you said STRAWBERRY.");
                break;
        }
    }
}



Months.java


enum Month {January, February, March, April, May, June, July, August,
    September, October, November, December};


public class Months {


    public static void main(String[] args) {
        Month[] theMonths = Month.values();
        for (int i=0; i < theMonths.length; i++)
        {
            System.out.print(theMonths[i].ordinal()+ ".) ");
            System.out.println(theMonths[i]);
            switch(theMonths[i])
            {
            case February:
                System.out.println(" has 28 or 29 days");
                break;
            case April:
            case June:
            case September:
            case November:
                System.out.println(" has 30 days");
                break;
            default:
                System.out.println(" has 31 days");
                break;
            }
        }

        // A few more examples:
        Month m1 = Month.October;
        Month m2 = Month.August;
        System.out.println("m1.compareTo(m2) " + m1.compareTo(m2));


    }

}



Summary of enumerated type capabilities

- Month m = Month.valueOf("May");
Month m2 = Month.valueOf("July");
- int x = m.ordinal();
- int x =m.compareTo(m2);
- Month[] months = Month.values();
- == works the same as equals
- enumerated types work in a switch statement

Chess

Consider creating an example of chess Pieces using enumerated types. Create an enumerated type of ChessPieceType, and a class called ChessPiece. Construct an array of chess pieces.


package Chess;


enum ColorType {black, white};
enum PieceType {Pawn, Rook, Knight, Bishop, Queen, King};



class ChessPiece
{
    int xSquare, ySquare;
    PieceType pieceType;
    ColorType color;

    ChessPiece (PieceType p, ColorType color, int xSquare, int ySquare)
    {
        this.pieceType=p;
        this.color = color;
        this.xSquare = xSquare;
        this.ySquare = ySquare;
    }


}


class ChessGame
{
	ChessPiece[] chessPieces = new ChessPiece[32];
	ChessGame()
	{
		// Fill in all the chessPieces and their locations
        int index=0;

        for (int i=0; i < 8; i++) // black pawns in row 1
        {
            chessPieces[index++] = new ChessPiece(PieceType.Pawn, ColorType.black, i, 1);
        }
        for (int i=0; i < 8; i++) // white pawns in row 6
        {
            chessPieces[index++] = new ChessPiece(PieceType.Pawn, ColorType.white, i, 6);
        }

        PieceType[] startingKingRow={PieceType.Rook, PieceType.Knight, PieceType.Bishop,
                 PieceType.Queen, PieceType.King,
                 PieceType.Bishop,PieceType.Knight,PieceType.Rook};

        for (int i=0; i < 8; i++) // black king row in row 0
        {
            chessPieces[index++] = new ChessPiece(startingKingRow[i], ColorType.black, i, 0);
        }
        for (int i=0; i < 8; i++) // white king row in row 7
        {
            chessPieces[index++] = new ChessPiece(startingKingRow[i], ColorType.white, i, 7);
        }
	}
	public static void main(String[] args)
	{
		ChessGame game = new ChessGame();
		
		ColorType[] colorTypes= ColorType.values();
		PieceType[] pieceTypes = PieceType.values();
		
		int[][] pieceCounts = new int[colorTypes.length][pieceTypes.length];
		
		for (int i=0; i < game.chessPieces.length; i++)
		{
			int colorIndex = game.chessPieces[i].color.ordinal();
			int pieceIndex = game.chessPieces[i].pieceType.ordinal();
			pieceCounts[colorIndex][pieceIndex] += 1;
		}
		for (int i=0; i < pieceCounts.length; i++)
		{
			String colorStr = colorTypes[i].toString();
			for (int j=0; j < pieceCounts[i].length; j++)
			{
				String typeStr = pieceTypes[j].toString();
				System.out.println(colorStr + " "+ typeStr + " : " + pieceCounts[i][j]);
			}
		}
		
	}
}


For-each loop:

consider the following alternatives:

public class ForEach {

    public static void main(String[] args) {
        int[] a = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
        for (int i=0; i < a.length; i++)
            System.out.println(a[i]);

        // With a for-each loop the equivalent logic is:
        for (int element : a)
            System.out.println(element);

        // Note the following doesn't do anything:
        for (int element : a)
            element = 0;

        System.out.println("**************************");
        for (int i=0; i < a.length; i++)
            System.out.println(a[i]);

    }

}



Variable number of parameters on a method call

The most notable place this is used is System.out.printf:



public class PrintfExample {

    public static void main(String[] args) {
        int x=11;
        double d=1.123;
        String s= " something ";

        System.out.printf("Just a String%n");  // 1 parameter
        System.out.printf("parm1=%d     %n", x);  // 2 parameters
        System.out.printf("parm1=%d parm2=%f    %n", x,d);  // 3 parameters
        System.out.printf("parm1=%d parm2=%f parm3=%s  %n", x,d,s);  // 4 parameters


    }

}



UtilityClass.java


import java.util.Scanner;


public class UtilityClass
{
    /**
     Returns the largest of any number of int values.
     */
    public static int max(int... arg)
    {
        if (arg.length == 0)
        {
            System.out.println("Fatal Error: maximum of zero values.");
            System.exit(0);
        }

        int largest = arg[0];
        for (int i = 1; i < arg.length; i++)
            if (arg[i] > largest)
                largest = arg[i];
        return largest;
    }
    public static void main(String[] args)
    {
        System.out.println("Enter scores for Tom, Dick, and Harriet:");
        Scanner keyboard = new Scanner(System.in);
        int tomsScore = keyboard.nextInt( );
        int dicksScore = keyboard.nextInt( );
        int harrietsScore = keyboard.nextInt( );

        int highestScore = UtilityClass.max(tomsScore, dicksScore, harrietsScore);

        System.out.println("Highest score = " + highestScore);
    }
}


Utility2.java


import java.util.Scanner;


public class Utility2
{
    /**
     Returns the first argument with all occurrences of other arguments deleted;
     */
    public static String censor(String sentence, String...  unwanted)
    {
        for (int i = 0; i < unwanted.length; i++)
            sentence = deleteOne(sentence, unwanted[i]);
        return sentence;
    }

    /**
     Returns sentence with all occurrences of oneUnwanted removed.
     */
    private static String deleteOne(String sentence, String oneUnwanted)
    {
        String ending;
        int position = sentence.indexOf(oneUnwanted);
        while (position >= 0) //While word was found in sentence
        {
            ending = sentence.substring(position + oneUnwanted.length( ));
            sentence = sentence.substring(0, position) + ending;
            position = sentence.indexOf(oneUnwanted);
        }
        return sentence;
    }

    public static void main(String[] args)
    {
        System.out.println("What did you eat for dinner?");
        Scanner keyboard = new Scanner(System.in);
        String sentence = keyboard.nextLine( );
        sentence = Utility2.censor(sentence,
                "candy", "french fries", "salt", "beer");
        sentence = Utility2.censor(sentence, " ,"); //Deletes extra commas
        System.out.println("You would be healthier if you could answer:");
        System.out.println(sentence);
    }
}



Last Modified: September 30, 2013 5:12 AM