Temperature class and Tic Tac Toe

Assignment

1: Temperature

Complete the provided Temperature class. Add any attributes and helper methods as needed.You must complete the constructors and methods in the provided class (without changing anysignatures, return types, or modifiers).
In this problem you will need to be able to convert temperatures between Celsius, Fahrenheit andKelvin. A temperature object holds a single temperature and displays it in one of the three scales. Oncea scale has been set, it will display the temperature in that scale until changed. The default scaleis Celsius if not specified.

Examples:
Temperature t = new Temperature(10.1);
System.out.println(t.getScale()); // outputs the char ’C’
System.out.println(t); // outputs 10.1C
t.setScale(“F”);
System.out.println(t); // outputs 50.18F
System.out.println(t.getScale()); // outputs the char ’F’

Note: Repeatedly changing the scale should not “change” the value of the temperature. Forexample,
Temperature t = new Temperature(10.1);
System.out.println(t);
for(int i=0; i<10000; i+=1){
t.setScale(“F”);
t.setScale(“C”);
}
System.out.println(t);
Should print out identical strings.
Note: You should have no static attributes or methods in your class (unless they were supplied in
the starter code).
Note: Your code must use encapsulation. Your grade will be reduced by 5 marks if you do not use
encapsulation.

2: Extreme Temperatures

Complete the MaxTempclass. The class consists of a single constructor and a single getter method.
The constructor takes an array of Temperature objects as input.
The getter method either returns an array of doubles with exactly two doubles in it or returnsnull. If the object was created with one more moreTemperature objects in the constructor’sinput array then the output consists of the maximum temperature of all Temperature objectspassed to the constructor and a count of how many times that maximum was present in thearray passed to the constructor (in that order). If zero Temperature objects were passed tothe constructor (in the array) then the getter returns null.
Note: The max temperature returned must be displayed in the Kelvin scale.
Note: Different Temperature objects in the array passed to the constructor may have differenttemperature scales set for themselves.
Since the Temperature objects will store a floating point number for the temperature, you willuse the provided EPSILON constant in the MaxTempclass and consider two temperatures as equalif their absolute difference is smaller than EPSILON. Therefore, if Math.abs(temp1 – temp2) <ESILON then temp1 and temp2 are considered equal.
For example, if the array
new Temperature[]fnew Temperature(1001.12, “K”),
new Temperature(-200.0, “F”),
new Temperature(1001.11, “K”)g
is passed to the constructor, and EPSILON = 0.1, then the getMaxgetter will return [1001.12,2.0].
The return value should still display the maximum temperature (in K). In the example above,even though we consider 1001.11 and 1001.12 the “same”, 1001.12 is still the max to be returned.
Note: Your code must use encapsulation. Your grade will be reduced by 5 marks if you do not use
encapsulation.

3: Tic-Tac-Toe

Implement the game of Tic-Tac-Toe. Your game must consist of at least three (3) classes: Board,Player, and TicTacToeApp. You can add more classes if you wish.
The TicTacToeAppprogram will run the game, using a Board object and two Player objects.
The Player class will implement a player in the game. A player could be a human user (andso user input will be needed) or a computer.
The Board class will be the board in the game. It can either be a 3×3 grid or a 5×5 grid. Theconstructor of the class will create an appropriate grid.
User input for specifying which grid element in the board will be a comma separated list oftwo numbers, where the first number is row (starting at 0) and the second number is thecolumn (starting at 0). The amount of whitespace around the numbers (and comma) can bearbitrary.
A single command line argument (for the TicTacToeAppprogram) will specify if the gameis a 3×3 or 5×5 grid. Acceptable command line arguments will be “3”, “5”, “three” and”five”. For any other command line argument (or lack) your program will terminate with ausage message (of how to run the program properly).
The game board must be displayed before any player makes a move.
The game should be easy to play.
Note: Style for this problem includes class design. Encapsulation is required.
MaxTemp.java 

