This commit is contained in:
louiscklaw
2025-01-31 19:15:17 +08:00
parent 09adae8c8e
commit 6c60a73f30
1546 changed files with 286918 additions and 0 deletions

View File

@@ -0,0 +1,209 @@
/*Name:Kwok Ho Hin
StudenID: 180160427
Class: IT114105-1B
Description of purpose: 6x6 Reversi game in console mode. The letter 1 mean black, the letter 2 mean white and the letter 0 mean empty space.
*/
import java.util.Scanner;
public class Assignment {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int[][] reversi = new int[6][6];/*Reversi Array*/
boolean End = false; /*End is false*/
int inputX, inputY, countWhite = 0, countBlack = 0, player = 1, countPlay = 1;/*default player is 1, start the Countturn is 1, inputX and inputY for the Scanner can position*/
reversi[2][2] = 1;
reversi[3][3] = 1;
reversi[3][2] = 2;
reversi[2][3] = 2;
endGamebk:
do {
boolean inputEnd = false; /*reset inputEnd is false, player need input the values*/
System.out.println(" 0 1 2 3 4 5\n -------------");
for (int count = 0; count < 6; count++) { /*print the gameboard*/
System.out.print(count + " | ");
for (int i = 0; i <= 5; i++) {
System.out.print(reversi[count][i] + " ");
}
System.out.print("\n");
}
if (countPlay % 2 == 0) {
player = 2;
} else {
player = 1;
} /*calculator the player odd number of turn is 1, even number of turn is 2*/
truebk:
for (int count = 0; count < 6; count++) {
for (int i = 0; i <= 5; i++) {
if (reversi[count][i] == 0 && checkMove(reversi, count, i, player, true)) {
break truebk; /*find have or have not empty can put, if find it break the loop*/
} else if (count == 5 && i == 5 && !checkMove(reversi, 5, 5, 2, true) && !checkMove(reversi, 5, 5, 1, true)) {
break endGamebk; /*not empty space put so finish the game*/
}
}
}
do {
System.out.print("Please enter the position of '" + player + "' :");
inputX = input.nextInt();
inputY = input.nextInt();
if (inputX > 5 || inputX < 0 || inputY > 5 || inputY < 0) {
/*Check input value*/
System.out.println("Error - input numbers should be 0 to 5!");
}else if(reversi[inputX][inputY]!=0){ /*check input position whether empty*/
System.out.println("Error - input cell is not empty");
} else if (checkMove(reversi, inputX, inputY, player, false)) {
reversi[inputX][inputY] = player;
int countInput = 0;
for (int i = 0; i < 6; i++) { /*Check can a input next turn*/
for (int count = 0; count < 6; count++) {
if ((countPlay + 1) % 2 == 0 && checkMove(reversi, i, count, 2, true) == false) {
countInput++;
} else if ((countPlay + 1) % 2 != 0 && checkMove(reversi, i, count, 1, true) == false) {
countInput++;
}
if (countInput > 35) { /*Check next turn player whether can put */
countPlay++; /*next turn*/
}
}
}
countPlay++; /*next turn*/
inputEnd = true; /*End of input*/
} else {
System.out.println("Error - invalid move");
}
} while (inputEnd == false);
} while (End == false);
for (int i = 0; i < 6; i++) {
/*Counter*/
for (int count = 0; count < 6; count++) {
if (reversi[i][count] == 1) {
countBlack++;
} else if (reversi[i][count] == 2) { /*cannot use 'else' because the reversi game not finish in use all table may include a letter'0'*/
countWhite++;
}
}
}
System.out.print("Game Finishes.\n\t'1' - " + countBlack + "\n\t'2' - " + countWhite);
if (countWhite < countBlack) {
System.out.print("\nBlack wins.");
} else {
System.out.print("\nWhite wins.");
}
}
/*Check the position and faceing up, if the inputtest is true that mean the method onlu check the position but not faceing up*/
public static boolean checkMove(int reversi[][], int inputX, int inputY, int player, boolean inputtest) {
boolean[] check = new boolean[8];
if (reversi[inputX][inputY] == 0) { /*only empty space can put*/
for (int i = 1; i <= inputX; i++) { /*checkTop*/
if (inputX - i < 0 || reversi[inputX - 1][inputY] == 0) { /*if arrary expection -> break*/
break;
} else if (reversi[inputX - 1][inputY] != player && reversi[inputX - i][inputY] == player && reversi[inputX - i][inputY] != 0) { /*on top of not a same and find do you have*/
check[0] = true;
if (inputtest == true) { /*Check test or not, if this for the test not need facing up */
break;
}
for (int count = 1; count <= i; count++) {
reversi[inputX - count][inputY] = player;
}
}
}
for (int i = 1; i <= 5 - inputX; i++) {/*checkdown*/
if (inputX + i > 5 || reversi[inputX + 1][inputY] == 0) {/*if arrary expection -> break*/
break;
} else if (reversi[inputX + 1][inputY] != player && reversi[inputX + i][inputY] == player && reversi[inputX + i][inputY] != 0) {
check[1] = true;
if (inputtest == true) { /*Check test or not, if this for the test not need facing up */
break;
}
for (int count = 1; count <= i; count++) {
reversi[inputX + count][inputY] = player;
}
}
}
for (int i = 1; i <= inputY; i++) {/*checkleft*/
if (inputY - i < 0 || reversi[inputX][inputY - 1] == 0) { /*if arrary expection -> break*/
break;
} else if (reversi[inputX][inputY - 1] != player && reversi[inputX][inputY - i] == player && reversi[inputX][inputY - i] != 0) {
check[2] = true;
if (inputtest == true) {/*Check test or not, if this for the test not need facing up */
break;
}
for (int count = 1; count <= i; count++) {
reversi[inputX][inputY - count] = player;
}
}
}
for (int i = 1; i <= 5 - inputY; i++) {/*checkRight*/
if (inputY + i > 5 || reversi[inputX][inputY + 1] == 0) { /*if arrary expection -> break*/
break;
} else if (reversi[inputX][inputY + 1] != player && reversi[inputX][inputY + i] == player && reversi[inputX][inputY + i] != 0) {
check[3] = true;
if (inputtest == true) { /*Check test or not, if this for the test not need facing up */
break;
}
for (int count = 1; count <= i; count++) {
reversi[inputX][inputY + count] = player;
}
}
}
for (int i = 1; i <= 5; i++) {/*checkRightTopL*/
if ((inputX - i < 0 || inputY + i > 5) || reversi[inputX - i][inputY + i] == 0) { /*if arrary expection -> break*/
break;
} else if (reversi[inputX - 1][inputY + 1] != player && reversi[inputX - i][inputY + i] == player && reversi[inputX - i][inputY + i] != 0) {
check[4] = true;
if (inputtest == true) { /*Check test or not, if this for the test not need facing up */
break;
}
for (int count = 1; count <= i; count++) {
reversi[inputX - count][inputY + count] = player;
}
}
}
for (int i = 1; i <= 5; i++) {/*RightDownL*/
if ((inputX + i > 5 || inputY + i > 5) || reversi[inputX + i][inputY + i] == 0) { /*if arrary expection -> break*/
break;
} else if (reversi[inputX + 1][inputY + 1] != player && reversi[inputX + i][inputY + i] == player && reversi[inputX + i][inputY + i] != 0) {
check[5] = true;
if (inputtest == true) { /*Check test or not, if this for the test not need facing up */
break;
}
for (int count = 1; count <= i; count++) {
reversi[inputX + count][inputY + count] = player;
}
}
}
for (int i = 1; i <= 5; i++) {/*checkLeftTopL*/
if ((inputX - i < 0 || inputY - i < 0) || reversi[inputX - i][inputY - i] == 0) { /*if arrary expection -> break*/
break;
} else if (reversi[inputX - 1][inputY - 1] != player && reversi[inputX - i][inputY - i] == player && reversi[inputX - i][inputY - i] != 0) {
check[6] = true;
if (inputtest == true) { /*Check test or not, if this for the test not need facing up */
break;
}
for (int count = 1; count <= i; count++) {
reversi[inputX - count][inputY - count] = player;
}
}
}
for (int i = 1; i <= 5; i++) {/*checkLeftDownL*/
if ((inputX + i > 5 || inputY - i < 0) || reversi[inputX + i][inputY - i] == 0) { /*if arrary expection -> break*/
break;
} else if (reversi[inputX + 1][inputY - 1] != player && reversi[inputX + i][inputY - i] == player && reversi[inputX + i][inputY - i] != 0) {
check[7] = true;
if (inputtest == true) { /*Check test or not, if this for the test not need facing up */
break;
}
for (int count = 1; count <= i; count++) {
reversi[inputX + count][inputY - count] = player; /*if */
}
}
}
}
return check[0] || check[1] || check[2] || check[3] || check[4] || check[5] || check[6] || check[7];
}
}

View File

@@ -0,0 +1,62 @@
# ITP3914-Assignment 19-20 (Reversi Game)
- [x] Pass All test cases and hidden test cases
Sample Result:
```
0 : 1 1 1 1 1 1
1 : 2 2 2 2 1 1
2 : 2 2 1 1 1 1
3 : 2 2 2 2 2 2
4 : 2 2 2 2 2 2
5 : 2 2 2 2 2 2
0 1 2 3 4 5
Game Finishes.
'1' - 12
'2' - 24
White wins.
```
Sample input:
```
-1 5
3 6
2 2
0 0
2 1
3 1
2 1
1 3
2 4
1 4
4 2
3 4
4 3
2 0
3 0
5 2
5 3
5 1
5 0
4 0
0 3
4 4
4 1
0 2
3 5
0 4
1 2
5 4
4 5
1 1
0 1
0 0
1 5
2 5
1 0
0 5
5 5
```

View File

@@ -0,0 +1,104 @@
import java.util.Scanner;
public class BingoGameBoard {
private Scanner input;
private List playerList;
private List records;
public BingoGameBoard(){
input = new Scanner(System.in);
playerList = new List();
records = new List();
}
public void regPlayer(Player player){
playerList.append(player);
player.setBingoGameCard(BingoGameCard.generateGameCard(playerList.getSize()));
}
public void printGameBoard(){
for(int i = 0; i < playerList.getSize(); i++){
Player player = (Player) playerList.getItemAt(i);
System.out.printf("Player%s's Card:\n", player.getName());
player.getBingoGameCard().print();
}
System.out.println();
}
public boolean hasWin(){
for(int i = 0; i < playerList.getSize(); i++){
Player player = (Player) playerList.getItemAt(i);
if(player.getBingoGameCard().isBingo())
return true;
}
return false;
}
public int getUserInput(){
int num = -1;
do{
try{
System.out.print("Game Host call (0 to exit): ");
num = Integer.parseInt(this.input.nextLine());
if(num < 0 || num > 25)
throw new NumberFormatException();
if(duplicateHistory(num))
throw new NumberRepeatException(num);
}catch(NumberFormatException e){
System.out.println("The number must be between 1 to 25, please call again!");
}catch(NumberRepeatException e){
System.out.println(e.getMessage());
num = -1;
}
}while(!(num < 26 && num > -1));
return num;
}
public boolean duplicateHistory(int num){
for(int i = 0; i < records.getSize(); i++){
if((int)records.getItemAt(i) == num)
return true;
}
return false;
}
public void place(int number){
for(int i = 0; i < playerList.getSize(); i++){
Player player = (Player) playerList.getItemAt(i);
player.getBingoGameCard().replace(number);
}
}
public void start(){
while(!hasWin()){
printGameBoard();
int num = getUserInput();
if(num == 0)
System.exit(1);
place(num);
records.append(num);
}
printGameBoard();
printBingoList();
}
private void printBingoList(){
for(int i = 0; i < playerList.getSize(); i++){
Player player = (Player) playerList.getItemAt(i);
if(player.getBingoGameCard().isBingo())
System.out.printf("Player%s Bingo!\n", player.getName());
}
}
}
class NumberRepeatException extends Exception{
NumberRepeatException(int num){
super("The number " + num +" is repeated, please call again!");
}
}

View File

@@ -0,0 +1,110 @@
public class BingoGameCard {
int[][] card;
private final static int[][][] CARD = {
{
{24,2,8,1,25},
{12,16,7,17,15},
{5,6,20,19,13},
{14,23,22,4,3},
{10,18,11,21,9}
},
{
{24,21,17,15,6},
{10,3,8,18,20},
{14,7,16,12,5},
{25,23,13,19,11},
{22,4,9,1,2}
}
};
public BingoGameCard(int[][] card){
this.card = card;
}
public void print(){
for(int i = 0; i < card.length; i++){
for(int j = 0; j < card[i].length; j++){
if(card[i][j] == -1)
System.out.print(" XX ");
else
System.out.printf(" %2d ", card[i][j]);
}
System.out.println();
}
}
public static BingoGameCard generateGameCard(int index){
if(index % 2 == 0)
return new BingoGameCard(CARD[1]);
return new BingoGameCard(CARD[0]);
}
public boolean isBingo(){
for(int i = 0; i < card.length; i++){
int count = 0;
for( int j = 0; j < card[i].length; j++){
if(j>0 && count == 0)
break;
if(card[i][j] == -1)
count++;
}
if(count == card[i].length)
return true;
}
for(int i = 0; i < card[0].length; i++){
int count = 0;
for(int j = 0; j < card.length; j++){
if(j>0 && count == 0)
break;
if(card[j][i] == -1)
count++;
}
if(count == card.length)
return true;
}
int count = 0;
for(int i = 0; i < card.length; i++){
if(i>0 && count == 0)
break;
if(card[i][card[i].length-i-1] == -1)
count++;
}
if (count == card.length)
return true;
count = 0;
for(int i = 0; i < card.length; i++){
if(i>0 && count == 0)
break;
if(card[i][i] == -1)
count++;
}
if(count == card.length)
return true;
return false;
}
public void replace(int number){
for(int i = 0; i < card.length; i++){
for(int j = 0; j < card[i].length; j++){
if(card[i][j] == number){
card[i][j] = -1;
break;
}
}
}
}
}

View File

@@ -0,0 +1,42 @@
public class List {
private Node head;
private Node tail;
private int size;
public List(){
head = tail = null;
size = 0;
}
public boolean isEmply(){
return head == null;
}
public void append(Object data){
if(head == null){
head = tail = new Node(data);
size++;
return;
}
tail.next = new Node(data);
tail = tail.next;
size++;
}
public Object getItemAt(int index){
Node tmp = head;
int tmpIndex = 0;
while(tmpIndex < index){
tmp = tmp.next;
tmpIndex++;
}
return tmp.data;
}
public int getSize(){
return size;
}
}

