put comments on it and do some adjustments (need it asap)

profilehammeryuan
2.docx

Q1. Consider a two-by-three integer array t. (14 points)

a) Write a statement that declares and creates t.

int t [] [] = new int [2] [3];

b) How many rows does t have?

It has two rows;

c) How many columns does t have?

It has three columns;

d) How many elements does t have?

It has six elements;

e) Write access expressions for all the elements in row 1 of t.

t[1] [0], t[1][1],t[1][2];

f) Write access expressions for all the elements in column 2 of t.

t[0][2],t[1][2];

g) Write a single statement that sets the element of t in row 0 and column 1 to zero.

t[0][1]=0;

h) Write individual statements to initialize each element of t to zero.

t[0][0] = 0;

t[0][1] = 0;

t[0][2] = 0;

t[1][0] = 0;

t[1][1] = 0;

t[1][2] = 0;

i) Write a nested for statement that initializes each element of t to zero.

for ( int j =0; j<t.length; j++)

for(int k = 0; k<t[j].length; k++)

t[j][k] = 0;

j) Write a nested for statement that inputs the values for the elements of t from the

user.

Scanner keyboard = new Scanner (System.in);

for ( int r = 0; r<t.length; r++)

for(int c = 0; c < t[r].length; c++)

t[r][c] = keyboard.nextInt();

k) Write a series of statements that determines and displays the smallest value in t.

int small = t[0] [0];

for ( int x = 0; x < t.length; x++)

for( int y = 0; y < t[x].length; y++)

{

if (t[x][y] < small)

small = t[x][y];

}

System.out.println(“Smallest Value :” + small);

l) Write a single printf statement that displays the elements of the first row of t.

System.out.printf(t[0][0] + “” + t[0][1] + “” +t[0][2]);

m) Write a statement that totals the elements of the third column of t. Do not use

repetition.

InTotal = t[0][2] + t[1][2];

n) Write a series of statements that displays the contents of t in tabular format. List

the column indices as headings across the top, and list the row indices at the left

of each row

System.out.println(“ 0 1 2 “ ) ;.

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

{

System.out.print(i + “”);

for (int j = 0; j < t[1].length; j++)

System.out.print(t[i][j] + “”);

System.out.println();

}

Q2. (Game of Craps) (10 points)

a) How many games are won on the first roll, second roll, …, twentieth roll and after

the twentieth roll?

b) How many games are lost on the first roll, second roll, …, twentieth roll and after

the twentieth roll?

c) What are the chances of winning at craps? [Note: You should discover that craps

is one of the fairest casino games. What do you suppose this means?]

d) What is the average length of a game of craps?

e) Do the chances of winning improve with the length of the game?

/

import java.util.Random;

public class GameOfCraps {

private Random randomNumbers=new Random();

private enum Status{Continue, Won, Lost};

int[] GamesWon;

int[] GamesLost;

int winTotal;

int loseTotal;

public void play() {

int totalOfDice=0;

int myPoints=0;

Status gameStatus;

int roll;

GamesWon=new int[22];

GamesLost=new int[22];

for(int x=1; x<=1000; x++){

totalOfDice=rollDice();

roll=1;

switch(totalOfDice){

case 7:

case 11:

gameStatus=Status.Won;

break;

case 2:

case 3:

case 12:

gameStatus=Status.Lost;

break;

default:

gameStatus=Status.Continue;

myPoints=totalOfDice;

break;

}

while(gameStatus==Status.Continue){

totalOfDice=rollDice();

roll++;

if(totalOfDice==myPoints)

gameStatus=Status.Won;

else if(totalOfDice==7)

gameStatus=Status.Lost;

}

if(roll>21)

roll=21;

if(gameStatus==Status.Won){

GamesWon[roll]++;

winTotal++;

}

else{

GamesLost[roll]++;

loseTotal++;

}

}

printStats();

}

public void printStats(){

int totalGames=winTotal+loseTotal;

int length=0;

int RollsToWin;

int RollsToLose;

for(int x=1; x<=21; x++){

if(x==21)

System.out.printf("\n%d games won and %d games lost on rolls after the 20th roll", GamesWon[21],GamesLost[21] );

else

if(x<=21)

System.out.printf("\n%d games won and %d games lost on roll %d", GamesWon[x], GamesLost[x], x);

RollsToWin=(1*GamesWon[1])+(2*GamesWon[2])+(3*GamesWon[3])+

(4*GamesWon[4])+(5*GamesWon[5])+(6*GamesWon[6])+(7*GamesWon[7])+

(8*GamesWon[8])+(9*GamesWon[9])+(10*GamesWon[10])+(11*GamesWon[11])+

(12*GamesWon[12])+(13*GamesWon[13])+(14*GamesWon[14])+(15*GamesWon[15])+

(16*GamesWon[16])+(17*GamesWon[17])+(18*GamesWon[18])+(19*GamesWon[19])+

(20*GamesWon[20])+(21*GamesWon[21]);

RollsToLose=(1*GamesLost[1])+(2*GamesLost[2])+(3*GamesLost[3])+

(4*GamesLost[4])+(5*GamesLost[5])+(6*GamesLost[6])+(7*GamesLost[7])+

(8*GamesLost[8])+(9*GamesLost[9])+(10*GamesLost[10])+(11*GamesLost[11])+

(12*GamesLost[12])+(13*GamesLost[13])+(14*GamesLost[14])+(15*GamesLost[15])+

(16*GamesLost[16])+(17*GamesLost[17])+(18*GamesLost[18])+(19*GamesLost[19])+

(20*GamesLost[20])+(21*GamesLost[21]);

length=(RollsToLose+loseTotal)+(RollsToWin+winTotal);

}

if((GamesWon[1]/GamesWon[1]+GamesLost[1])>(GamesWon[3]/GamesWon[3]+GamesLost[3])&&(GamesWon[3]/GamesWon[3]+GamesLost[3])>(GamesWon[5]/GamesWon[5]+GamesLost[5]))

System.out.printf("\nChances of winning decrease as rolls increase");

else

System.out.printf("\nChances of winning increase as rolls increase");

System.out.printf("\n%s %d / %d = %.2f%%\n", "The chances of winning are", winTotal, totalGames, (100.0*winTotal/totalGames));

System.out.printf("The average game length is %.2f rolls.\n", ((double)length/totalGames));

}

public int rollDice(){

int die1=1+randomNumbers.nextInt(6);

int die2=1+randomNumbers.nextInt(6);

int sum=die1+die2;

return sum;

}

public static void main(String args[]){

GameOfCraps game=new GameOfCraps();

game.play();

}

}