public class MaxTemp{

/** t1 and t2 are considered the same if Math.abs(t1-t2) < EPSILON */

public static final double EPSILON = 0.01;

/* add attributes as you need */

/* —————————————————-

* constructor

* —————————————————-

*/

publicMaxTemp(Temperature[] t){

// add your code here

}

/* —————————————————-

* getter

* —————————————————-

*/

public double[] getMax(){

// – returns null if empty array was passed to constructor

// – returns null if null was passed to constructor

// – otherwise, returns an array of length 2 [max, count]

//   where max is the maximum temperature (expressed in the Kelvin scale)

//   of all Temperature objects passed to the constructor, and count

//   is the number of times that temperature was present (in the input

//   array of the constructor)

return new double[]{0.1, 0.2, 0.3, 0.4};

}

/* OPTIONAL – use your main method to test your code */

public static void main(String[] args){

// testing code here is optional

}

} 

Temperature.java 

public class Temperature{

/** different scale names */

public static String[] scales = {“Celsius”, “Fahrenheit”, “Kelvin”};

/** Initializes a temperature object with given value in Celcius

*

*  If the initial temperature is less than -273.15 then the temperature

*  object will be initialized with -273.15C.

*

* @param temp is the initial temperature in Celsius.

*/

public Temperature(double temp){

}

/** Initializes a temperature object with given value using the specified scale

* <par>

* If the temperature is lower than absolute zero, then set the temperature to

* absolute zero (in whichever scale is specified).

* <par>

* Examples: new Temperature(12.3, “K”)

*           new Temperature(-90.2, “Celsius”)

*

* @param temp is the initial temperature

* @param scale is the scale of initial temperature and must either be

*        one of the Strings in the <code>scales</code> array, or

*        the first letter (capitalized) of one of those strings.

*/

public Temperature(double temp, String scale){

}

/** getter for the scale

*

* The output of this getter method must always be the first letter of one

* of the strings in the <code>scales</code> array, capitalized.

*

* @return the current scale of the object as a single char (the first letter,

*         capitalized of one of the strings from <code>scales</code>)

*/

public char getScale(){

return ‘X’;

}

/** getter for the temperature

*

* @return the temperature of the object using the current scale

*/

public double getTemp(){

return -Double.MAX_VALUE;

}

/** setter for scale

*

*

*

* @param scale is the new scale of the temperature and must either be

*        one of the Strings in the <code>scales</code> array, or

*        the first letter (capitalized) of one of those strings.

*/

public void setScale(String scale){

}

/** setter for temperature

*

* @param temp is the new temperature (in the objects current scale)

*/

public void setTemp(double temp){

}

/** setter for temperature

*

*

* @param temp is the new temperature

* @param scale is the scale of the new temperature. It must be

*        the first letter (capitalized) of one of the strings in

*        the<code>scales</code> array.

*/

public void setTemp(double temp, char scale){

}

/** setter for temperature

*

* @param temp is the new temperature

* @param scale is the scale of the new temperature. It must be one

*        of the strings in the <code>scales</code> array, or the first letter

*        (capitalized) of one of those strings.

*/

public void setTemp(double temp, String scale){

}

/* ————————————————- */

/* ————————————————- */

/* do not change anything below this                 */

/* ————————————————- */

/* ————————————————- */

/** String representation of a temperature object    */

@Override

public String toString(){

return “” + this.getTemp() + this.getScale();

}

} 

Solution 

Board.java