View File

@@ -0,0 +1,8 @@
public class Main {
public static void main(String[] args) {
BingoGameBoard game = new BingoGameBoard();
game.regPlayer(new Player("1"));
game.regPlayer(new Player("2"));
game.start();
}
}

View File

@@ -0,0 +1,14 @@
public class Node {
public Object data;
public Node next;
public Node(Object data){
this.data = data;
next = null;
}
public Node(Object data, Node next){
this.data = data;
this.next = next;
}
}

View File

@@ -0,0 +1,21 @@
public class Player {
private BingoGameCard card;
private String name;
public Player(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setBingoGameCard(BingoGameCard card){
this.card = card;
}
public BingoGameCard getBingoGameCard(){
return card;
}
}

View File

@@ -0,0 +1,168 @@
## BINGO game
### Test case
```
28
-2
16
10
10
22
6
20
18
2
23
```
### Expected Output
```
Player1's Card:
24 2 8 1 25
12 16 7 17 15
5 6 20 19 13
14 23 22 4 3
10 18 11 21 9
Player2's Card:
24 21 17 15 6
10 3 8 18 20
14 7 16 12 5
25 23 13 19 11
22 4 9 1 2
Game Host call (0 to exit): 28
-2
16
10
10
22
6
20
18
2
23
The number must be between 1 to 25, please call again!
Game Host call (0 to exit): The number must be between 1 to 25, please call again!
Game Host call (0 to exit):
Player1's Card:
24 2 8 1 25
12 XX 7 17 15
5 6 20 19 13
14 23 22 4 3
10 18 11 21 9
Player2's Card:
24 21 17 15 6
10 3 8 18 20
14 7 XX 12 5
25 23 13 19 11
22 4 9 1 2
Game Host call (0 to exit):
Player1's Card:
24 2 8 1 25
12 XX 7 17 15
5 6 20 19 13
14 23 22 4 3
XX 18 11 21 9
Player2's Card:
24 21 17 15 6
XX 3 8 18 20
14 7 XX 12 5
25 23 13 19 11
22 4 9 1 2
Game Host call (0 to exit): The number 10 is repeated, please call again!
Game Host call (0 to exit):
Player1's Card:
24 2 8 1 25
12 XX 7 17 15
5 6 20 19 13
14 23 XX 4 3
XX 18 11 21 9
Player2's Card:
24 21 17 15 6
XX 3 8 18 20
14 7 XX 12 5
25 23 13 19 11
XX 4 9 1 2
Game Host call (0 to exit):
Player1's Card:
24 2 8 1 25
12 XX 7 17 15
5 XX 20 19 13
14 23 XX 4 3
XX 18 11 21 9
Player2's Card:
24 21 17 15 XX
XX 3 8 18 20
14 7 XX 12 5
25 23 13 19 11
XX 4 9 1 2
Game Host call (0 to exit):
Player1's Card:
24 2 8 1 25
12 XX 7 17 15
5 XX XX 19 13
14 23 XX 4 3
XX 18 11 21 9
Player2's Card:
24 21 17 15 XX
XX 3 8 18 XX
14 7 XX 12 5
25 23 13 19 11
XX 4 9 1 2
Game Host call (0 to exit):
Player1's Card:
24 2 8 1 25
12 XX 7 17 15
5 XX XX 19 13
14 23 XX 4 3
XX XX 11 21 9
Player2's Card:
24 21 17 15 XX
XX 3 8 XX XX
14 7 XX 12 5
25 23 13 19 11
XX 4 9 1 2
Game Host call (0 to exit):
Player1's Card:
24 XX 8 1 25
12 XX 7 17 15
5 XX XX 19 13
14 23 XX 4 3
XX XX 11 21 9
Player2's Card:
24 21 17 15 XX
XX 3 8 XX XX
25 23 13 19 11
XX 4 9 1 XX
Game Host call (0 to exit):
Player1's Card:
24 XX 8 1 25
12 XX 7 17 15
5 XX XX 19 13
14 XX XX 4 3
XX XX 11 21 9
Player2's Card:
24 21 17 15 XX
XX 3 8 XX XX
14 7 XX 12 5
25 XX 13 19 11
XX 4 9 1 XX
Player1 Bingo!
Player2 Bingo!
```

View File

@@ -0,0 +1,206 @@
import java.util.Scanner;
public class Battleships {
public final static int DEFAULT_GAME_BOARD_SIZE = 10;
public final static int DEFAULT_GAME_NUM_GROUP_SHIP = 3;
private int[][] board;
private Scanner input;
private int launched = 1, hit = 0;
// -1 missing
// 0 null
// 1 hit
// 2 ship
public Battleships() {
board = new int[DEFAULT_GAME_BOARD_SIZE][DEFAULT_GAME_BOARD_SIZE];
setShips();
}
public Battleships(int size) {
board = new int[size][size];
setShips();
}
public Battleships(int size, Ship[] ships) {
board = new int[size][size];
setShips(ships);
}
public void setScanner(Scanner scanner) {
this.input = scanner;
}
public void start() {
System.out.println("---- Battleship Game----");
showBoard(false);
while (!isWin()) {
System.out.print("Set your missile [XY] (x to exit) :");
char[] misile = input.nextLine().toCharArray();
if (misile.length == 1) {
if (misile[0] == 'c')
showBoard(true);
else if (misile[0] == 'x') {
System.out.println("Bye!");
System.exit(1);
} else
System.out.println("Mismatch!!");
} else if (misile.length == 2) {
int x = Integer.parseInt(String.valueOf(misile[0]));
int y = Integer.parseInt(String.valueOf(misile[1]));
put(x, y);
showBoard(false);
showStatus();
} else {
System.out.println("Mismatch!!");
}
}
System.out.println("You have hit all battleships!");
}
public void put(int x, int y) {
int val = board[x][y];
if (val == 0) {
System.out.println("Missed.");
board[x][y] = -1;
launched++;
} else if (val == 2) {
System.out.println("It's a hit!!");
board[x][y] = 1;
hit++;
launched++;
} else {
System.out.println("You have already fired this area.");
}
}
public void setShips(Ship[] ships) {
for (Ship ship : ships) {
this.board[ship.x][ship.y] = 2;
}
}
public void setShips() {
setShips(createShip(this.board));
}
public static Ship[] createShip(int[][] boards) {
return createShip(boards, DEFAULT_GAME_NUM_GROUP_SHIP, DEFAULT_GAME_NUM_GROUP_SHIP);
}
public static Ship[] createShip(int[][] board, int numOfGroupShip, int numOfShip) {
Ship[] ships = new Ship[numOfGroupShip * numOfShip];
for (int i = 0; i < numOfGroupShip * numOfShip; i += 3) {
int count = 0;
while (count++ < numOfShip) {
int cX;
int cY;
boolean isHorizontally = (Math.random() > 0.5);
do {
cX = (int) Math.ceil(Math.random() * (board.length - 1 - 2));
cY = (int) Math.ceil(Math.random() * (board[0].length - 1 - 2));
ships[i] = new Ship(cX, cY);
} while ((!isHorizontally && board[cX][cY] == 2 || board[cX + 1][cY] == 2 || board[cX + 2][cY] == 2)
|| (isHorizontally && board[cX][cY] == 2 || board[cX][cY + 1] == 2 || board[cX][cY + 2] == 2));
for (int j = 0; j < numOfShip; j++) {
if (!isHorizontally)
ships[i + j] = new Ship(cX + j, cY);
else
ships[i + j] = new Ship(cX, cY + j);
}
}
}
return ships;
}
public void showStatus() {
System.out.printf("Launched:%d, Hit: %d\n", launched, hit);
}
public boolean isWin() {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
int val = board[i][j];
if (val == 2)
return false;
}
}
return true;
}
public void showBoard(boolean showHidden) {
System.out.println();
int size = Integer.toString(board.length - 1).length();
if (size < 2)
size++;
for (int i = 0; i < size + 1; i++)
System.out.print(" ");
System.out.print(" ");
for (int i = 0; i < board.length; i++)
System.out.printf(" %d", i);
System.out.println();
for (int i = 0; i < size + 1; i++)
System.out.print("-");
System.out.print("+-");
for (int i = 0; i < board.length; i++)
for (int j = 0; j < Integer.toString(i).length() + 1; j++)
System.out.print("-");
System.out.println();
for (int i = 0; i < board.length; i++) {
System.out.printf("%d", i);
for (int j = 0; j < size - Integer.toString(i).length() + 1; j++)
System.out.print(" ");
System.out.print("| ");
for (int j = 0; j < board[i].length; j++) {
int val = board[i][j];
if (val == 1)
System.out.print("#");
else if (val == -1)
System.out.print("O");
else if (showHidden && val == 2)
System.out.print("S");
else
System.out.print(".");
for (int k = 0; k < Integer.toString(j).length(); k++)
System.out.print(" ");
}
System.out.println();
}
}
}
class Ship {
public int x;
public int y;
public Ship(int x, int y) {
this.x = x;
this.y = y;
}
}

View File

@@ -0,0 +1,11 @@
import java.util.Scanner;
class Main{
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
Battleships game = new Battleships();
game.setScanner(scanner);
game.start();
}
}

View File

@@ -0,0 +1,153 @@
# ITP3914 Programming Assignment (PTE)
## Instructions
1. This assignment is an individual assignment and should be done by you only. Plagiarism will be treated seriously. Any submitted assignment is found that involved wholly or partly in plagiarism (no matter the assignments are from the original authors or from the plagiarists) will be scored Zero mark and the students involved will be received discipline penalty set by the institute accordingly.
2. Grading of your programs will be based on correctness, quality, style and efficiency.
3. You are required to hand in
- softcopy of the program source codes upload to Moodle. (named: BattleShip.java)
- test report (sample screen of your program) (named: TestReport.docx)
4. Late submission will NOT be accepted.
5. Each student may be arranged to conduct an interview with your lecturer to explain some parts of your program code and answer some questions. Marks will be deducted if you cannot explain your code well.
## Assignment Specification
You are asked to write a Battleship game using Java.
### Setting up the game
1. When the program runs, there is a 10 x 10 battlefield created. Computer will set 3 battleship on the field randomly.
2. Each battleship's occupies consecutively 3 cells, and can be placed horizontally or vertically, the chance should be 50:50.
3. The following is an example of two battleships set horizontally while one set vertically.
4. The three battleships should not overlap.
```
0 1 2 3 4 5 6 7 8 9
--+--------------------
0 | . . . S S S . . . .
1 | . . . . . . . . . .
2 | . . . . . . . . . .
3 | . . . . . S . . . .
4 | . . . . . S . . . .
5 | . . . . . S . . . .
6 | . . . . . . . . . .
7 | . . . . . . . . . .
8 | S S S . . . . . . .
9 | . . . . . . . . . .
```
#### Game play
1. Show the greeting message and battlefield to player as below. Hide the battleship (of course!)
```
---- Battleship Game----
0 1 2 3 4 5 6 7 8 9
--+--------------------
0 | . . . . . . . . . .
1 | . . . . . . . . . .
2 | . . . . . . . . . .
3 | . . . . . . . . . .
4 | . . . . . . . . . .
5 | . . . . . . . . . .
6 | . . . . . . . . . .
7 | . . . . . . . . . .
8 | . . . . . . . . . .
9 | . . . . . . . . . .
```
2. Prompt player to input the place where to he/she wants to hit.
3. The player will enter two characters range from 0-9, where the first character is the nth column, and the second character is the mth row. E.g. [45] means the player wants to hit column 4, row 5 of the battlefield.
```
Set your missile [XY] (x to exit) :45
Missed.
Launched:1, Hit: 0
```
4. If player hit the battleship, the cell will shows [#].
5. If player missed the battleship, the cell will shows [o].
```
Set your missile [XY] (x to exit) :45
Missed.
Launched:1, Hit: 0
0 1 2 3 4 5 6 7 8 9
--+--------------------
0 | . . . . . . . . . .
1 | . . . . . . . . . .
2 | . . . . . . . . . .
3 | . . . . . . . . . .
4 | . . . . . . . . . .
5 | . . . . o . . . . .
6 | . . . . . . . . . .
7 | . . . . . . . . . .
8 | . . . . . . . . . .
9 | . . . . . . . . . .
```
6. Cumulated and show the number of missile launched and the number of successful hit.
7. If the player chose a cell which have been hit before, show [You have already fired this area.] and do NOT cumulate the number of missile launched.
#### Extra feature
1. Add a cheating function: whenever the player enter "c", shows the battleships with mark "S".
```
Set your missile [XY] (x to exit) :c
0 1 2 3 4 5 6 7 8 9
--+--------------------
0 | . . . . . . . . . .
1 | . . . o . . . . . .
2 | . . o . . . . . o .
3 | . . . . . . . . . .
4 | . . . . . . . . . .
5 | . . . . o S S S . .
6 | . . S S S . . S S S
7 | . . . . . . o . . .
8 | . . . . o . . . . .
9 | . . . . . . . . . .
```
2. Whenever the player enter "x", end the game
```
0 1 2 3 4 5 6 7 8 9
--+--------------------
0 | . . . . . . . . . .
1 | . . . o . . . . . .
2 | . . o . . . . . o .
3 | . . . . . . . . . .
4 | . . . . . . . . . .
5 | . . . . o . . . . .
6 | . . . # . . . . . .
7 | . . . . . . o . . .
8 | . . . . o . . . . .
9 | . . . . . . . . . .
Set your missile [XY] (x to exit) :x
Bye!
```
3. When the player hit all battleships, show " You have hit all battleships!" and end the game.
```
Set your missile [XY] (x to exit) :96
It's a hit!!
Launched:19, Hit: 9
Set your missile [XY] (x to exit) :96
It's a hit!!
Launched:19, Hit: 9
0 1 2 3 4 5 6 7 8 9
--+--------------------
0 | . . . . . . . . . .
1 | . . . o . . . . . .
2 | . . o . . . . . o .
3 | . . . . . . . . . .
4 | . . . . . . . . . .
5 | . . . . o # # # o .
6 | . o # # # o o # # #
7 | . . . . . . o . . .
8 | . . . . o . . . . .
9 | . . . . . . . . . .
Launched:19, Hit: 9
You have hit all battleships!
```
## Remark
1. No data validation is needed, you may assume the user will always input correctly. The user will only input a two-character number such as [04] or [99], [c] (to cheat) or [x] (to terminate).
2. You should put all your program code in ONE single JAVA file named BattleShip.java.
3. Total number of code should be around 100-200 lines.
## Deliverables
1. Program source code - Battleship.java
2. Test report - at least two sample running output (in doc / docx / pdf / txt format)

View File

@@ -0,0 +1,36 @@
/*
Filename: Ex1.java
Programmer: <YOUR NAME>
Description: Determine the check digit of HKID numbers.
*/
import java.util.*;
public class Ex1 { // Validate HKID
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("? ");
String str = kb.next();
char[] letter;
int sum;
int code;
letter = str.toCharArray();
letter[0] = Character.toUpperCase(letter[0]);
sum = ((int) letter[0] - 64) * 8;
sum = sum + ((int) letter[1] - 48) * 7;
sum = sum + ((int) letter[2] - 48) * 6;
sum = sum + ((int) letter[3] - 48) * 5;
sum = sum + ((int) letter[4] - 48) * 4;
sum = sum + ((int) letter[5] - 48) * 3;
sum = sum + ((int) letter[6] - 48) * 2;
code = 11 - (sum % 11);
System.out.print("The HKID is: " + letter[0] + str.substring(1, 7));
if (code == 11) {
System.out.println("(0)");
} else if (code == 10) {
System.out.println("(A)");
} else {
System.out.println("(" + code + ")");
}
}
}