Q3. (Simulation: The Tortoise and the Hare)

import java.util.*;

public class tortouseAndHare

{public static void main(String []args)

{int finish=70,tort=1,hare=1,rtime=0;

System.out.println("ON YOUR MARK, GET SET\nBANG !!!!!\nAND THEY'RE OFF !!!!!\n");

do

{hare=movehare(hare);

tort=movetort(tort);

print(tort,hare);

rtime++;

}while(tort<finish&&hare<finish);

if(tort>hare )

System.out.println("TORTOISE WINS!!! YAY!!!\n");

else if(tort<hare )

System.out.println("Hare wins. Yuch. \n");

else

System.out.println("Would you believe IT\'S A TIE!!\n");

System.out.println("time of race: "+rtime+" simulated seconds\n");

}

public static void print(int t,int h)

{int i;

if(h==t)

{for(i=0;i<h;i++)

System.out.print(" ");

System.out.println("OUCH!!!");

}

else if(h<t)

{for(i=0;i<h;i++)

System.out.print(" ");

System.out.print("H");

for(i=0;i<(t-h);i++)

System.out.print(" ");

System.out.print("T");

}

else

{for(i=0;i<t;i++)

System.out.print(" ");

System.out.print("T");

for(i=0;i<(h-t);i++)

System.out.print(" ");

System.out.print("H");

}

System.out.println();

}

public static int movehare(int r )

{int num;

num=(int)(Math.random()*10);

if(num<2)

r-=2;

else if(num<5)

r++;

else if(num<6)

r-=12;

else if(num<8)

r+=9;

if(r< 1 )

r=1;

return r;

}

public static int movetort(int t)

{int num;

num=(int)(Math.random()*10);

if(num<5)

t+=3;

else if(num<7)

t-= 6;

else

t++;

if(t<1)

t=1;

return t;

}

}

Q4 a:

import java.util.*;

public class TicTacToe

{

// Do we need static class variables?

// what should our instance variables be?

private String[][] board;

static String X = "X";

static String O = "O";

/**

* Constructor for objects of class TicTacToe

*/

public TicTacToe()

{

// initialize instance variables

board = new String[3][3];

}

/**

* Print out the tictactoe board

*/

public void printBoard()

{

System.out.println();

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

for (int j = 0; j < board[i].length; j++) {

if (board[i][j] == null) {

System.out.print("_");

} else {

System.out.print(board[i][j]);

}

if (j < 2) {

System.out.print("|");

} else {

System.out.println();

}

}

}

System.out.println();

}

/* Check if player wins. Check right after X makes a play

*

*/