public class Board {

private static final char EMPTY_SYMBOL = ‘ ‘;

private static final char[] PLAYERS_SYMBOL = {‘X’, ‘O’};

private static final int INLINE = 3;

privateint size;

private char[][] board;

public Board(String s) {

switch (s) {

case “3”:

case “three”:

size = 3;

break;

case “5”:

case “five”:

size = 5;

break;

default:

throw new IllegalArgumentException();

}

board = new char[size][size];

for (int i = 0; i<size; i++) {

for (int j = 0; j<size; j++) {

board[i][j] = EMPTY_SYMBOL;

}

}

}

publicintgetSize() {

return size;

}

public void makeMove(int[] cell, int player) {

if ((cell[0] < 0) || (cell[1] < 0) || (cell[0] >= size) || (cell[1] >= size) || (board[cell[0]][cell[1]] != EMPTY_SYMBOL)) {

throw new IllegalArgumentException();

}

board[cell[0]][cell[1]] = PLAYERS_SYMBOL[player];

}

publicbooleanisEmpty(int i, int j) {

return (board[i][j] == EMPTY_SYMBOL);

}

publicbooleanisDraw() {

// Checking if there’s no empty cells

for (int i = 0; i<size; i++) {

for (int j = 0; j<size; j++) {

if (isEmpty(i, j))

return false;

}

}

// For draw no one must win

return ((!wins(PLAYERS_SYMBOL[0]))&&(!wins(PLAYERS_SYMBOL[1])));

}

privateboolean wins(char symbol) {

// Checking horizontal lines

for (int r = 0; r< size; r++) {

for (int c = 0; c<= size-INLINE; c++) {

int j = 0;

for (; j<INLINE; j++) {

if (board

[r]

[c+j]

!= symbol)

break;

}

if (j == INLINE)

return true;

}

}

// Checking vertical lines

for (int c = 0; c< size; c++) {

for (int r = 0; r<= size-INLINE; r++) {

int j = 0;

for (; j<INLINE; j++) {

if (board

[r+j]

[c]

!= symbol)

break;

}

if (j == INLINE)

return true;

}

}

// Checking diagonals from top left to bottom right

for (int r = 0; r<= size-INLINE; r++) {

for (int c = 0; c<= size-INLINE; c++) {

int j = 0;

for (; j<INLINE; j++) {

if (board

[r+j]

[c+j]

!= symbol)

break;

}

if (j == INLINE)

return true;

}

}

// Chacking diagonals from bottom left to top right

for (int r = 0; r<= size-INLINE; r++) {

for (int c = INLINE-1; c< size; c++) {

int j = 0;

for (; j<INLINE; j++) {

if (board

[r+j]

[c-j] != symbol)

break;

}

if (j == INLINE)

return true;

}

}

// If no lines found, return false

return false;

}

publicint evaluate() {

if (wins(PLAYERS_SYMBOL[0]))

return 0;

if (wins(PLAYERS_SYMBOL[1]))

return 1;

if (isDraw())

return 2;

return 3;

}

@Override

public String toString() {

StringBufferbuf = new StringBuffer();

for (int i = 0; i<=size+1; i++) {

buf.append(‘_’);

}

buf.append(‘\n’);

for (int i = 0; i<size; i++) {

buf.append(“|”);

for (int j = 0; j<size; j++) {

buf.append(board[i][j]);

}

buf.append(“|\n”);

}

for (int i = 0; i<=size+1; i++) {

buf.append(‘-‘);

}

buf.append(‘\n’);

returnbuf.toString();

}

} 

MaxTemp.java 

public class MaxTemp {

/** t1 and t2 are considered the same if Math.abs(t1-t2) < EPSILON */

public static final double EPSILON = 0.01;

private double max;

private double number;

/* add attributes as you need */

/*

* —————————————————- constructor

* —————————————————-

*/

publicMaxTemp(Temperature[] t) {

if (t.length == 0) {

max = -1;

number = -1;

}

else {

max = -1;

number = 0;

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

t[i].setScale(“K”);

}

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

if (t[i].getTemp() > max) {

max = t[i].getTemp();

}

}

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

if (max – t[i].getTemp() < EPSILON) {

number += 1;

}

}

}

}

/*

* —————————————————- getter

* —————————————————-

*/

public double[] getMax() {

// – returns null if empty array was passed to constructor

// – returns null if null was passed to constructor

// – otherwise, returns an array of length 2 [max, count]

// where max is the maximum temperature (expressed in the Kelvin scale)

// of all Temperature objects passed to the constructor, and count

// is the number of times that temperature was present (in the input

// array of the constructor)

if (number == -1) {

return null;

} else

return new double[] { max, number };

}

/* OPTIONAL – use your main method to test your code */

public static void main(String[] args) {

Temperature[] ts = new Temperature[] {

new Temperature(1001.12,”K”),

new Temperature(-200.0, “F”),

new Temperature(1001.11, “K”)

};

Temperature[] ts2 = new Temperature[] {};

MaxTempmt = new MaxTemp(ts);

double[] result = mt.getMax();

System.out.println(“Max Temp – ” + result[0]);

System.out.println(“Max Numb – ” + result[1]);

MaxTemp mt2 = new MaxTemp(ts2);

double[] result2 = mt2.getMax();

System.out.println(“Result – ” + result2);

}

} 