View File

@@ -0,0 +1,18 @@
import java.util.Scanner;
public class Ex2 {
public static void main(String[] args) {
// Create a Scanner object for console input
Scanner input = new Scanner(System.in);
// Declare variables
double tc, hdlc, tg;
System.out.print("Enter TC: ");
tc = input.nextDouble();
System.out.print("Enter HDLC: ");
hdlc = input.nextDouble();
System.out.print("Enter TG: ");
tg = input.nextDouble();
System.out.println("result = " + (tc - hdlc - (tg / 5)));
}
}

View File

@@ -0,0 +1,122 @@
# Lab 2 Programming Practices
## Topic 2.1-2.3: Variables, Data Types, Operators
### Exercise 1
(a) Type the Java program ValidateHKID below with proper format (using indentations and blank lines appropriately, merge or break lines in a meaningful way, etc.).
```java
import java.util.*;
public class Ex1{ //Validate HKID
public static void main(String[] args) {
Scanner kb=new Scanner(System.in);
System.out.print("? ");
String str=kb.next();
char[] letter;
int sum; int code;
letter = str.toCharArray();
letter[0] = Character.toUpperCase(letter[0]);
sum = (
(int)letter[0] -64 )
*8;
sum = sum + ( (int)letter[1] -48 )*7;
sum = sum + ( (int)letter[2] -48 )*6;
sum = sum + ( (int)letter[3] -48 )*5;
sum = sum + ( (int)letter[4] -48 )*4;
sum = sum + ( (int)letter[5] -48 )*3;
sum = sum + ( (int)letter[6] -48 )*2;
code = 11 - (sum % 11);
System.out.print("The HKID is: "
+ letter[0] +
str.substring(1,7));
if(code == 11) {System.out.println("(0)");} else if(code == 10) {
System.out.println("(A)");}
else { System.out.println("(" + code +
")"); }
}}
```
(b) Compile and execute the program. State the purpose of the program.
(c) At the top of your program, insert the following multi-comment to document who the writer of the program is. (Writing comments alongside program statements is called inline documentation.)
```
/*
Filename: Ex1.java
Programmer: <YOUR NAME>
Description: Determine the check digit of HKID numbers.
*/
```
```
c:\> java Ex1
? A123456
The HKID is: A123456(3)
```
### Exercise 2 Programming Exercise
Total Cholesterol (TC, 總膽固醇), HDL cholesterol (HDLC, 高密度膽固醇), and triglyceride (TG, 甘油三酯) levels are measured directly from a blood sample. LDL cholesterol (LDLC, 低密度膽固醇) is calculated by using the formula:
```math
LDLC = TC - HDLC - \frac{TG}{5}
```
Write a Java program that prompts user to input TC, HDLC, and TG as double values and then calculate and display the LDLC as shown below.
```
c:\> java Ex2
Enter TC : 234
Enter HDLC : 66
Enter TG : 104
LDLC = 147.2
```
Study the program below for how keyboard input can be performed.
```java
import java.util.Scanner;
public class Ex2 {
public static void main( String[] args ) {
// Create a Scanner object for console input
Scanner input = new Scanner(System.in);
// Declare variables
double n, j, result;
System.out.println( "This is a template program for console I/O." );
System.out.print( "Enter n: " );
n = input.nextDouble(); // input a double from keyboard
System.out.print( "Enter j: " );
j = input.nextDouble(); // input a double from keyboard
result = n + j;
System.out.println( "result = " + result );
}
}
```

View File

@@ -0,0 +1,15 @@
import java.util.Scanner;
public class Ex10 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double a, R, n;
System.out.print("Enter a: ");
a = input.nextDouble();
System.out.print("Enter R: ");
R = input.nextDouble();
System.out.print("Enter n: ");
n = input.nextDouble();
System.out.printf("S = %.1f\n", (a * (Math.pow(R, n)-1)/(R-1)));
}
}

View File

@@ -0,0 +1,13 @@
import java.util.Scanner;
public class Ex8 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int r, l;
System.out.print("Enter r: ");
r = input.nextInt();
System.out.print("Enter l: ");
l = input.nextInt();
System.out.printf("v = %.4f\n", (r*r) * Math.PI * l);
}
}

View File

@@ -0,0 +1,21 @@
import java.util.Scanner;
public class Ex9 {
final static int[] dollars = {10,5,2,1};
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int amount;
System.out.print("Input an amount: ");
amount = input.nextInt();
for (int dollar : dollars) {
System.out.printf("%d-dollar coin(s): ", dollar);
if(amount > dollar){
System.out.println(amount/dollar);
amount %= dollar;
}else{
System.out.println(0);
}
}
}
}

View File

@@ -0,0 +1,262 @@
# Lab 2 Variables and Arithmetic Operations
### Intended Learning Outcomes
Upon completion of this tutorial/lab, you should be able to:
- Define variables with meaningful names.
- Use arithmetic expressions and assignment statements to perform calculations.
- Identify and fix syntax errors in Java programs.
## Exercise 1
Identify whether the followings are valid or invalid identifiers.
| variable name | Valid | Invalid |
| ------------- | ----- | ------- |
| R2D2 | [x] | [] |
| Watchamacallit | [x] | [] |
| howAboutThis? | [] | [x] |
| Java | [x] | [] |
| GoodChoice | [x] | [] |
| 12345 | [] | [x] |
| 3CPO | [] | [x] |
| This is okay | [] | [x] |
| thisIsReallyokay | [x] | [] |
| aPPlet | [x] | [] |
| Bad-Choice | [] | [x] |
| A12345 | [x] | []|
## Exercise 2
Write down the output of the program fragments below.
```
double amount;
amount = 20;
System.out.println(amount 8);
# Output: 12.0
```
```
int n=9;
n+=1;
System.out.println(n);
System.out.println(n+1);
# Output:
10
11
```
```
int num=7;
num = 9%num;
System.out.println(num);
# Output: 2
```
```
int u, v;
u = 5;
v = u * u;
System.out.println(u*v);
# Output: 125
```
```
double x=8;
x += 5;
System.out.println(x + 3 * x);
# Output: 52
```
```
double p=5.1, q=2.3;
p += p;
System.out.println(p + q);
System.out.println(p q);
# output:
12.5
7.9
```
### Exercise 3
Identify the errors in the following Java program fragments.
(a)
```java
// Question
double a, b, c;
a = 2;
b = 3;
a + b = c;
System.out.println( 5((a + b) / (c + d);
```
```
// Answer
"a + b" = c;
```
* only a variable is allowed on the left hand side of an assignment statement
```
System.out.println( 5"*"((a + b) / (c + "d")"))";
```
* \* is expected between 5(
* d was not declared
* two ) were missed
(b)
```java
// Question
double balance, deposit;
balance = 1,200.3;
deposit = $140;
System.out.println( balance + deposit );
```
```
// Answer
balance = 1","200.3;
```
* comma is not allowed
```
deposit = $140;
```
* $ is not allowed
(c)
```java
// Question
double 6n;
6n = 2 * 6n;
```
```
// Answer
double "6n";
```
* a variable name must start with a letter (not a digit)
## Exercise 4
Write down the output of the program fragments below.
```java
String var;
var = "Programming";
System.out.print( var );
var = "Networking";
System.out.println( var );
// Output:
ProgrammingNetworking
```
```java
System.out.println( "act" + "ion" );
// Output: action
```
```java
double var1 = 3;
System.out.println( var1 + 5 );
// Output: 8.0
```
```java
System.out.println("The price is " + 30 + " dollars and " + 60 + " cents." );
// Output:
The price is 30 dollars and 60 cents.
```
## Exercise 5
```java
public class StringConcatenate {
public static void main(String[] args) {
int number1 = 200;
int number2 = 8;
int number3 = 18;
System.out.println("Next year is " + number1 + number2);
System.out.println("My age is " + (number2 + number3));
}
}
// Output:
Next year is 2008
My age is 26
```
## Exercise 6
```java
public class IncrementDecrement {
public static void main( String[] args ) {
int a, x;
a = 10;
x = a++;
System.out.println( "a=" + a );
System.out.println( "x=" + x );
x = ++a;
System.out.println( "a=" + a );
System.out.println( "x=" + x );
}
}
// Output:
11
10
12
12
```
## Exercise 7
Can the following conversions involving casting be allowed? If so, find the converted result, that is, the value stored in variable $i$.
```java
char c = 'A';
int i = int (c);
// not allowed
```
```java
double d = 1000.74;
int i = (int) d;
// allowed, 1000
```
```java
boolean b = true;
int i = (int) b;
// not allowed
```
## Exercise 8
PROBLEM: Calculate the volume of a cylinder (with console I/O)
Write a Java program that computes the volume ($v$) of a cylinder. The program should use Scanner class to read the radius ($r$) and the length ($l$), and compute the volume ($v$) with the formula: $v = r^2\pi l$.
Test Case
| | Case 1 | Case 2 | Case 3 |
| - | - | - | - |
| $r$ | 4 | 6 | 8 |
| $l$ | 5 | 7 | 9 |
| $v=$ | 251/3274 | 791.6813 | 1809.5574 |
```
c:\> java Ex8
Enter r : 8
Enter l : 9
v = 1809.5574
```

View File

@@ -0,0 +1,13 @@
import java.util.Scanner;
public class Ex1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double r, l;
System.out.print("Enter radius: ");
r = input.nextDouble();
System.out.print("Enter length: ");
l = input.nextDouble();
System.out.printf("volume = %.2f\n", (r*r*Math.PI*l) );
}
}

View File

@@ -0,0 +1,16 @@
import java.util.Scanner;
public class Ex3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double a, b, c;
System.out.print("Please enter a: ");
a = input.nextDouble();
System.out.print("Please enter b: ");
b = input.nextDouble();
System.out.print("Please enter c: ");
c = input.nextDouble();
System.out.printf("x1 = %.2f, x2 = %.2f\n", ((-b+Math.sqrt(b*b - 4*a*c))/(2*a)), ((-b-Math.sqrt(b*b-4*a*c))/(2*a)));
}
}

View File

@@ -0,0 +1,33 @@
# Lab 4 Simple I/O
## Topic 2.1-2.3: Variables, Data Types, Operators
### Intended Learning Outcomes
Upon completion of this tutorial/lab, you should be able to:
- Use console screen to input/output data.
- Use dialog box and message box to input/output data.
#### Exercise 1 Programming Exercise
PROBLEM: Calculate the volume of a cylinder (with console I/O)
Write a Java program that computes the volume ($v$) of a cylinder. The program should use Scanner class to read the radius ($r$) and the length ($l$), and compute the volume ($v$) with the formula:$ v = r^2\pi l$.
#### Exercise 2 Programming Exercise
PROBLEM: Calculate the volume of a cylinder (with dialog and message boxes)
Rewrite the program in Exercise 1 using dialog and message boxes in the `JOptionPane` class as the input/output method.
#### Exercise 3 Programming Exercise
PROBLEM: Find the root(s) of a quadratic equation
Write a Java program to calculate the two roots of a quadratic equation (ax2 + bx + c = 0) by using the formulae:
```math
x1 = \frac{-b+\sqrt{b^2-4ac}}{2a}, x2=\frac{-b-\sqrt{b^2-4ac}}{2a}
```
You can use `Math.sqrt(x)` method to calcuate $\sqrt{x}$ For example, the statement
```java
System.out.println(Math.sqrt(10));
```
prints the square root of 10. You are free to use either console I/O or `JOptionPane` classes.

BIN
_resources/it114105/itp3914/Lab05/Ex6.png (Stored with Git LFS) Normal file

Binary file not shown.

View File

@@ -0,0 +1,26 @@
public class Ex8 {
public static void main(String[] args) {
int[][] mTable = new int[10][10];
for (int i = 0; i < mTable.length; i++) {
for (int j = 0; j < mTable[i].length; j++) {
mTable[i][j] = i*j;
}
}
System.out.print(" ");
for ( int i = 0; i < 10; i++ )
System.out.printf( "%3d", i );
System.out.println();
System.out.print(" +");
for(int i = 0; i < 10; i++)
System.out.print("---");
System.out.println();
for (int i = 0; i < mTable.length; i++) {
System.out.printf("%3d|", i);
for (int col : mTable[i])
System.out.printf("%3d", col);
System.out.println();
}
}
}

View File

@@ -0,0 +1,52 @@
import java.util.Scanner;
public class Ex9 {
public static void main(String[] args) {
double[] nums = new double[10];
Scanner input = new Scanner(System.in);
int i;
for(i = 0; i < nums.length; i++){
System.out.printf("Enter number %d: ", i+1);
double num = input.nextDouble();
if(num == -1){
break;
}
nums[i] = num;
}
double min = nums[0];
double max = nums[0];
for(int index = 1; index < i; index++){
if(nums[index] > max)
max = nums[index];
if(nums[index] < min)
min = nums[index];
}
System.out.println("Maximum = " + max);
System.out.println("Minimum = " + min);
// Non-array version (Quesiton is required Array)
// double max = -1, min = -1;
// for (int i = 0; i < 10; ) {
// System.out.printf("Enter number %d: ", ++i);
// double num = input.nextDouble();
// if(num == -1)
// break;
// if(max == -1 && min == -1)
// max = min = num;
// if(num > max)
// max = num;
// if (num < min)
// min = num;
// }
// System.out.println("Maximum = " + max);
// System.out.println("Minimum = " + min);
}
}