public Boolean checkWinner(String play) {

int playInRow = 0;

int playD1 = 0;

int playD2 = 0;

int[] playInColumn = new int[board[0].length]; // assumes square board

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

playInRow = 0;

for (int j = 0; j < board[i].length; j++) {

if (null == board[i][j]) {

continue;

}

if (board[i][j].equals(play)) {

playInRow++;

playInColumn[j]++;

if (i == j) {

playD1++;

} else if (2 == i + j) {

playD2++;

}

}

}

if (playInRow == 3) {

return true;

}

}

if (3 == playD1 || 3 == playD2) {

return true;

}

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

if (playInColumn[i] == 3) {

return true;

}

}

return false;

}

/*

* makeMove gets a legal coordinate for the move that is not occupied

* and marks it with the play string

*/

public void makeMove(Scanner stdin, String play) {

int r;

int c;

Boolean goodInput = false;

while(!goodInput) {

r = -1;

c = -1;

System.out.println ("Enter coordinates to play your " + play);

if (stdin.hasNextInt()) { // must be integers

r = stdin.nextInt();

}

if (stdin.hasNextInt()) {

c = stdin.nextInt();

}

else {

stdin.nextLine(); // consume a line without an integer

System.out.println("Both inputs must be integers between 0 and 2.");

continue;

}

// must be in the right coordinate range

if ((r < 0) || (r > 2) || (c < 0) || (c > 2)) {

System.out.println("Both inputs must be integers between 0 and 2.");

continue;

}

// make sure the space is not occupied

else if (board[r][c] != null ){

System.out.println("That location is occupied");

continue;

}

else {

board[r][c] = play;

return;

}

}

return;

}

public static void main(String[] args) {

TicTacToe ttt = new TicTacToe(); // allocate a board

Scanner stdin = new Scanner(System.in); // read from standard in

int moves = 0;

System.out.println("Let's play TicTacToe -- X goes first");

ttt.printBoard();

while (moves < 9) {

ttt.makeMove(stdin, ttt.X);

moves++;

if (moves > 4) {

if (ttt.checkWinner(X)) {

System.out.println(X + " You Win!!!");

break;

}

}

ttt.printBoard();

ttt.makeMove(stdin, ttt.O);

moves++;

if (moves > 4) {

if (ttt.checkWinner(O)) {

System.out.println(O + " You Win!!!");

break;

}

}

ttt.printBoard();

}

}

}

Q5: Write a method that reverses the order of elements in an ArrayList<E> without creating a

new ArrayList. You may only use the methods remove, add, and size. (For this problem you

could use ArrayList<Integer> or ArrayList<String>). Write a driver class and demonstrate the

working of your method. (5 points)

Original

ArrayList E = new ArrayList();

E.add("1");

E.add("2");

E.add("3");

E.add("4");

E.add("5");

while ( E.listIterator().hasPrevious())

Log.d("reverse", "" + aList.listIterator().previous());

Rewrite

ArrayList E= new ArrayList();

E.add("1");

E.add("2");

E.add("3");

E.add("4");

E.add("5");

Collections.reverse(E);

System.out.println("After Reverse Order, ArrayList Contains : " + E);

7. Write an inheritance hierarchy for classes Quadrilateral, Trapezoid, Parallelogram,

Rectangle and Square. Use Quadrilateral as the superclass of the hierarchy. You are being

provided with a Point class, use it to represent the points in each shape. For e.g. the private

instance variables of Quadrilateral should be the x-y coordinate pairs for the four endpoints of

the Quadrilateral. Write a program that instantiates objects of your classes and outputs each

object’s area (except Quadrilateral). (10 points)

The Quadrilateral class

import java.awt.*;

public abstract class Quadrilateral

{

public Point topleft = new Point(0,0);

public Point topright = new Point(0,0);

public Point bottomleft = new Point(0,0);

public Point bottomright = new Point(0,0);

public abstract int calculateArea();

}//end of class Quadrilateral

The Rectangle class

import java.awt.*;

public class MyRect extends Quadrilateral

{

public MyRect()

{

super();

}//end of constructor

public MyRect(int x, int y, int width, int height)

{

//super();

topleft = new Point(x,y);

topright = new Point(x+width,y);

bottomleft = new Point(x, y+height);

bottomright = new Point(x+width, y+height);

}//end of constructor

public int calculateArea()

{

/*

* The area of a Rectangle is calculated as follows:

* (length * breadth)

*/

int area = (bottomright.x - topleft.x) * (bottomright.y - topleft.y);

return area;

}//end of method calculateArea()

}//end of class MyRect

The Square class

public class ShapeGenerator

{

public static void main(String args[])

{

Quadrilateral shapes[] = {

new MyRect(0,0,10,20),

new Parallelogram(0,0,10,20),

new Square(0,0,10)

};

int area=0;

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

{

area = shapes[i].calculateArea();

System.out.println("Area of " + shapes[i].getClass() + " : " + area);

}//end of for loop

}//end of method main()

}//end of class ShapeGenerator