Player.java 

importjava.util.NoSuchElementException;

importjava.util.Random;

importjava.util.Scanner;

public class Player {

public static final int HUMAN_PLAYER = 0;

public static final int COMP_PLAYER = 1;

privateint controls;

private Scanner humanScanner;

private Board board;

public Player(int controls, Board board) {

this.controls = controls;

if (controls == HUMAN_PLAYER) {

humanScanner = new Scanner(System.in);

this.board = null;

}

else {

this.board = board;

humanScanner = null;

}

}

publicint[] makeMove() {

if (controls == HUMAN_PLAYER) {

int[] result = new int[2];

System.out.println(“Please enter number of row and column you want to choose in format: R C”);

String line = humanScanner.nextLine();

Scanner lineScan = new Scanner(line);

try {

result[0] = lineScan.nextInt();

result[1] = lineScan.nextInt();

}

catch (NoSuchElementExceptionnse) {

lineScan.close();

throw new IllegalArgumentException();

}

lineScan.close();

return result;

}

else {

System.out.println(“Computer moves”);

while (true) {

Random r = new Random();

int size = board.getSize();

int[] cell = new int[]{r.nextInt(size), r.nextInt(size)};

if (board.isEmpty(cell[0], cell[1])) {

return cell;

}

}

}

}

} 

Temperature.java

 /**

* A Temperature object represents temperature (with a value and scale)

*

* COMP 1006/1406 Fall 2017 Assignment 2

*/

// import java.util.System;

public class Temperature {

/** different scale names */

private double[] temps = new double[3];

privateintscl;

/**

* Initializes a temperature object with given value in Celcius

*

* If the initial temperature is less than -273.15 then the temperature

* object will be initialized with -273.15C.

*

* @param temp

*            is the initial temperature in Celsius.

*/

public Temperature(double temp) {

doublef_temp = temp * 9 / 5 + 32;

doublek_temp = temp + 273.15;

temps[0] = temp;

temps[1] = f_temp;

temps[2] = k_temp;

scl = 0;

}

/**

* Initializes a temperature object with given value using the specified

* scale <par> If the temperature is lower than absolute zero, then set the

* temperature to absolute zero (in whichever scale is specified). <par>

* Examples: new Temperature(12.3, “K”) new Temperature(-90.2, “Celsius”)

*

* @param temp

*            is the initial temperature

* @param scale

*            is the scale of initial temperature and must either be one of

*            the Strings in the <code>scales</code> array, or the first

*            letter (capitalized) of one of those strings.

*/

public Temperature(double temp, String scale) {

if (scale.equals(“Celsius”) || scale.equals(“C”)) {

doublef_temp = temp * 9 / 5 + 32;

doublek_temp = temp + 273.15;

temps[0] = temp;

temps[1] = f_temp;

temps[2] = k_temp;

scl = 0;

}

else if (scale.equals(“Fahrenheit”) || scale.equals(“F”)) {

doublec_temp = (temp – 32) * 5 / 9;

doublek_temp = c_temp + 273.15;

temps[0] = c_temp;

temps[1] = temp;

temps[2] = k_temp;

scl = 1;

} else {

doublec_temp = temp – 273.15;

doublef_temp = c_temp * 9 / 5 + 32;

temps[0] = c_temp;

temps[1] = f_temp;

temps[2] = temp;

scl = 2;

}

}

/**

* getter for the scale

*

* The output of this getter method must always be the first letter of one

* of the strings in the <code>scales</code> array, capitalized.

*

* @return the current scale of the object as a single char (the first

*         letter, capitalized of one of the strings from

*         <code>scales</code>)

*/

public char getScale() {

if (scl == 0)

return ‘C’;

else if (scl == 1)

return ‘F’;

else if (scl == 2)

return ‘K’;

else

return ‘X’;

}

/**

* getter for the temperature

*

* @return the temperature of the object using the current scale

*/

public double getTemp() {

return temps[scl];

}

/**

* setter for scale

*

*

*

* @param scale

*            is the new scale of the temperature and must either be one of

*            the Strings in the <code>scales</code> array, or the first

*            letter (capitalized) of one of those strings.

*/

public void setScale(String scale) {

if (scale.equals(“Celsius”) || scale.equals(“C”))

scl = 0;

else if (scale.equals(“Fahrenheit”) || scale.equals(“F”))

scl = 1;

else

scl = 2;

}

/**

* setter for temperature

*

* @param temp

*            is the new temperature (in the objects current scale)

*/

public void setTemp(double temp) {

doublef_temp = temp * 9 / 5 + 32;

doublek_temp = temp + 273.15;

temps[0] = temp;

temps[1] = f_temp;

temps[2] = k_temp;

scl = 0;

}

/**

* setter for temperature

*

*

* @param temp

*            is the new temperature

* @param scale

*            is the scale of the new temperature. It must be the first

*            letter (capitalized) of one of the strings in the

*            <code>scales</code> array.

*/

public void setTemp(double temp, char scale) {

if (scale == ‘C’)

setTemp(temp);

else if (scale == ‘F’) {

doublec_temp = (temp – 32) * 5 / 9;

doublek_temp = c_temp + 273.15;

temps[0] = c_temp;

temps[1] = temp;

temps[2] = k_temp;

scl = 1;

} else {

doublec_temp = temp – 273.15;

doublef_temp = c_temp * 9 / 5 + 32;

temps[0] = c_temp;

temps[1] = f_temp;

temps[2] = temp;

scl = 2;

}

}

/**

* setter for temperature

*

* @param temp

*            is the new temperature

* @param scale

*            is the scale of the new temperature. It must be one of the

*            strings in the <code>scales</code> array, or the first letter

*            (capitalized) of one of those strings.

*/

public void setTemp(double temp, String scale) {

if (scale.equals(“Celsius”))

setTemp(temp);

else if (scale.equals(“Fahrenheit”)) {

doublec_temp = (temp – 32) * 5 / 9;

doublek_temp = c_temp + 273.15;

temps[0] = c_temp;

temps[1] = temp;

temps[2] = k_temp;

scl = 1;

} else {

doublec_temp = temp – 273.15;

doublef_temp = c_temp * 9 / 5 + 32;

temps[0] = c_temp;

temps[1] = f_temp;

temps[2] = temp;

scl = 2;

}

}

/* ————————————————- */

/* ————————————————- */

/* do not change anything below this */

/* ————————————————- */

/* ————————————————- */

/** String representation of a temperature object */

@Override

public String toString() {

return “” + this.getTemp() + this.getScale();

}

public static void main(String[] args) {

Temperature t = new Temperature(10.1);

System.out.println(t.getScale()); // outputs the char ’C’

System.out.println(t); // outputs 10.1C

t.setScale(“F”);

System.out.println(t); // outputs 50.18F

System.out.println(t.getScale()); // outputs the char ’F’

}

} 