View File

@@ -0,0 +1,161 @@
# Lab 5 Array
## Topic 2.5 Arrays
### Intended Learning Outcomes:
Upon completion of this tutorial/lab, you should be able to:
- Determine the name, size, data type and initial values of an array for a defined problem.
- Declare one- and two-dimensional arrays.
- Use `.length` to get the size of an array.
## Exercise 1
What will be printed on the screen when the program fragment below is executed?
```java
int [] a = {1, 2, 3, 4, 5};
System.out.println( a[1] + a[4] );
```
```
# Output:
7
```
## Exercise 2
Identify whether the array declarations below are valid.
| Code | valid | invalid |
| ---- | ----- | ------- |
| char [] charArray = new charArray[26]; | [] | [x] |
| char charArray[] = new charArray[26]; | [] | [x] |
| int [] words = new words[100]; | [] | [x] |
| int [100] words = new int []; | [] | [x] |
| char [] name = "Peter"; | [] | [x] |
| char [] name = {'P', 'e', 't', 'e', 'r'}; | [x] | [] |
| char [] name = {"P", "e", "t", "e", "r"}; | [] | [x] |
| double [] nums = [10.5, 25.1, 30.05]; | [] | [x] |
| double [] nums = {-3.5, 0, 3, 20.5}; | [x] | [] |
## Exercise 3
Write a program statement to declare an array named scores with initialize values: 5, 66, 2, 19, 6, 0.
```
double[] scores = {5, 66, 2, 19, 6, 0};
// or
int[] scores = {5, 66, 2, 19, 6, 0};
```
## Exercise 4
Identify whether the 2D array declarations below are valid.
| Code | valid | invalid |
| - | - | - |
| `int [3][4] matrix;` | [] | [x] |
| `double [3][4] matrix = new double[][];` | [] | [x] |
| `int [][] matrix = new int[3][4];` | [x] | [] |
| `int [][] matrix = new double[3][4];` | [] | [x] |
| `double [][] matrix = new double[][4];` | [] | [x] |
| `int [][] matrix = {(1, 2), (3, 4), (5, 6)};` | [] | [x] |
| i`nt [][] matrix = {1, 2}, {3, 4}, {5, 6};` | [] | [x] |
| `int [][] matrix = {{1, 2}, {3, 4}, {5, 6}};` | [x] | [] |
## Exercise 5
Given the 2D array declaration:
```java
int [][] m = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}};
```
What will be printed on the screen when the program fragments below are executed?
| Code | Output |
| ---- | ------ |
| System.out.print( m[0][0] ); | 1 |
| System.out.print( m[1][2] ); | 6 |
| System.out.print( m[3][1] ); | 11 |
| System.out.print( m[0][2] + m[3][1] ); | 14 |
| System.out.print( m.length ); | 4 |
| System.out.print( m[2].length ); | 3 |
| System.out.print( m[2][m[0][1]] ); | 9 |
| System.out.print( m[m[1].length][1]*2 ); | 22 |
## Exercise 6
Given the 2D array declaration:
```java
char [][] board = new char[10][10];
```
Complete the assignment statements below for storing THE and EGG into the 2D array so that it looks like:
![Image](./Ex6.png)
```java
board [a][b] = 'T';
board [c][d] = 'H';
board [e][f] = 'E';
board [g][h] = 'G';
board [i][j] = 'G';
```
a) 3
b) 2
c) 3
d) 3
e) 3
f) 4
g) 4
h) 4
i) 5
j) 4
## Exercise 7
Write a program to declare an array with the following settings:
- Array variable: `list`
- Data type: `int`
- Size: `10 elements`
- Values: `default to 0`
And then prints the data values stored in the array list by using following for loop.
```java
for ( int i=____; i < _____________; i++)
System.out.println( ______________ );
```
```java
// Answer
for (int i = 0; i < list.length; i ++>)
System.out.println( list[i] );
```
## Exercise 8
Generate a Multiplication Table:
Write a Java program to fill values to a two-dimensional array, mTable[10][10], for a multiplication table. Print the multiplication table as follows.
```
C:\> java Ex8
0 1 2 3 4 5 6 7 8 9
+------------------------------
0| 0 0 0 0 0 0 0 0 0 0
1| 0 1 2 3 4 5 6 7 8 9
2| 0 2 4 6 8 10 12 14 16 18
3| 0 3 6 9 12 15 18 21 24 27
4| 0 4 8 12 16 20 24 28 32 36
5| 0 5 10 15 20 25 30 35 40 45
6| 0 6 12 18 24 30 36 42 48 54
7| 0 7 14 21 28 35 42 49 56 63
8| 0 8 16 24 32 40 48 56 64 72
9| 0 9 18 27 36 45 54 63 72 81
```
## Exercise 9
Write a Java program to prompt a user to input some positive real numbers and store them in an array. The user can enter no more than 10 numbers. The program should stop prompting input when the user has entered the 10th number or input a negative value, e.g. -1. Then, the program starts to calculate the following statistics.
1. Maximum
2. Minimum
Test your program with the following five numbers, 1.23, 2.05, 4.0, 0.01, 0.12. Their maximum=4.0 and minimum=0.01.
```
C:\> java Ex9
Enter number 1 : 1.23
Enter number 2 : 2.05
Enter number 3 : 4.0
Enter number 4 : 0.01
Enter number 5 : 0.12
Enter number 6 : -1
Maximum = 4.0
Minimum = 0.01
```

View File

@@ -0,0 +1,30 @@
import java.util.Scanner;
public class Ex5 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a;
int x = 0;
System.out.print("a: ");
a = scan.nextInt();
switch (a) {
case 1:
x += 3;
break;
case 2:
x += 3;
break;
case 3:
x += 5;
break;
default:
x += 7;
break;
}
System.out.println("x = " + x);
}
}

View File

@@ -0,0 +1,13 @@
import java.util.Scanner;
public class Ex6 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Street number? ");
if(input.nextInt() % 2 == 0){
System.out.println("east-bound");
}else{
System.out.println("West-bound");
}
}
}

View File

@@ -0,0 +1,17 @@
import java.util.Scanner;
public class Ex7 {
final static int[] HOURLY_RATE = {15, 35, 50};
public static void main(String[] args) {
int type, hours;
Scanner input = new Scanner(System.in);
System.out.print("Vehicle Type [1=private, 2=bus, 3=truck]? ");
type = input.nextInt();
System.out.print("Number of hours? ");
hours = input.nextInt();
System.out.println("Parking fee = " + HOURLY_RATE[type-1]*hours);
}
}

View File

@@ -0,0 +1,20 @@
import java.util.Scanner;
public class Ex8 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Exam mark? ");
double mark = input.nextDouble();
char grade = 'A';
if (mark < 39)
grade = 'F';
else if(mark <= 49)
grade = 'D';
else if(mark <= 59)
grade = 'C';
else if (mark <= 69)
grade = 'B';
System.out.printf("Grade = %c\n", grade);
}
}

View File

@@ -0,0 +1,27 @@
import java.util.Scanner;
public class Ex9 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double a, b, c;
System.out.print("Enter a: ");
a = input.nextDouble();
System.out.print("Enter b: ");
b = input.nextDouble();
System.out.print("Enter c: ");
c = input.nextDouble();
if(a == 0)
System.out.println("This is not a quadratic equation.");
else{
double discriminan = b*b - 4*a*c;
if(discriminan > 0)
System.out.printf("2 roots, x1=%.1f, x2=%.1f\n", (-b+Math.sqrt(discriminan))/(2*a), (-b-Math.sqrt(discriminan))/(2*a));
else if (discriminan == 0)
System.out.printf("1 root, x=%.1f\n", (-b+Math.sqrt(discriminan))/(2*a));
else
System.out.println("No real solution");
}
}
}

View File

@@ -0,0 +1,131 @@
# Lab 6 Selection Structures
## Topic 3 Basic Program Structures
## Exercise 1
Assuming that the variable $x$ is storing $1$, determine the result of the boolean expressions below.
```
int x = 1;
```
| Boolean expressions | Result |
| ------------------- | ------ |
| (true) && (4 < 3) | false|
| !(x < 0) && (x < 0) | false |
| (x < 0) || (x > 0) | true |
| (x != 0) || (x == 0) | true |
| (x != 0) || (x == 0) | true |
| (x != 0) == !(x == 0) | true |
## Exercise 2
Assuming that $x$ and $y$ are `int` type, which of the followings are legal Java expressions?
| Expressions | legal | illegal |
| ----------- | ----- | ------- |
| x > y > 0 | [] | [x] |
| x = y || y | [] | [x] |
| x /= y | [x] | [x] |
| x or y | [] | [x] |
| x and y | [] | [x] |
| (x != 7) || (x = 7) | [] | [x] |
## Exercise 3
What will be the value of y after the program fragment below has been executed?
```
int x = 4;
int y = 4;
switch (x + 4) {
case 8: y=1;
default: y++;
}
# y is 2
```
## Exercise 4
Write a boolean expression that evaluates to true if the number x is in the range 21 to 30 inclusive, or x is negative.
```
(x >= 21 and x <= 30) || x < 0
```
## Exercise 5
Rewrite the `if-else` statements below to use the `switch` statement.
```java
import java.util.Scanner;
public class Ex5 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a;
int x = 0;
System.out.print("a: ");
a = scan.nextInt();
if (a == 1)
x += 3;
else if (a == 2)
x += 5;
else if (a == 3)
x += 7;
else
x += 10;
System.out.println("x = " + x);
}
}
```
## Exercise 6
In New York City (NYC), even numbered streets are east-bound, odd numbered streets are west-bound. Write a Java program to accept a street number from the user and print a message on screen to tell the user the direction.
A sample execution of the program is shown below. Those in __ are user inputs.
```
e:\> java Ex6
Street number? __213__
West-bound
```
## Exercise 7
Write a Java program to calculate the parking fee based on the vehicle type and the hours a vehicle spent in a car park. The parking fee is charged according to the table below.
| Vehicle Type | Hourly Rate ($ per hour) |
| - | - |
| Private Car | 15 |
| Bus | 35 |
| Truck | 50 |
Sample executions of the program are shown below. Those in __ are user inputs. All inputs (including the vehicle type) have the data type `int`.
```
e:\> java Ex7
Vehicle Type [1=private, 2=bus, 3=truck]? _1_
Number of hours? _3_
Parking fee = 45
```
```
e:\> java Ex7
Vehicle Type [1=private, 2=bus, 3=truck]? _2_
Number of hours? _2_
Parking fee = 70
```
## Exercise 8
Write a Java program to read an examination mark and determine the grade obtained according to the table below. Note that an examination mark may be a fractional number such as 62.5.
| Mark | 0-39 | 39.1-49 | 49.1-59 | 59.1-69 | otherwise |
| - | - | - | - | - | - |
| Grade | F | D | C | B | A |
Sample executions of the program are shown below. Those in __ are user inputs.
```
e:\> java Ex8
Exam mark? _72.5_
Grade = A
```
```
e:\> java Ex8
Exam mark? _43.5_
Grade = D
```

View File

@@ -0,0 +1,17 @@
import java.util.Scanner;
public class Ex10 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many values to enter? ");
int size = input.nextInt();
double sum = 0.0;
for(int i = 0; i < size; i++){
System.out.print("Value? ");
sum += input.nextDouble();
}
System.out.println("Average = " + sum/size);
}
}

View File

@@ -0,0 +1,19 @@
import java.util.Scanner;
public class Ex11 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double sum = 0;
int count = 0;
while(true){
System.out.print("Value? ");
double value = input.nextDouble();
if(value == 0)
break;
sum+=value;
count++;
}
System.out.println("Average = " + sum/count);
}
}

View File

@@ -0,0 +1,19 @@
import java.util.Scanner;
public class Ex12 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numOfOdd=0, numOfEven=0;
for (int i = 0; i < 5; i++) {
System.out.print("Value? ");
int value = input.nextInt();
if(value % 2 == 0)
numOfEven++;
else
numOfOdd++;
}
System.out.println("Number of odd values = " + numOfOdd);
System.out.println("Number of even values = " + numOfEven);
}
}

View File

@@ -0,0 +1,12 @@
public class Ex6a {
public static void main(String[] args) {
// (a)
int i = -9;
while( i <= -1){
System.out.println(i);
i+=3;
}
System.out.println("After loop, i=" + i);
}
}

View File

@@ -0,0 +1,13 @@
public class Ex6b {
public static void main(String[] args) {
// (b)
int i = 5;
System.out.println(i--);
while ( i >= 0){
System.out.println(i--);
}
System.out.println("After loop, i=" + i);
}
}

View File

@@ -0,0 +1,12 @@
import java.util.Scanner;
public class Ex7 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Number of stars? ");
int num = input.nextInt();
for(int i = 0; i < num; i++){
System.out.print("*");
}
}
}

View File

@@ -0,0 +1,14 @@
import java.util.Scanner;
public class Ex8 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("n? ");
int num = input.nextInt();
int result = 1;
for(int i=num; i > 0; i--)
result*=i;
System.out.printf("%d! = %d\n", num, result);
}
}

View File

@@ -0,0 +1,19 @@
import java.util.Scanner;
public class Ex9 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("n? ");
int num = input.nextInt();
int result = 1;
for(int i=num; i > 0; i--){
System.out.printf("%d ", i);
if(i != 1)
System.out.print("x ");
else
System.out.print("= ");
result*=i;
}
System.out.println(result);
}
}

View File

@@ -0,0 +1,249 @@
# Lab 7 Repetition Part 1
## Topic 3: Basic Program Structures
### Intended Learning Outcomes
Upon completion of this tutorial/lab, you should be able to:
- Use loops to perform searching on a text string.
- Use different types of loops to calculate sum of series.
## Exercise 1
Determine the output of the following Java programs.
(a)
```java
public static void main( String[] args ) {
double balance = 1000; // initialize to $1000
double interestRate = 0.1;
int years = 0; // number of years
do {
balance = ( 1 + interestRate ) * balance;
years += 1;
} while ( balance <= 1200 );
System.out.println( years );
}
// Output:
2
```
(b)
```java
public static void main( String[] args ) {
int j = 2;
String s = "";
while ( j <= 8 ) {
s += "*";
j += 2;
}
System.out.println( j + " " + s );
}
// Output:
10 ****
```
(c)
```java
public static void main( String[] args ) {
int i;
for ( i=-9; i<=-1; i+=3 )
System.out.print( i + " " );
}
// Output:
-9 -6 -3
```
## Exercise 2
Identify and correct the error(s) in the program fragment below.
(a)
```java
int c=0, product=1;
while (c <= 5) {
product *= c;
++c;
```
Logic error:
The variable product is always 0 after each loop, thus the loop is having no use.
Having a syntactically correct program doesn't mean that your program is producing the
correct result.
(b)
```java
int x=1, total;
While (x <= 10) {
total += x;
x++;
}
```
Syntax error: While should be while.
Better: Although Java initializes numerical variables to 0 automatically if an initial value is
not specified during variable declaration, it is better to write explicitly total=0 for better
program readability.
(c)
```java
For (int x=100, x >= 1, x++);
System.out.println(x);
```
Syntax error: for (int x=100; x >= 1; x++)
Logic error: x will always be greater than 1 and the loop will never terminate.
Having a syntactically correct program doesn&#39;t mean that your program is producing the
correct result.
## Exercise 3
What will be the value of variable $x$ after executing the following program fragment?
```java
int x=1, y=9;
for (int i=0; i<y; i+=3)
x++;
# x is 4
```
## Exercise 4
What will be printed by the program fragments below?
(a)
```java
int x=12;
do {
System.out.print(x + " ");
x--;
} while (x > 7);
// Output:
12 11 10 9 8
```
(b)
```java
for (int i=10; i<=25; i+=5)
System.out.print( (i/5) + " ")
// Output:
2 3 4 5
```
## Exercise 5
What will be printed by the program below?
```java
public class Question {
public static void main(String [] args) {
int y, x=1, total=0;
while (x <= 5) {
y = x * x;
System.out.println(y);
total += y;
x++;
}
System.out.println("Total is " + total);
}
}
// Output:
1
4
9
16
25
Total is 55
```
## Exercise 6
Rewrite the following programs with while loops.
(a)
```java
public static void main( String[] args ) {
int i;
for ( i=-9; i<=-1; i+=3 )
System.out.println( i );
System.out.println( "After loop, i=" + i );
}
```
(b)
```java
public static void main( String[] args ) {
int i = 5;
do {
System.out.println(i--);
} while ( i >= 0 );
System.out.println( "After loop, i=" + i ); }
```
## Exercise 7
Write a program to ask the user to input an int value. The program then prints the corresponding number of * on screen.
Shown below are two sample executions of the program. Those in underline are user inputs.
```
e:\> java Ex7
Number of stars? _5_
****
```
```
e:\> java Ex7
Number of stars? _9_
*********
```
## Exercise 8
Write a program to calculate n! where n is an integer value entered by the user.
NOTE: $n! = n (n-1) \times (n-2) \times (n-3) \times …\times 1$
For example, $5!=5\times 5\times 4\times 3\times 2\times 1$
Shown below are two sample executions of the program. Those in __ are user inputs.
```
e:\> java Ex8
n? _3_
3! = 6
```
```
e:\> java Ex8
n? _6_
6! = 720
```
## Exercise 9
Rewrite your program in Exercise 8 so that the output becomes:
```
e:\> java Ex9
n? _3_
3 x 2 x 1 = 6
```
```
e:\> java Ex9
n? _6_
6 x 5 x 4 x 3 x 2 x 1 = 720
```
## Exercise 10
Write a program to perform the followings:
- Ask the user the number of values to enter
- Read the values from the user
- Calculate and print the average of the values.
Shown below is a sample execution of the program. Those in __ are user inputs.
```
e:\> java Ex10
How many values to enter? _4_
Value? _10_
Value? _24_
Value? _20_
Value? _9_
Average = 15.75
```

View File

@@ -0,0 +1,24 @@
public class Ex5a {
public static void main(String [ ] args) {
int times = 0;
int count=1;
System.out.print(2); // 2 is the first prime number
int num=2;
while (count < 20) {
num++; // try next number
boolean isPrime=true;
for (int i=2; i<num; i++) {
if (num%i == 0) // divisible by i
isPrime = false; // not a prime
times++;
}
if (isPrime) {
count++; // one more prime is found
System.out.print(", " + num);
}
}
System.out.println("\nDone");
System.out.println("Total calculation = " + times);
}
}

View File

@@ -0,0 +1,26 @@
public class Ex5b {
public static void main(String [ ] args) {
int times = 0;
int count=1;
System.out.print(2); // 2 is the first prime number
int num=2;
while (count < 20) {
num++; // try next number
boolean isPrime=true;
for (int i=2; i<num; i++) {
times++;
if (num%i == 0 ){ // divisible by i
isPrime = false; // not a prime
break;
}
}
if (isPrime) {
count++; // one more prime is found
System.out.print(", " + num);
}
}
System.out.println("\nDone");
System.out.println("Total calculation = " + times);
}
}

View File

@@ -0,0 +1,15 @@
import java.util.Scanner;
public class Ex6a {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Number? ");
int num = input.nextInt();
for(int i = 1; i <= num; i++){
for(int j = 1; j <= i; j++){
System.out.print(j);
}
System.out.println();
}
}
}

View File

@@ -0,0 +1,16 @@
import java.util.Scanner;
public class Ex6b {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Number? ");
int num = input.nextInt();
for(int i = 1; i <= num; i++){
for( int j = 0; j < num-i; j++)
System.out.print(" ");
for (int k = 1; k <=i; k++)
System.out.print(k);
System.out.println();
}
}
}

View File

@@ -0,0 +1,32 @@
import java.util.Scanner;
public class Ex7 {
final static String[] option = {"Paper", "Scissor", "Stone"};
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while(true){
System.out.print("0:Paper 1:Scissor 2:Stone 3:Exit? ");
int userInput = input.nextInt();
if(userInput == 3)
break;
int cmpInput = (int) (Math.random()*3);
System.out.printf("You choose %s vs CPU choose %s\n", option[userInput], option[cmpInput]);
if(userInput == cmpInput)
System.out.println("It's Draw");
else {
if(userInput == 0 && cmpInput == 2 ||
userInput == 1 && cmpInput == 0 ||
userInput == 2 && cmpInput == 1){
System.out.println("You Win");
}
else {
System.out.println("You Lose");
}
}
}
System.out.println("Bye Bye!");
}
}

View File

@@ -0,0 +1,38 @@
import java.util.Arrays;
import java.util.DoubleSummaryStatistics;
import java.util.Scanner;
import java.util.stream.DoubleStream;
class Ex8{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double[] values = new double[10];
int index = 0;
while(index < 10){
double value = input.nextDouble();
if(value == -1)
break;
if(value > 0)
values[index++] = value;
}
double sum, mean, max, min, mu, sd;
sum = mean = mu = sd = 0.0;
min = max = values[0];
for(int i = 0; i < index; i++){
sum += values[i];
if(max < values[i])
max = values[i];
if(min > values[i])
min = values[i];
}
mean = mu = sum/index;
double tmpsum = 0.0;
for(int i = 0; i < index; i++)
tmpsum += Math.pow((values[i]-mu) , 2);
sd = Math.sqrt(tmpsum/index);
System.out.printf("sum=%.2f, mean=%.2f, maximum=%.2f, minimum=%.2f, and standard deviation=%.2f\n", sum, mean, max, min, sd);
}
}

View File

@@ -0,0 +1,28 @@
import java.util.Scanner;
public class Ex9 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter x (in radians): ");
double result = 0.0;
double x = result = input.nextDouble();
System.out.println("Term 1 = " + x);
for(int i = 3; i <= 27; i+=2){
double factorial = 1;
for(int j = 2; j <= i; j++)
factorial *= j;
double value = Math.pow(x, i)/factorial;
int term = i/2;
if((term %2) == 0){
result += value;
System.out.println("Term " + (term+1) + " = " + value);
}else{
result -= value;
System.out.println("Term " + (term+1) + " = -" + value);
}
}
System.out.println("Sin(" + x + ")=" + result);
}
}

View File

@@ -0,0 +1,14 @@
public class Q6cExtra {
public static void main(String[] args) {
for(int i = 0; i < 5; i++){
for(int s = 0; s < i; s++)
System.out.print(" ");
for(int j = i+1; j <= 5; j++)
System.out.print(" "+j);
System.out.println();
}
}
}

View File

@@ -0,0 +1,9 @@
public class Q6dExtra {
public static void main(String[] args) {
for(int i = 0; i < 5; i++){
for (int j = 5-i; j > 0; j--)
System.out.print(j + " ");
System.out.println();
}
}
}

View File

@@ -0,0 +1,9 @@
public class Q6eExtra {
public static void main(String[] args) {
for(int i = 0 ; i < 5; i++){
for(int j = 5; j > 0 + 4 - i; j--)
System.out.print(j + " ");
System.out.println();
}
}
}

View File

@@ -0,0 +1,11 @@
public class Q6fExtra {
public static void main(String[] args) {
for(int i = 0; i < 5; i++){
for(int s = 0; s < 4-i; s++)
System.out.print(" ");
for(int j = 5; j > 4-i; j--)
System.out.print(" " + j);
System.out.println();
}
}
}

View File

@@ -0,0 +1,11 @@
public class Q6gExtra {
public static void main(String[] args) {
for(int i = 0; i < 5; i++){
for (int s = 0; s < i; s++)
System.out.print(" ");
for( int j = 5-i; j > 0; j--)
System.out.print(j + " ");
System.out.println();
}
}
}

View File

@@ -0,0 +1,283 @@
# Lab 8 Repetition Part 2 (Nested Loops)
## Topic 3: Basic Program Structures
### Intended Learning Outcomes
Upon completion of this lab, you should be able to:
- Trace loops to determine their actions, such as the number of iterations.
- Use loops to process elements in an array.
- Use nested loops to generate two-dimensional tables.
## Exercise 1
What will be the value of x after executing the program fragments below?
(a)
```java
int x, a=0;
for (x=9; x>=1; x--) {
a++;
if (a == 4)
break;
}
// x is 6
```
(b)
```java
int a=9, x=0;
while (a > 0) {
a--;
x+=2;
if (a < 3)
continue;
x+=3;
}
// x is 36
```
## Exercise 2
Will the programs below terminate? If so, give the output.
(a)
```java
int balance = 100;
while ( true ) {
if ( balance < 12 )
break;
balance = balance 12;
}
System.out.println( "Balance is " + balance );
// Output:
Balance is 4
```
(b)
```java
int balance = 100;
while ( true ) {
if ( balance < 12 )
continue;
balance = balance 12;
}
System.out.println( "Balance is " + balance );
// loop
```
## Exercise 3
What will be the number of times the statement marked with a comment executes?
(a)
```java
for (i=0; i<5; i++)
for (j=0; j<7; j++)
System.out.println("loop"); // statement in question
// 5*7 = 35 times
```
(b)
```java
for (i=0; i<5; i++)
for (j=0; j<7; j++)
for (k=0; k<6; k++)
System.out.println("another loop");
System.out.println("loop"); // statement in question
// 1 times, due to for loop not {}. Therefore, the loop will only handle next line only.
```
## Exercise 4
Determine the output of the program below.
(a)
```java
public class Test {
public static void main ( String[] args ) {
for ( int i = 1; i < 5; i++ ) {
int j = 0;
while ( j < i ) {
System.out.print( j + " " );
j++;
}
}
System.out.println();
}
}
// Output:
0 0 1 0 1 2 0 1 2 3
```
(b)
```java
public static void main( String[] args ) {
String s1;
for ( int row=1; row<=5; row++ ) {
s1 = "";
for ( int column=1; column<=5; column++ ) {
s1 += ( row == column ) ? "*" : " ";
}
System.out.println( s1 );
}
}
// Output:
*
*
*
*
*
```
(c)
```java
for (int i=0; i<2; i++) {
System.out.println("outer " + i);
for (int j=0; j<3; j++) {
System.out.println("Inner " + i + " " + j);
}
for (int k=2; k>0; k--) {
System.out.println("Inner " + i + " " + k);
}
}
// Output:
outer 0
Inner 0 0
Inner 0 1
Inner 0 2
Inner 0 2
Inner 0 1
outer 1
Inner 1 0
Inner 1 1
Inner 1 2
Inner 1 2
Inner 1 1
```
## Exercise 5
In lecture notes 3.2 (Repetition Structures Part 2), the Java program FindPrime is used to illustrate nested-loops.
```java
public class FindPrime {
public static void main(String[] args) {
int count = 1;
System.out.print(2); // 2 is the first prime number
int num = 2;
while (count < 20) {
num++; // try next number
boolean isPrime = true;
for (int i = 2; i < num; i++) {
if (num % i == 0) // divisible by i
isPrime = false; // not a prime
}
if (isPrime) {
count++; // one more prime is found
System.out.print(", " + num);
}
}
System.out.println("\nDone");
}
}
```
(a) Add some program statements to count the number of times the inner-loop has been executed, and verify that it agrees with the value 2415 given in the lecture notes.
```
c:\> java FindPrime
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71
Done
Total calculation = 2415
```
(b) Modify the program so that the number of times the inner-loop is executed can be reduced without sacrificing the correctness of the program. Report the number of times the inner-loop has been executed in your improved program.
```
c:\> java FindPrime2
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71
Done
Total calculation = 677
```
## Exercise 6
Write a program that asks the user to input an integer. The program then prints a pattern with the number of lines controlled by the user input. You must use a nested-for loop.
(a)
```
c:\exercises> java Pattern
Number? 4
1
12
123
1234
```
(b)
```
c:\exercises> java Pattern2
Number? 5
1
12
123
1234
12345
```
## Exercise 7
Generate a Multiplication Table:
Write a Java program to fill values to a two-dimensional array, mTable[10][10], for a multiplication table. Print the multiplication table as follows.
```
0 1 2 3 4 5 6 7 8 9
+------------------------------
0| 0 0 0 0 0 0 0 0 0 0
1| 0 1 2 3 4 5 6 7 8 9
2| 0 2 4 6 8 10 12 14 16 18
3| 0 3 6 9 12 15 18 21 24 27
4| 0 4 8 12 16 20 24 28 32 36
5| 0 5 10 15 20 25 30 35 40 45
6| 0 6 12 18 24 30 36 42 48 54
7| 0 7 14 21 28 35 42 49 56 63
8| 0 8 16 24 32 40 48 56 64 72
9| 0 9 18 27 36 45 54 63 72 81
```
## Exercise 8
Write a Java program to prompt a user to input some positive real numbers and store them in an array. The user can enter no more than 10 numbers. The program should stop prompting input when the user has entered the 10th number or input a negative value, e.g. -1. Then, the program starts to calculate the following statistics.
1. Sum = $\sum_{i=1}^{n}x_i$
2. Mean, $\overline{x} = \frac{Sum}{n}$
3. Maximum
4. Minimum
5. Standard Deviation, $\sigma = \sqrt{\frac{\sum_{i=1}^{n}(x_i-\overline{x})^2}{n-1}}$ (for $n>1$ only)
Test your program with the following five numbers, 1.23, 2.05, 4.0, 0.01, 0.12. Their sum=7.41, mean=1.48, maximum=4.0, minimum=0.01, and standard deviation=1.64.
## Exercise 9
Approximate sin x by a sum of series:
Write a Java program to calculate the following series ($x$ is in radians, $360° = 2\pi$ radians):
```math
\sin(x)=x-\frac{x^3}{3!}+\frac{x^5}{5!}-\frac{x^7}{7!}+\frac{x^9}{9!}-\frac{x^{11}}{11!}...+\frac{x^{25}}{25!}-\frac{x^{27}}{27!'}, -3.1416 < x < 3.1416
```
**Sample Output**
```
C:\>java SinX
Enter x (in radians): _2_
Term 1 = 2.0
Term 2 = -1.3333333333333333
Term 3 = 0.26666666666666666
Term 4 = -0.025396825396825393
Term 5 = 0.0014109347442680773
Term 6 = -5.130671797338463E-5
Term 7 = 1.3155568711124264E-6
Term 8 = -2.5058226116427168E-8
Term 9 = 3.6850332524157597E-10
Term 10 = -4.309980412182175E-12
Term 11 = 4.1047432496973094E-14
Term 12 = -3.2448563238713907E-16
Term 13 = 2.163237549247594E-18
Term 14 = -1.2326139881752673E-20
Sin(2.0)=0.9092974268256817
```