TicTacToeApp.java

public class TicTacToeApp {

private Board board;

private Player p1;

private Player p2;

publicTicTacToeApp(Board board, Player p1, Player p2) {

this.board = board;

this.p1 = p1;

this.p2 = p2;

}

public void run() {

int i = 0;

booleanisFinished = false;

while(!isFinished) {

System.out.println(board);

int[] cell = null;

while (true) {

try {

if (i % 2 == 0) {

System.out.println(“Player 1 making a move…”);

cell = p1.makeMove();

}

else {

System.out.println(“Player 2 making a move…”);

cell = p2.makeMove();

}

board.makeMove(cell, i % 2);

break;

}

catch(IllegalArgumentExceptioniae) {

System.out.println(“Illegal Move”);

}

}

intev = board.evaluate();

switch(ev) {

case 0:

System.out.println(“Player 1 wins”);

isFinished = true;

break;

case 1:

System.out.println(“Player 2 wins”);

isFinished = true;

break;

case 2:

System.out.println(“Draw”);

isFinished = true;

break;

}

i++;

}

System.out.println(board);

}

public static void main(String[] args) {

if (args.length != 1) {

System.out.println(“Illegal command line arguments”);

return;

}

try {

Board b = new Board(args[0]);

TicTacToeAppttt = new TicTacToeApp(b, new Player(Player.HUMAN_PLAYER, b), new Player(Player.COMP_PLAYER, b));

ttt.run();

}

catch (IllegalArgumentException e) {

System.out.println(“Illegal command line arguments”);

return;

}

}

}