View File

@@ -0,0 +1,16 @@
import java.util.*;
public class Ex3 {
public static void main(String [] args) {
Scanner kb = new Scanner(System.in);
System.out.print("? ");
int num = kb.nextInt();
countDown(num);
}
public static void countDown(int num) {
for (int i = num; i > 0; i--)
System.out.print(i + " ");
System.out.println();
}
}

View File

@@ -0,0 +1,17 @@
import java.util.Scanner;
public class Ex4 {
public static void main(String [] args) {
Scanner kb = new Scanner(System.in);
System.out.print("Your age? ");
int manAge = kb.nextInt();
int wifeAge;
// call idealAge() with manAge as argument
wifeAge = idealAge(manAge);
System.out.println("Ideal age of wife = " + wifeAge);
}
public static int idealAge(int age) {
return ( age / 2) + 7;
}
}

View File

@@ -0,0 +1,18 @@
import java.util.Scanner;
public class Ex5 {
public static void main(String [] args) {
Scanner kb = new Scanner(System.in);
System.out.print("? ");
int num = kb.nextInt();
if (isDivisibleBy7(num)) // call isDivisibleBy7() with num as argument
System.out.println(num + " is divisible by 7");
else
System.out.println(num + " is not divisible by 7");
}
public static boolean isDivisibleBy7(int num) {
return num %7 == 0;
}
}

View File

@@ -0,0 +1,24 @@
import java.util.Scanner;
public class Ex6 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double a, b, c;
System.out.print("a? ");
a = input.nextDouble();
System.out.print("b? ");
b = input.nextDouble();
System.out.print("c? ");
c = input.nextDouble();
if(isRightAngledTriangle(a, b, c))
System.out.println("It is a right-angled triangle");
else
System.out.println("It is not a right-angled triangle");
}
public static boolean isRightAngledTriangle(double a, double b, double c){
return (a*a + b*b) == (c*c);
}
}

View File

@@ -0,0 +1,23 @@
import java.util.Scanner;
public class Ex7 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("? ");
int num = input.nextInt();
if(isPrime(num))
System.out.printf("%d is a prime number\n", num);
else
System.out.printf("%d is not a prime number\n", num);
}
public static boolean isPrime(int num) {
if(num==2)
return true;
for (int i = 2; i < num; i++){
if (num%i == 0)
return false;
}
return true;
}
}

View File

@@ -0,0 +1,321 @@
# Lab 9 Methods and Parameter Passing
## Topic 3: Basic Program Structures
## Exercise 1
Show the output of the following programs.
(a)
```java
public class Q1a {
public static void main( String[] args ) {
question();
answer();
}
public static void answer() {
System.out.println("javac.exe");
}
public static void question() {
System.out.println("What is the command to compile a Java program?");
}
}
// Output:
What is the command to compile a Java program?
javac.exe
```
(b)
```java
public class Q1b {
public static void main( String[] args ) {
firstName("Peter");
}
public static void firstName( String Name ) {
System.out.println("Call me " + Name + "." );
}
}
// Output:
Call me Peter.
```
(c)
```java
public class Q1c {
public static void main( String[] args ) {
potato( 1 );
potato( 2 );
potato( 3 );
}
public static void potato( int Quantity ) {
System.out.println(Quantity + " potato");
}
}
// Output:
1 potato
2 potato
3 potato
```
(d)
```java
public class Q1d {
public static void main( String[] args ) {
characterType( 'A' );
characterType( 'z' );
characterType( '5' );
}
public static void characterType( char ch ) {
System.out.print( "'" + ch + "' is a " );
if ( ( ch >= 'A' ) && ( ch <= 'Z' ) )
System.out.println( "upper-case letter." );
else if ( ( ch >= 'a' ) && ( ch <= 'z' ) )
System.out.println( "lower-case letter." );
else if ( ( ch >= '0' ) && ( ch <= '9' ) )
System.out.println( "digit." );
}
}
// Output:
'A' is a upper-case letter.
'z' is a lower-case letter.
'5' is a digit.
```
## Exercise 2
Show the output of the following programs.
(a)
```java
public class Q2a {
public static void main( String[] args ) {
double acres = 5;
System.out.println( "You can park about " + cars(acres)+ " cars." );
}
public static double cars( double x ) {
return 100 * x;
}
}
// Output:
You can park about 500 cars.
```
(b)
```java
public class Q2b {
public static void main( String[] args ) {
double r = 1; // Radius of the base of a cylinder
double h = 2; // Height of a cylinder
displayVolume( r, h );
r = 3;
h = 4;
displayVolume( r, h );
}
public static double getArea( double r ) {
return 3.14159 * r * r;
}
public static void displayVolume( double r, double h ) {
double area = getArea(r);
System.out.println("Volume of cylinder having base area " + area +
" and height " + h + " is " + ( h * area ) + "." );
}
}
// Output:
Volume of cylinder having base area 3.14159 and height 2.0 is 6.28318.
Volume of cylinder having base area 28.274309999999996 and height 4.0 is 113.09723999999999.
```
(c)
```java
public class Q2c {
public static void main( String[] args ) {
double maxResult = max4( 2.3, 4.9, -5.1, 0.0 );
System.out.println( "The maximum is " + maxResult);
}
public static double max2( double a, double b ) {
return ( a > b ) ? a : b;
}
public static double max4( double a, double b, double c, double d ) {
return max2( max2( a, b ), max2( c, d ) );
}
}
// Output:
The maximum is 4.9
```
(d)
```java
import java.util.*;
public class Q2d {
public static void main(String [] args) {
Scanner kb = new Scanner(System.in);
int street;
System.out.print("Street number? ");
street = kb.nextInt();
if (isEven(street))
System.out.println("East-bound");
else
System.out.println("West-bound");
}
public static boolean isEven( int num ) {
return num%2 == 0;
}
}
// Output:
Street number? 1
West-bound
```
## Exercise 3
Complete the method `countDown()` in the program below. The program allows the users to enter an integer value and prints the counting down of the integer. Example executions are shown below. User inputs are underline.
```
c:\> java Ex3
? _3_
3 2 1
```
```
c:\> java Ex3
? _5_
5 4 3 2 1
```
```java
import java.util.*;
public class Ex3 {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("? ");
int num = kb.nextInt();
countDown(num);
}
public static ________ countDown(_____________) {
___ missing codes ____
}
}
```
## Exercise 4
**Ideal Age of Wife**: According to Plato, a man should marry a woman whose age is half his age plus seven years. Write a Java program that requests a mans age as input. The `main()` method then calls a method `idealAge()`, passing the mans age as argument. The method then returns to the ideal age of his wife for the `main()` method to print on the screen. The program skeleton is shown below.
```java
import java.util.Scanner;
public class Ex4 {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("Your age? ");
int manAge = kb.nextInt();
int wifeAge;
// call idealAge() with manAge as argument
System.out.println("Ideal age of wife = " + wifeAge);
}
public static _______ idealAge(____________) {
___ missing codes ____
}
}
```
```
c:\> java Ex4
Your age? _18_
Ideal age of wife = 16
```
## Exercise 5
Write a Java program to let users enter an integer. The integer is then passed to a `boolean` method as argument. The method checks if the integer is divisible by 7. Return `true` if so, and `false` otherwise. Test you method by developing a complete Java program and calling the method from `main()`.
```java
import java.util.Scanner;
public class Ex5 {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("? ");
int num = kb.nextInt();
if (________________) // call isDivisibleBy7() with num as argument
System.out.println(num + " is divisible by 7");
else
System.out.println(num + " is not divisible by 7");
}
public static __________ isDivisibleBy7(___________) {
___ missing codes ____
}
}
```
```
c:\> java Ex5
? _21_
21 is divisible by 7
```
## Exercise 6
Write a Java program to let users enter the three sides of a triangle. The three sides are then passed to a `boolean` method as argument. The method checks if it the triangle is right-angled by using the Pythagorean Theorem $a^2 + b^2 = c^2$. Test you method by developing a complete Java program and calling the method from `main()`.
```
c:\> java Ex6
a ? _3_
b ? _4_
c ? _5_
It is a right-angled triangle
```
```
c:\> java Ex6
a ? _3_
b ? _3_
c ? _4_
It is not a right-angled triangle
```
## Exercise 7
In Lab 8 Exercise 5 (b), you have developed a Java program to print 20 prime numbers on screen. You are now required to enhance the functionality of the program.
- Move the program logic for checking whether a number is prime to a `boolean` method `isPrime()`. The method receives the integer to be checked as a parameter.
- Modify the program so that users are allowed to enter the integer to be checked during runtime.
- NOTE: The new program does not need to find 20 prime numbers, thus the program logic is much more simple.
Example executions are shown below. User inputs are highlighted in underline.
```
c:\> java Ex7
? _6_
6 is not a prime number
```
```
c:\> java Ex7
? _11_
11 is a prime number
```

View File

@@ -0,0 +1,33 @@
public class Employee {
String name;
int salary;
Employee(String name, int salary){
this.name = name;
this.salary = salary;
}
public Employee() {}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public void displayDetails(){
System.out.printf("Employee 1: name=%s salary=%d\n", name, salary);
}
public void raiseSalary(double perc){
salary = (int)(salary * perc) + salary;
}
}

View File

@@ -0,0 +1,24 @@
class Ex1b {
public static void main(String[] args) {
Employee emp1 = new Employee();
Employee emp2 = new Employee();
int oldSalary;
// Part 1-2 here
emp1.setName("Chan Tai Man");
emp1.setSalary(12000);
emp2.setName("Tam Pring Shing");
emp2.setSalary(13500);
// Part 3 below
System.out.println("Before-");
System.out.println("Employee 1: name=" + emp1.getName() + " salary=" + emp1.getSalary());
System.out.println("Employee 2: name=" + emp2.getName() + " salary=" + emp2.getSalary());
// Part 4-5 here
emp1.setSalary((int) (emp1.getSalary()*0.1)+emp1.getSalary());
emp2.setSalary(((int) (emp2.getSalary()*0.05) + emp2.getSalary()));
System.out.println("After-");
System.out.println("Employee 1: name=" + emp1.getName() + " salary=" + emp1.getSalary());
System.out.println("Employee 2: name=" + emp2.getName() + " salary=" + emp2.getSalary());
}
}

View File

@@ -0,0 +1,15 @@
public class Ex1cde {
public static void main(String[] args) {
Employee emp1 = new Employee("Chan Tai Main", 12000);
Employee emp2 = new Employee("Tam Ping Shing", 13500);
System.out.println("Before-");
emp1.displayDetails();
emp2.displayDetails();
emp1.raiseSalary(0.1);
emp2.raiseSalary(0.05);
System.out.println("After-");
emp1.displayDetails();
emp2.displayDetails();
}
}

View File

@@ -0,0 +1,24 @@
public class Ex2b {
public static void main(String[] args) {
Student stud1 = new Student();
Student stud2 = new Student();
Student stud3 = new Student();
stud1.setId(310567);
stud1.setName("Cheung Siu Ming");
stud1.setScore(87.1);
stud2.setId(451267);
stud2.setName("Ng Wau Man");
stud2.setScore(77.5);
stud3.setId(789014);
stud3.setName("Wong Sui Kai");
stud3.setScore(83.4);
System.out.printf("Student: name=%s id=%d score=%.1f\n", stud1.getName(), stud1.getId(), stud1.getScore());
System.out.printf("Student: name=%s id=%d score=%.1f\n", stud2.getName(), stud2.getId(), stud2.getScore());
System.out.printf("Student: name=%s id=%d score=%.1f\n", stud3.getName(), stud3.getId(), stud3.getScore());
System.out.println("Average Score =" + (stud1.getScore()+stud2.getScore()+stud3.getScore())/ 3);
}
}

View File

@@ -0,0 +1,15 @@
public class Ex2c {
public static void main(String[] args) {
Student[] students = new Student[3];
students[0] = new Student("Cheung Siu Ming", 310567, 87.1);
students[1] = new Student("CNg Wai Man", 451267, 77.5);
students[2] = new Student("Wong Sui Kai", 789014, 83.4);
double totalScore = 0.0;
for (Student student : students) {
student.printDetails();
totalScore += student.getScore();
}
System.out.println("Average Score = " + totalScore/students.length);
}
}

View File

@@ -0,0 +1,41 @@
public class Student {
String name;
int id;
double score;
Student(){}
Student(String name, int id, double score) {
this.name = name;
this.id = id;
this.score = score;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setScore(double score) {
this.score = score;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public double getScore() {
return score;
}
public void printDetails(){
System.out.println("Student: name="+name+" id=" + id + " score="+score);
}
}

View File

@@ -0,0 +1,35 @@
class AStudent {
private String name;
public int age;
public void setName(String inName) {
name = inName;
}
public String getName() {
return name;
}
public void setAge(int age) {
if(age<0 || age>120){
this.age = 18;
System.out.println("Invalid age:" + age + ", reset it to 18");
}else
this.age = age;
}
}
public class Ex3 {
public static void main(String s[]) {
AStudent stud1 = new AStudent();
AStudent stud2 = new AStudent();
stud1.setName("Chan Tai Man");
stud1.setAge(19);
stud2.setName("Ng Hing");
stud2.setAge(-23);
System.out.println("Student: name="+stud1.getName() +
", age=" + stud1.age);
System.out.println("Student: name="+stud2.getName() +
", age=" + stud2.age);
}
}

View File

@@ -0,0 +1,48 @@
class CurrencyConverter {
private double exchangeRate;
private double commissionRate;
private int largeAmount;
public CurrencyConverter(double er , double cr){
exchangeRate = er;
commissionRate = cr;
}
public double fromUSDollar(double dollar){
if (dollar >= largeAmount)
return (dollar * exchangeRate * (1-commissionRate*0.5));
else
return (dollar * exchangeRate * (1-commissionRate));
}
public double toUSDollar(double foreignMoney){
if (foreignMoney/exchangeRate >= largeAmount)
return (foreignMoney/exchangeRate*(1-commissionRate*0.5));
else
return (foreignMoney/exchangeRate*(1-commissionRate));
}
public void setExchangeRate(double rate){
exchangeRate = rate;
}
public double getExchangeRate(){
return exchangeRate;
}
public void setCommissionRate(double rate){
commissionRate = rate;
}
public double getCommissionRate(){
return commissionRate;
}
public void setLargeAmount(int amount){
largeAmount = amount;
}
public int getLargeAmount(){
return largeAmount;
}
}

View File

@@ -0,0 +1,19 @@
public class Ex4 {
public static void main(String[] args) {
CurrencyConverter yenConverter = new CurrencyConverter(115.7, 0.0005);
CurrencyConverter euroConverter = new CurrencyConverter(0.9881, 0.0003);
yenConverter.setLargeAmount(50000);
euroConverter.setLargeAmount(50000);
int yens = 1500000;
System.out.println(yens + " yens = US$ " + yenConverter.toUSDollar(yens));
int usd = 20000;
System.out.println("US$ " + usd + " = " + yenConverter.fromUSDollar(usd) + " yens");
int euros = 170000;
System.out.println(euros + " euros = US$ " + euroConverter.toUSDollar(euros));
usd = 20000;
System.out.println("US$ " + usd + " = " + euroConverter.fromUSDollar(usd) + " euros");
}
}

View File

@@ -0,0 +1,241 @@
# Lab 10 Objects and Classes
## Topic 4.1 to 4.4 Part (a) Objects and Classes
## Exercise 1
(a) Create a class `Employee` that has
Variables:
| Instance Variable name | Data type |
| - | - |
| name | String |
| salary | int |
Methods:`getName()`, `setName()`, `getSalary()` and `setSalary()`
(b) Complete the following test program that creates two `Employee` object instances named `emp1` and `emp2`. Then perform the followings:
1. Set the name and salary of `emp1` to *"Chan Tai Man"* and 12000, respectively.
2. Set the name and salary of `emp2` to *"Tam Ping Shing"* and 13500, respectively.
3. Print the current details of `emp1` and ``emp2``.
4. Increase the salary of *"Chan Tai Man"* by 10% and the salary of *"Tam Ping Shing"* by 5%.
5. Print the new details of `emp1` and `emp2`.
```java
public class Ex1b {
public static void main(String[] args) {
Employee emp1 = new Employee();
Employee emp2 = new Employee();
int oldSalary;
// Part 1-2 here
// Part 3 below
System.out.println("Before-");
System.out.println("Employee 1: name=" + emp1.getName() +" salary=" + emp1.getSalary());
System.out.println("Employee 2: name=" + emp2.getName() +" salary=" + emp2.getSalary());
// Part 4-5 here
}
}
```
The output of the program is shown below.
```
C:\> java Ex1b
Before-
Employee 1: name=Chan Tai Man salary=12000
Employee 2: name=Tam Ping Shing salary=13500
After-
Employee 1: name=Chan Tai Man salary=13200
Employee 2: name=Tam Ping Shing salary=14175
```
(c) Redo Part (b) by adding a Constructor to set the name and salary.
(d) Add a method `displayDetails()` to display the name and salary in Employee class, and modify Ex1b to use `displayDetails()`to print the details of `emp1` and `emp2`.
(e) Add method `raiseSalary()` that accepts a percentage increase in salary (`double`) as argument and increases the salary by the corresponding percentage. Create a new Test program `Ex1cde.java` to raise Chans salary by 10% and that of Tam by 5%. Print the details of `emp1` and `emp2` after the increase of salaries.
```
C:\> java Ex1cde
Before-
Employee: name=Chan Tai Man salary=12000
Employee: name=Tam Ping Shing salary=13500
After-
Employee: name=Chan Tai Man salary=13200
Employee: name=Tam Ping Shing salary=14175
```
## Exercise 2
(a) Create a class `Student` that has
Variables:
| Attribute name | Data type |
| - | - |
| name | String |
| id | int |
| score | double |
Methods: *the getter and setter methods for each of the above attributes.*
(b) Write a test program Ex2b.java that creates three Student object instances named `stud1`, `stud2` and `stud3`. Then perform the followings:
1. Set the name, id and score of stud1 to *"Cheung Siu Ming"*, 310567 and 87.1.
2. Set the name, id and score of stud2 to *"Ng Wai Man"*, 451267 and 77.5.
3. Set the name, id and score of stud3 to *"Wong Sui Kai"*, 789014 and 83.4.
4. Print the details of `stud1`, `stud2` and `stud3`.
5. Find and print the average score among the three students.
The output of the program is shown below.
```
C:\> java Ex2b
Student : name=Cheung Siu Ming id=310567 score=87.1
Student : name=Ng Wai Man id=451267 score=77.5
Student : name=Wong Sui Kai id=789014 score=83.4
Average Score = 82.66666666666667
```
(c) Redo Part (b) by adding a Constructor to set the name, id and score and then create a new test program `Ex2c.java` to test it.
```
C:\> java Ex2c
Student : name=Cheung Siu Ming id=310567 score=87.1
Student : name=Ng Wai Man id=451267 score=77.5
Student : name=Wong Sui Kai id=789014 score=83.4
Average Score = 82.66666666666667
```
## Exercise 2
Consider the following classes.
```java
class AStudent {
private String name;
public int age;
public void setName(String inName) {
name = inName;
}
public String getName() {
return name;
}
}
public class Ex3 {
public static void main(String s[]) {
AStudent stud1 = new AStudent();
AStudent stud2 = new AStudent();
stud1.setName("Chan Tai Man");
stud1.age = 19;
stud2.setName("Ng Hing");
stud2.age = -23;
System.out.println("Student: name=" + stud1.getName() +", age=" + stud1.age);
System.out.println("Student: name=" + stud2.getName() +", age=" + stud2.age);
}
}
```
For the object `stud2`, age is -23 which is a negative value, this is not allowed in human being.
Enhance the class `AStudent` by enforcing data encapsulation on the attribute `age`. If the inputted `age` is invalid, print an error message and set the age to 18.
```
C:\> java Ex3
-23 is not allowed! Age must be greater than or equal to 18!
Student: name=Chan Tai Man, age=19
Student: name=Ng Hing, age=18
```
## Exercise 4
Given the following CurrencyConverter class which handles the exchange between a foreign currency and US dollars.
```java
public class CurrencyConverter {
private double exchangeRate;
private double commissionRate;
private int largeAmount;
public CurrencyConverter(double er, double cr) {
exchangeRate = er;
commissionRate = cr;
}
public double fromUSDollar(double dollar) {
if (dollar >= largeAmount)
return (dollar * exchangeRate * (1 - commissionRate * 0.5));
else
return (dollar * exchangeRate * (1 - commissionRate));
}
public double toUSDollar(double foreignMoney) {
if (foreignMoney / exchangeRate >= largeAmount)
return (foreignMoney / exchangeRate * (1 - commissionRate * 0.5));
else
return (foreignMoney / exchangeRate * (1 - commissionRate));
}
public void setExchangeRate(double rate) {
exchangeRate = rate;
}
public double getExchangeRate() {
return exchangeRate;
}
public void setCommissionRate(double rate) {
commissionRate = rate;
}
public double getCommissionRate() {
return commissionRate;
}
public void setLargeAmount(int amount) {
largeAmount = amount;
}
public int getLargeAmount() {
return largeAmount;
}
}
```
Write a test program `Ex4.java` to test the CurrencyConverter class by performing the following operations:
1. Instantiate two `CurrencyConverter` object with the following attributes:
| | exchangeRate | comissionRate |
| - | - | - |
| yenConverter | 115.7 | 0.0005 |
| euroCOnverter | 0.9881 | 0.0003 |
2. Set `largeAmount` to 50000.
3. Use the `yenConverter` to convert 1500000 yens to US dollars.
4. Use the `yenConverter` to convert from US$2000 to yens.
5. Set the exchange rate of euro to 0.9881.
6. Use the `euroConverter` to convert 170000 euros to US$.
7. Use the `euroConverter` to convert from US$20000 to euros.
Sample output
```
C:\> java Ex4
1500000 yens = US$ 12958.0812445981
US$ 2000 = 231284.30000000002 yens
170000 euros = US$ 172021.55652261918
US$ 20000 = 19756.0714 euros
```

View File

@@ -0,0 +1,7 @@
public class Ex7 {
public static void main(String[] args) {
Point p1 = new Point(4, 5);
Point p2 = new Point(11, 4);
System.out.println("Distance = " + p1.distance(p2));
}
}

View File

@@ -0,0 +1,28 @@
public class Point {
private int x;
private int y;
public Point() {
this(0, 0);
}
public Point(int x, int y) {
setPoint(x, y);
}
public void setPoint(int x, int y) {
if (x>=0 && y>=0) {
this.x = x;
this.y = y;
}
}
public int getX() { return x; }
public int getY() { return y; }
public double distance(Point p) {
return Math.sqrt((x-p.x)*(x-p.x) + (y-p.y)*(y-p.y));
}
}

View File

@@ -0,0 +1,7 @@
public class Ex8 {
public static void main(String[] args) {
Student stu1 = new Student("John Chan"); //line 10
System.out.println(Student.numberOfStudent); //line 11
System.out.println(stu1.name); //line 12
}
}

View File

@@ -0,0 +1,17 @@
public class Student {
public static int numberOfStudent=0; //line 1
public String name; //line 2
public Student (String name) { //line 3
numberOfStudent++ ; //line 4
setName(name); //line 5
}
public int getNumberOfStudent() { //line 6
return numberOfStudent; //line 7
}
public void setName(String name) { //line 8
this.name = name; //line 9
}
}

View File

@@ -0,0 +1,345 @@
# Lab 11
## Exercise 1
You are given the Java classes `Circle`, `Rectangle` and `Test` below.
```java
public class Circle {
private double radius;
public Circle(double r) {
radius = r;
}
public double area() {
return radius * radius * Math.PI;
}
}
public class Rectangle {
private double length;
private double width;
public Rectangle(double l, double w) {
length = l;
width = w;
}
public double area() {
return length * width;
}
}
public class Test {
public static void main(String[] args) {
Rectangle r = new Rectangle(30.1, 10.2);
Circle c = new Circle(5.3);
System.out.println("r=" + r);
System.out.println("c=" + c);
}
}
```
Execute `Test` and write down the output.
```
r=Rectangle@19e1023e
c=Circle@3a4afd8d
# RAM address
```
## Exercise 2
You are given the Java classes `Test2` below. Execute the program together with the `Rectangle` class in Exercise 1.
```java
public class Test2 {
public static void main(String[] args) {
Rectangle r = new Rectangle(1, 2);
System.out.println("r=" + r);
System.out.println("area=" + r.area());
r = new Rectangle(3, 4);
System.out.println("r=" + r);
System.out.println("area=" + r.area());
r = null;
System.out.println("r=" + r);
System.out.println("area=" + r.area());
}
}
```
Execute `Test2` and write down the output. Can you explain the output?
```
r=Rectangle@27ddd392
area=2.0
r=Rectangle@2a098129
area=12.0
r=null
Exception in thread "main" java.lang.NullPointerException
```
## Exercise 3
You are given the Java classes `Triangle` below.
```java
public class Triangle {
private int base;
private int height;
public Triangle() {
base = 0;
height = 0;
}
public Triangle(int base, int height) {
this.base = base;
this.height = height;
}
public void printThis() {
System.out.println(this);
}
public static void main(String[] args) {
Triangle t = new Triangle(1, 2);
System.out.println(t);
t.printThis();
}
}
```
Execute `Triangle` and write down the output. Can you explain the output? Discuss what `this` is in an object instance.
```
Triangle@6504e3b2
Triangle@6504e3b2
# RAM Address
```
## Exercise 4
You are given the Java classes Date and DateUser below.
```java
public class Date {
private int day;
private int month;
private int year;
public Date() {
this(1, 1, 1970);
}
public Date(int day, int month, int year) {
this.day = day;
this.month = month;
this.year = year;
}
public String toString() {
return "[" + day + "/" + month + "/" + year + "]";
}
}
public class DateUser {
public static void main(String[] args) {
Date d1 = new Date();
System.out.println(d1);
}
}
```
(a) Execute `DateUser` and observer the output. Can you explain the purpose of the program statement “`this(1, 1, 1970)`” in the no-argument constructor of `Date`?
(b) Remove the `toString()` method from the `Date` class. Compile and execute the program again. What is the difference?
```
# (a)
[1/1/1970]
# (b)
Date@28a418fc
# RAM Address
```
## Exercise 5
Consider the following class.
```java
public class QuestionOne {
public final int A = 345;
public int b;
private float c;
private void methodOne(int a) {
b = a;
}
public float methodTwo() {
return 23;
}
}
```
Identify the invalid statements in the program below. For each invalid statement, state why it is invalid.
```java
public class Q1Main {
public static void main(String[] args) {
QuestionOne q1 = new QuestionOne(); //line1
q1.A = 12; //line2
q1.b = 12; //line3
q1.c = 12; //line4
q1.methodOne(12); //line5
q1.methodOne(); //line6
System.out.println(q1.methodTwo()); //line7
q1.b = q1.methodTwo(); //line8
}
}
```
```
Q1Main.java:17: cannot assign a value to final variable A
q1.A = 12;
^
Q1Main.java:19: c has private access in QuestionOne
q1.c = 12;
^
Q1Main.java:21: methodOne(int) has private access in QuestionOne
q1.methodOne(12);
^
Q1Main.java:22: methodOne(int) in QuestionOne cannot be applied to ()
q1.methodOne();
^
Q1Main.java:24: possible loss of precision
found : float
required: int
q1.b = q1.methodTwo();
^
5 errors
Tool completed with exit code 1
```
## Exercise 6
Suppose that the class `Foo` is defined as below.
```java
public class Foo {
public int i;
public static String s;
public void imethod() { }
public static void smethod() { }
}
```
Let f be an instance of `Foo`. Determine if each of the following Java statements is valid or invalid.
| Code | valid | invalid |
| ---- | ----- | ------- |
| System.out.println(f.s); | [x] | [] |
| f.smethod(); | [x] | [] |
| System.out.println(Foo.i); | [] | [x] |
| System.out.println(Foo.s); | [x] | [] |
| Foo.imethod(); | [] | [x] |
| Foo.smethod(); | [x] | [] |
## Exercise 7
A `Point` object instance represents a Cartesian coordinate and thus has two member variables, x and y. The Java program `Distance` below instantiates two `Point` object instances to represent the coordinates (4, 5) and (11, 4). The program then displays the distance between the two coordinates by invoking the `distance()` method in the `distance() `method.
Expression to get the distance of two Points (x1, y1) (x2, y2) is `distance = Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));`
```
C:\> java Ex7
Distance = 7.0710678118654755
```
```java
public class Ex7 {
public static void main(String[] args) {
Point p1 = new Point(4, 5);
Point p2 = new Point(11, 4);
System.out.println("Distance = " + p1.distance(p2));
}
}
```
Complete the `Point` class.
```java
public class Point {
private int x;
private int y;
public Point() {
this(0, 0);
}
public Point(int x, int y) {
setPoint(x, y);
}
public void setPoint(int x, int y) {
if (x >= 0 && y >= 0) {
this.x = x;
this.y = y;
}
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public double distance(Point p) {
// COMPLETE THIS METHOD
}
}
```
## Exercise 8
Study the validity of the programs below. Correct those invalid statements.
```java
public class Student {
public static int numberOfStudent = 0; //line 1
public String name; //line 2
public void Student(String name) { //line 3
numberOfStudent++; //line 4
setName(name); //line 5
}
public int getNumberOfStudent() { //line 6
return; //line 7
}
public String setName(String name) { //line 8
name = name; //line 9
}
}
public class Ex8 {
public static void main(String args[]) {
Student stu1 = new Student("John Chan"); //line 10
System.out.println(numberOfStudent); //line 11
System.out.println(name); //line 12
}
}
```
```
C:\> java Ex8
1
John Chan
```

View File

@@ -0,0 +1,11 @@
class Circle {
private double radius;
public Circle(double r) {
radius = r;
}
public double area() {
return radius*radius*Math.PI;
}
}

View File

@@ -0,0 +1,33 @@
class Circle {
private double radius;
public Circle(double r) {
radius = r;
}
public double area() {
return radius*radius*Math.PI;
}
}
class Rectangle {
private double length;
private double width;
public Rectangle(double l, double w) {
length = l;
width = w;
}
public double area() {
return length * width;
}
}
public class Ex1 {
public static void main(String [] args) {
Rectangle r = new Rectangle(30.1, 10.2);
Circle c = new Circle(5.3);
System.out.println("r=" + r);
System.out.println("c=" + c);
}
}

View File

@@ -0,0 +1,15 @@
public class Ex2 {
public static void main(String [] args) {
Rectangle r = new Rectangle(1, 2);
System.out.println("r=" + r);
System.out.println("area=" + r.area());
r = new Rectangle(3, 4);
System.out.println("r=" + r);
System.out.println("area=" + r.area());
r = null;
System.out.println("r=" + r);
System.out.println("area=" + r.area());
}
}

View File

@@ -0,0 +1,11 @@
class Rectangle {
private double length;
private double width;
public Rectangle(double l, double w) {
length = l;
width = w;
}
public double area() {
return length * width;
}
}

View File

@@ -0,0 +1,24 @@
class Triangle {
private int base;
private int height;
public Triangle() {
base = 0;
height = 0;
}
public Triangle(int base, int height) {
this.base = base;
this.height = height;
}
public void printThis() {
System.out.println(this);
}
public static void main(String [] args) {
Triangle t = new Triangle(1, 2);
System.out.println(t);
t.printThis();
}
}

View File

@@ -0,0 +1,28 @@
class Date {
private int day;
private int month;
private int year;
public Date() {
this(1, 1, 1970);
}
public Date(int day, int month, int year) {
this.day = day;
this.month = month;
this.year = year;
}
public String toString() {
return "[" + day + "/" + month + "/" + year + "]";
}
}
public class DataUser {
public static void main(String [] args) {
Date d1 = new Date();
System.out.println(d1);
}
}

View File

@@ -0,0 +1,13 @@
public class Q1Main {
public static void main(String [] args) {
QuestionOne q1 = new QuestionOne(); //line1
q1.A = 12; //line2
q1.b = 12; //line3
q1.c = 12; //line4
q1.methodOne(12); //line5
q1.methodOne();//line6
System.out.println(q1.methodTwo());//line7
q1.b = q1.methodTwo();//line8
}
}

View File

@@ -0,0 +1,12 @@
public class QuestionOne {
public final int A = 345;
public int b;
private float c;
private void methodOne(int a) {
b = a;
}
public float methodTwo() {
return 23;
}
}

View File

@@ -0,0 +1,17 @@
public class Ex1 {
public static void main(String [] args) {
Invoice inv = new Invoice("A123", 4);
double total=0;
inv.addItem("U-231", 34.5, 10);
inv.addItem("J-994", 124.5, 5);
inv.addItem("K-674", 4.5, 100);
for (int i=0; i<inv.getItemCount(); i++) {
System.out.println(inv.getItem(i));
total += inv.getItem(i).getItemTotal();
}
System.out.println("Invoice Total = " + total);
}
}

View File

@@ -0,0 +1,42 @@
public class Invoice {
private String invNumber;
private Item [] itemList;
private int itemCount;
public Invoice(String invNumber, int itemNum) {
// 1. Set instance variable invNumber
// 2. Create an array of Item with number of elements specified
// by parameter itemNum. Refer to Topic 4.6, Slide 9
// 3. Set itemCount to 0, as there is no Item initially.
this.invNumber = invNumber;
itemList = new Item[itemNum];
itemCount = 0;
}
public String getInvNumber() {
return invNumber;
}
public Item[] getItemList() {
return itemList;
}
public int getItemCount() {
return itemCount;
}
public Item getItem(int index) {
return itemList[index];
}
public void addItem(String productCode, double price, int quantity) {
if (itemCount < itemList.length) {
// create a new Item; Refer to Topic 4.6, Slide 9
// save item to appropriate element in itemList
itemList[itemCount] = new Item(productCode, price, quantity);
itemCount++;
} else {
System.out.println("Failed to add new item; max already");
}
}
}

View File

@@ -0,0 +1,19 @@
public class Item {
private String productCode;
private double price;
private int quantity;
public Item(String productCode, double price, int quantity) {
this.productCode = productCode;
this.price = price;
this.quantity = quantity;
}
public double getItemTotal() {
return price * quantity;
}
public String toString() {
return productCode +":" + price + "*" + quantity + "=" + getItemTotal();
}
}

View File

@@ -0,0 +1,17 @@
public class Employee {
public static final int MIN_ID = 1000;
protected String name;
protected int employeeID;
public Employee(String n, int id) {
name = n;
if (id < MIN_ID)
employeeID = 0;
else
employeeID = id;
}
public String toString() {
return "Name: " + name + ", ID: " + employeeID;
}
}

View File

@@ -0,0 +1,9 @@
public class Ex2 {
public static void main(String [] args) {
Employee emp = new Employee("John", 31520);
FTEmployee ftemp = new FTEmployee("Mary", 42680, 15000.5);
System.out.println(emp);
System.out.println(ftemp);
}
}

View File

@@ -0,0 +1,11 @@
public class FTEmployee extends Employee {
double salary;
FTEmployee(String name, int employeeID, double salary){
super(name, employeeID);
this.salary = salary;
}
public String toString(){
return super.toString() + ", Salary: " + salary;
}
}

View File

@@ -0,0 +1,15 @@
public class Ex3 {
public static void main(String [] args) {
Student s1=new Student("Ben", 123, 2);
System.out.println(s1);
Student s2=new Student("John", 246, 6);
System.out.println(s2);
Student os1=new OutstandingStudent("Mary", 456, 3, "academic");
System.out.println(os1);
Student os2=new OutstandingStudent("Peter", 567, 7, "sports");
System.out.println(os2);
}
}

View File

@@ -0,0 +1,11 @@
public class OutstandingStudent extends Student{
String award;
OutstandingStudent(String name, int stid, int year, String award){
super(name, stid, year);
this.award = award;
}
@Override
public String toString() {
return super.toString() + ", Award: " + award;
}
}

View File

@@ -0,0 +1,24 @@
public class Student {
protected String name;
protected int stid; // student id
protected int year;
public Student(String name, int stid, int year) {
this.name = name;
this.stid = stid;
setYear(year);
}
public void setYear(int year) {
if (year>0 && year<=3)
this.year = year;
else {
System.out.println("Wrong input! Year will be set to 1.");
this.year = 1;
}
}
public String toString() {
return "Name: "+name+", Student ID: "+stid+", Year: "+year;
}
}

View File

@@ -0,0 +1,25 @@
public class Coffee extends Drink{
boolean isSweet;
Coffee(String name, int price, int volume, boolean isSweet){
super(name, price, volume);
this.isSweet = isSweet;
}
@Override
public void setPrice(int price) {
// TODO Auto-generated method stub
if(price < 10)
super.setPrice(10);
else
super.setPrice(price);
}
@Override
public String toString() {
// TODO Auto-generated method stub
String sweetStr = "sweet";
if(!isSweet)
sweetStr = "not sweet";
return super.toString() + ", " + sweetStr;
}
}

View File

@@ -0,0 +1,20 @@
public class Drink extends Food {
protected int volume;
Drink(String name, int price, int volume){
super(name, price);
this.volume = volume;
}
@Override
public void setPrice(int price) {
if(price < 5)
super.setPrice(5);
else
super.setPrice(price);
}
@Override
public String toString() {
return super.toString() + ", volume=" + volume;
}
}

View File

@@ -0,0 +1,11 @@
public class Ex4 {
public static void main(String [] args) {
Food f = new Food("Rice", 3);
Drink d = new Drink("Pepsi", 7, 250);
Coffee c = new Coffee("Cappuccino", 13, 200, true);
System.out.println(f);
System.out.println(d);
System.out.println(c);
}
}

View File

@@ -0,0 +1,25 @@
public class Food {
protected String name;
protected int price;
public Food() {
name = null;
price = 0;
}
public Food(String name, int price) {
this.name = name;
setPrice(price);
}
public String toString() {
return "name=" + name + ", price=" + price;
}
public void setPrice(int price) {
if (price >= 0)
this.price = price;
else
this.price = 0;
}
}

View File

@@ -0,0 +1,21 @@
public class Employee5 {
String name;
int employeeID;
protected int salary;
public Employee5(String name, int employeeID) {
this.name = name;
this.employeeID = employeeID;
}
public Employee5(String name, int employeeID, int salary) {
this.name = name;
this.employeeID = employeeID;
this.salary = salary;
}
public String toString() {
return "Name: " + name + ", Employee ID: "
+ employeeID + ", Salary: " + salary;
}
}

View File

@@ -0,0 +1,12 @@
public class Ex5 {
public static void main(String[] args) {
Employee5[] emps = new Employee5[4];
emps[0] = new Employee5("Sam", 111, 30000);
emps[1] = new PartTimer("Ray", 222, 30, 300);
emps[2] = new NewPartTimer("June", 333, 40, 100, 0.05);
emps[3] = new NewPartTimer("May", 444, 100, 100, 0.05);
for (Employee5 employee : emps)
System.out.println(employee);
}
}

View File

@@ -0,0 +1,29 @@
public class NewPartTimer extends PartTimer{
protected int mpf;
protected double mpfRate;
NewPartTimer(String name, int employeeID, int workingHour, int hourlyRate, double mpfRate){
super(name, employeeID, workingHour, hourlyRate);
this.mpfRate = mpfRate;
calculateMpf();
}
protected void calculateMpf(){
if(salary >= 6500){
mpf = (int)(salary * mpfRate);
if(mpf > 1250)
mpf = 1250;
salary = salary - mpf;
}else
mpf = 0;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return super.toString() + ", MPF Rate: " + mpfRate + "%, MPF: " + mpf;
}
}

View File

@@ -0,0 +1,21 @@
public class PartTimer extends Employee5 {
protected int workingHour;
protected int hourlyRate;
PartTimer(String name, int employeeID, int workingHour, int hourlyRate){
super(name, employeeID);
this.workingHour = (workingHour > 220) ? 0: workingHour;
this.hourlyRate = hourlyRate;
calculateSalary();
}
protected void calculateSalary(){
salary = workingHour * hourlyRate;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return super.toString() + ", Salary: " + salary + ", working Hour: " + workingHour + ", Hourly rate: " + hourlyRate;
}
}

Some files were not shown because too many files have changed in this diff Show More