The first one was OOP task.
Here is the description of the task:"Write a class named User. It must have three string fields: login, firstName, lastName and a constructor with three parameters to initialize these fields. The order of parameters in the constructor must be the same as presented bellow. Do not make the fields and the constructor private."
The idea is the participant to train OOP a little bit. How to create a class in Java and how to create a constructor. Here is a short video which demonstrates the task:
Here is how the code looks:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class User { | |
String login; | |
String firstName; | |
String lastName; | |
public User(String login, String firstName, String lastName) { | |
this.login = login; | |
this.firstName = firstName; | |
this.lastName = lastName; | |
} | |
} |
The second task was:
"You want to create a program that models the behavior of cars. For this purpose, you've created a class named Car containing three fields: the int field yearModel, the string field make, and the int field speed. You want to add functionality to your cars, so you need methods. Add the following instance methods to your class: void accelerate() that adds 5 to the speed each time it's called; void brake() that subtracts 5 from the speed field each time it's called, the speed cannot be less than zero. Do not make the fields and methods private."The idea is the participant to train OOP more to creating methods. Here the tricky part was that when the car speed cannot be less than 5 the car must stop. :) Here is a short video which demonstrates the task:
Here is how the code looks:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Car { | |
int yearModel; | |
String make; | |
int speed = 0; | |
public void accelerate() { | |
this.speed += 5; | |
} | |
public void brake() { | |
if (this.speed >= 5) { | |
this.speed -= 5; | |
} else { | |
this.speed = 0; | |
} | |
} | |
} |
The same day I've implemented a task about multidimensional arrays. You must draw an asterisk in console using a matrix - two dimensional array. The task was a bit tricky but very funny:
The star figure Given an odd number n, not exceeding 15. Create a two-dimensional array (matrix) from n×n elements, by filling it with "." symbols (each element of the matrix is a string containing a single symbol). Then fill the middle row of the matrix, the middle column, and the main and the secondary diagonals with the "*" symbols. As a result, all "*"s in the array must form the star figure. Output this matrix; elements of the array should be space separated. Sample Input: 5 Sample Output: * . * . * . * * * . * * * * * . * * * . * . * . *"This is how my implementation looks:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
import java.util.Scanner; | |
class Main { | |
public static void main(String[] args) { | |
Scanner scanner = new Scanner(System.in); | |
int size = scanner.nextInt(); | |
char[][] matrix = new char[size][size]; | |
int center = (int) Math.ceil(size / 2.0) - 1; | |
for (char[] chars : matrix) { | |
Arrays.fill(chars, '.'); | |
} | |
for (int i = 0; i < matrix.length; i++) { | |
for (int j = 0; j < matrix[i].length; j++) { | |
// lines through the center vertically and horizontally | |
if (j == center || i == center) { | |
matrix[i][j] = '*'; | |
} | |
// the diagonal line in the upper left quarter and in the lower right quarter | |
if (j == i) { | |
matrix[i][j] = '*'; | |
} | |
// the diagonal line in the upper right quarter and in the lower left quarter | |
if (j == (matrix.length - 1) - i) { | |
matrix[i][j] = '*'; | |
} | |
} | |
} | |
for (char[] chars : matrix) { | |
StringBuilder line = new StringBuilder(); | |
for (char aChar : chars) { | |
line.append(aChar).append(" "); | |
} | |
System.out.println(line.toString().trim()); | |
} | |
} | |
} |
The third thing which I did was that task:
Given the sequence of integer numbers (which ends with the number 0). Find the largest element of the sequence. The number 0 itself is not included in the sequence but serves only as a sign of the sequence’s end. Sample Input 1: 1 7 9 0 Sample Output 1: 9And this is my code.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
class Main { | |
public static void main(String[] args) { | |
Scanner scanner = new Scanner(System.in); | |
int maximum = 0; | |
int number; | |
for (;(number = scanner.nextInt()) != 0;) { | |
if (number > maximum) { | |
maximum = number; | |
} | |
} | |
System.out.println(maximum); | |
} | |
} |
The fourth:
Declare an enum Currency. It should include the following currency codes (according to ISO 4217): USD — United States dollar EUR — Euro GBP — Pound sterling RUB — Russian ruble UAH — Ukrainian hryvnia KZT — Kazakhstani tenge CAD — Canadian dollar JPY — Japanese yen CNY — Chinese yuan You must include all of the codes presented above and nothing else. The constants in the enum can be declared in any order.This is my code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
enum Currency { | |
USD, | |
EUR, | |
GBP, | |
RUB, | |
UAH, | |
KZT, | |
CAD, | |
JPY, | |
CNY; | |
} |
The fifth:
It was a sipmple question: What name should the class containing the main method have? Of course it can have any name.
The sixth:
It was finishing of Stage 1/5 of the Tic-Tac-Toe project. You can check the whole finished project here in Github.
Description Tic-tac-toe is a game played by two players on a 3x3 field. One of the players plays as 'X', and the other player is 'O'. 'X' plays first, then the 'O' side plays, and so on. The players write 'X' and 'O' on a 3x3 field. The first player that writes 3 'X' or 3 'O' in a straight line (including diagonals) wins. Your first task in this project is to print any state of the field in the console output. Example The example below shows how your output might look. X O X O X O X X OBellow you can check the code of that step:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package tictactoe; | |
public class Main { | |
public static void main(String[] args) { | |
TikTakToeGame game = new TikTakToeGame(); | |
System.out.println(game.getState()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package tictactoe; | |
public class TikTakToeGame { | |
private char[][] state; | |
public TikTakToeGame() { | |
this.state = new char[][]{ | |
{'X', 'O', 'X'}, | |
{'O', 'X', 'O'}, | |
{'X', 'X', 'O'} | |
}; | |
} | |
public String getState() { | |
String out = ""; | |
for (char[] chars : this.state) { | |
StringBuilder row = new StringBuilder(); | |
for (char aChar : chars) { | |
row.append(aChar).append(" "); | |
} | |
out = out + row + "\n"; | |
} | |
return out; | |
} | |
} |
The seventh:
It was finishing of Stage 2/5 of the Tic-Tac-Toe project: The user is the gamemaster
Description In this stage, you should write a program that reads 9 symbols from the input and writes an appropriate 3x3 field. Elements of the field can contain only 'X', 'O' and '_' symbols. Note, that field has a specific format and should start and end with ---------, all lines in between should start and end with '|' symbol and everything in the middle should be separated with a single space. Examples Examples below show how your output should look. Example 1: Enter cells: O_OXXO_XX --------- | O _ O | | X X O | | _ X X | --------- Example 2: Enter cells: OXO__X_OX --------- | O X O | | _ _ X | | _ O X | --------- Example 3: Enter cells: _XO__X___ --------- | _ X O | | _ _ X | | _ _ _ | ---------Bellow you can check the code of that step:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package tictactoe; | |
import java.util.Scanner; | |
public class Main { | |
public static void main(String[] args) { | |
Scanner scanner = new Scanner(System.in).useDelimiter(""); | |
char[][] state = new char[3][3]; | |
int i = 0; | |
int j = 0; | |
int size = state.length - 1; | |
System.out.print("Enter cells: "); | |
while (scanner.hasNext()) { | |
state[i][j] = scanner.next().charAt(0); | |
if (j < size) { | |
j++; | |
} else if ( i < size) { | |
j = 0; | |
i++; | |
} else { | |
break; | |
} | |
} | |
TikTakToeGame game = new TikTakToeGame(state); | |
System.out.println(game.getState()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package tictactoe; | |
public class TikTakToeGame { | |
private char[][] state; | |
public TikTakToeGame(char[][] initialState) { | |
this.state = initialState; | |
} | |
public String getState() { | |
StringBuilder out = new StringBuilder(); | |
out.append("---------\n"); | |
for (char[] chars : this.state) { | |
StringBuilder row = new StringBuilder(); | |
row.append("| "); | |
for (char aChar : chars) { | |
row.append(aChar).append(" "); | |
} | |
row.append("|"); | |
out.append(row).append("\n"); | |
} | |
out.append("---------"); | |
return out.toString(); | |
} | |
} |
The eight:
It was finishing of Stage 3/5 of the Tic-Tac-Toe project: What's up on the field?
Description In this stage, you should analyze a Tic-Tac-Toe field. Note. In this stage either 'X' or 'O' can start the game. After printing the field, you need to find the state in which the game is at the moment. Possible states: "Game not finished" - when no side has a three in a row but the field has empty cells; "Draw" - when no side has a three in a row and the field has no empty cells; "X wins" - when the field has three X in a row; "O wins" - when the field has three O in a row; "Impossible" - when the field has three X in a row as well as three O in a row. Or the field has a lot more X's than O's or vice versa (if the difference is 2 or more, should be 1 or 0). Also, you can use ' ' or '_' to print empty cells - it's up to you. Examples The examples below show outputs for some predefined states. Your program should work in the same way. Example 1: Enter cells: XXXOO__O_ --------- | X X X | | O O _ | | _ O _ | --------- X wins Example 2: Enter cells: XOXOXOXXO --------- | X O X | | O X O | | X X O | --------- X wins Example 3: Enter cells: XOOOXOXXO --------- | X O O | | O X O | | X X O | --------- O wins Example 4: Enter cells: XOXOOXXXO --------- | X O X | | O O X | | X X O | --------- Draw Example 5: Enter cells: XO_OOX_X_ --------- | X O | | O O X | | X | --------- Game not finished Example 6: Enter cells: XO_XO_XOX --------- | X O _ | | X O _ | | X O X | --------- Impossible Example 7: Enter cells: _O_X__X_X --------- | O | | X | | X X | --------- Impossible Example 8: Enter cells: _OOOO_X_X --------- | O O | | O O | | X X | --------- ImpossibleBellow you can check the code of that step:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package tictactoe; | |
import java.util.Scanner; | |
public class Main { | |
public static void main(String[] args) { | |
Scanner scanner = new Scanner(System.in).useDelimiter(""); | |
char[][] state = new char[3][3]; | |
int i = 0; | |
int j = 0; | |
int size = state.length - 1; | |
System.out.print(Messages.ASK.message); | |
while (scanner.hasNext()) { | |
state[i][j] = scanner.next().charAt(0); | |
if (j < size) { | |
j++; | |
} else if ( i < size) { | |
j = 0; | |
i++; | |
} else { | |
break; | |
} | |
} | |
TikTakToeGame game = new TikTakToeGame(state); | |
System.out.println(game.getState()); | |
System.out.println(game.getStatus()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package tictactoe; | |
public class TikTakToeGame { | |
private char[][] state; | |
public TikTakToeGame(char[][] initialState) { | |
this.state = initialState; | |
} | |
public String getState() { | |
StringBuilder out = new StringBuilder(); | |
out.append("---------\n"); | |
for (char[] chars : this.state) { | |
StringBuilder row = new StringBuilder(); | |
row.append("| "); | |
for (char aChar : chars) { | |
row.append(aChar).append(" "); | |
} | |
row.append("|"); | |
out.append(row).append("\n"); | |
} | |
out.append("---------"); | |
return out.toString(); | |
} | |
public String getStatus() { | |
int countOfX = 0; | |
int countOfO = 0; | |
int emptyCount = 0; | |
boolean xWins = false; | |
boolean oWins = false; | |
for (int i = 0; i < this.state.length; i++) { | |
if (i == 0) { | |
boolean equalsFirstDiagonal = this.state[i][0] == this.state[1][1] && | |
this.state[i][0] == this.state[2][2]; | |
boolean equalsSecondDiagonal = this.state[i][2] == this.state[1][1] && | |
this.state[2][0] == this.state[i][2]; | |
if (equalsFirstDiagonal || equalsSecondDiagonal && this.state[i][0] == 'X') { | |
xWins = true; | |
} else if (equalsFirstDiagonal || equalsSecondDiagonal && this.state[i][0] == 'O') { | |
oWins = true; | |
} | |
} | |
boolean equalHorizontal = this.state[i][0] == this.state[i][1] && this.state[i][0] == this.state[i][2]; | |
if (equalHorizontal && this.state[i][0] == 'X') { | |
xWins = true; | |
} else if (equalHorizontal && this.state[i][0] == 'O') { | |
oWins = true; | |
} | |
for (int j = 0; j < this.state[i].length; j++) { | |
String current = String.valueOf(this.state[i][j]); | |
if ("X".equals(current)) { | |
countOfX++; | |
} else if ("O".equals(current)) { | |
countOfO++; | |
} else { | |
emptyCount++; | |
} | |
if (i == 0) { | |
boolean equalVertical = this.state[i][j] == this.state[1][j] && | |
this.state[i][j] == this.state[2][j]; | |
if (equalVertical && "X".equals(current)) { | |
xWins = true; | |
} else if (equalVertical && "O".equals(current)) { | |
oWins = true; | |
} | |
} | |
} | |
} | |
if (oWins && xWins || Math.abs(countOfO - countOfX) >= 2) { | |
return Messages.IMPOSSIBLE.message; | |
} else if (oWins) { | |
return String.format(Messages.WINNER.message, "O"); | |
} else if (xWins) { | |
return String.format(Messages.WINNER.message, "X"); | |
} else if (emptyCount == 0) { | |
return Messages.DRAW.message; | |
} else { | |
return Messages.NOT_FINISHED.message; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package tictactoe; | |
public enum Messages { | |
ASK("Enter cells: "), | |
NOT_FINISHED("Game not finished"), | |
DRAW("Draw"), | |
WINNER("%s wins"), | |
IMPOSSIBLE("Impossible"); | |
String message; | |
Messages(String message) { | |
this.message = message; | |
} | |
} |
The ninth was the project of the day.
Write a program that reads an array of lowercase strings and checks whether the array is in alphabetical order or not. There are some rules to compare a pair of strings a and b: First chars of strings are compared: a[0] and b[0]. If a[0] comes earlier than b[0] in the alphabet, then a comes before b in terms of alphabetical order. If the first chars are the same, then the second chars are compared, and so on. If a position is reached where one string has no more chars to compare while the other does, then the shorter string is deemed to come first in alphabetical order. Finally, identical strings are always in alphabetical order. You can use compareTo method of the String class to compare 2 strings. If this String object alphabetically precedes the argument string, then the result is a negative integer. The result is a positive integer if this String object alphabetically follows the argument string. The result is zero if the strings are identical. This is exactly what you need to compare 2 strings in terms of alphabetical order! For example System.out.println("abc".compareTo("acd")); // -1 "abc" < "acd" System.out.println("abc".compareTo("aac")); // 1 "abc" > "aac" System.out.println("abc".compareTo("abc")); // 0 "abc" = "abc" Input data format The single input line contains lowercase strings separated by spaces. Output data format Only a single word: true or false. Report a typo Sample Input 1: a b c Sample Output 1: true Sample Input 2: a aa az aza Sample Output 2: trueBellow you can check the code of that step:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
class Main { | |
public static void main(String[] args) { | |
Scanner scanner = new Scanner(System.in); | |
String[] input = scanner.nextLine().split("\\s+", 0); | |
boolean result = true; | |
for (int i = 0; i < input.length - 1; i++) { | |
String first = input[i]; | |
String second = input[i + 1]; | |
if (second.compareTo(first) < 0) { | |
result = false; | |
break; | |
} | |
} | |
System.out.println(result); | |
} | |
} |
The tenth was the daily step:
Here is the method named getNumberOfMaxParam that takes three integer numbers and returns the position of the first maximum in the order of the method parameters. The method should return number 1, 2 or 3 respectively. Write just a body of the method. Report a typo Sample Input 1: 12 3 12 Sample Output 1: 1Here you can see my code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
public class Main { | |
public static int getNumberOfMaxParam(int a, int b, int c) { | |
if (a >= b && a >= c) { | |
return 1; | |
} | |
if (b >= a && b >= c) { | |
return 2; | |
} | |
return 3; | |
} | |
public static void main(String[] args) { | |
Scanner scanner = new Scanner(System.in); | |
final int a = scanner.nextInt(); | |
final int b = scanner.nextInt(); | |
final int c = scanner.nextInt(); | |
System.out.println(getNumberOfMaxParam(a, b, c)); | |
} | |
} |
The eleventh was the daily step:
Shape Switch statement Write a program, which reads the number of the shape (1 – square, 2 – circle, 3 – triangle, 4 – rhombus) and prints the text "You have chosen a square" (or circle, or triangle, or rhombus, depending on the number). If it is a number that doesn't correspond to any of the listed shapes, the program should output: "There is no such shape!". Note: output text should exactly match the sample, including letters' case and location of spaces. Report a typo Sample Input 1: 1 Sample Output 1: You have chosen a squareHere you can see my code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
class Main { | |
public static void main(String[] args) { | |
Scanner scanner = new Scanner(System.in); | |
int shape = scanner.nextInt(); | |
String message; | |
switch (shape) { | |
case 1: | |
message = "You have chosen a square"; | |
break; | |
case 2: | |
message = "You have chosen a circle"; | |
break; | |
case 3: | |
message = "You have chosen a triangle"; | |
break; | |
case 4: | |
message = "You have chosen a rhombus"; | |
break; | |
default: | |
message = "There is no such shape!"; | |
break; | |
} | |
System.out.println(message); | |
} | |
} |
The twelfth was a daily step:
Given a sequence of natural numbers, not exceeding 30000. Find the maximum element divisible by 4. As input, the program gets the number of elements in the sequence, and then the elements themselves. In the sequence, there is always an element divisible by 4. The number of elements does not exceed 1000. The program should print a single number: the maximum element of the sequence divisible by 4. Try to solve this problem by using a while-loop. Report a typo Sample Input 1: 10 76 18 69 63 36 18 49 16 12 50 Sample Output 1: 76Here you can see my code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
class Main { | |
public static void main(String[] args) { | |
Scanner scanner = new Scanner(System.in); | |
int max = 0; | |
while (scanner.hasNextInt()) { | |
int input = scanner.nextInt(); | |
if (input % 4 == 0 && input > max) { | |
max = input; | |
} | |
} | |
System.out.println(max); | |
} | |
} |
The thirteenth was a daily step:
The cinema has n rows, each row consists of m seats (n and m do not exceed 20). The two-dimensional matrix stores the information on the sold tickets, number 1 means that the ticket for this place is already sold, the number 0 means that the place is available. You want to buy k tickets to the neighboring seats in the same row. Find whether it can be done. Input data format On the input, the program gets the number of n rows and m seats. Then, there are n lines, each containing m numbers (0 or 1) separated by spaces. The last line contains a number k. Output data format The program should output the number of the row with k consecutive available seats. If there are several rows with k available seats, output the first row with these seats. If there is no such a row, output the number 0. Report a typo Sample Input 1: 3 4 0 1 0 1 1 1 0 1 1 0 0 1 2 Sample Output 1: 3 Sample Input 2: 3 3 0 1 0 1 0 0 1 1 1 3 Sample Output 2: 0You can see my code here:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
class Main { | |
public static void main(String[] args) { | |
Scanner scanner = new Scanner(System.in); | |
int externalSize = scanner.nextInt(); | |
int internalSize = scanner.nextInt(); | |
int[][] matrix = new int[externalSize][internalSize]; | |
for (int i = 0; i < matrix.length; i++) { | |
for (int j = 0; j < matrix[i].length; j++) { | |
matrix[i][j] = scanner.nextInt(); | |
} | |
} | |
int tickets = scanner.nextInt(); | |
int row = 0; | |
int maximum = 0; | |
for (int i = 0; i < matrix.length; i++) { | |
int rowMax = 0; | |
for (int j = 0; maximum == 0 && j < matrix[i].length; j++) { | |
if (matrix[i][j] == 0) { | |
rowMax++; | |
} else { | |
rowMax = 0; | |
} | |
if (rowMax >= tickets) { | |
row = i; | |
maximum = rowMax; | |
break; | |
} | |
} | |
} | |
int result = maximum == 0 ? 0 : ++row; | |
System.out.println(result); | |
} | |
} |
The fourteenth was a daily step:
Write a program that reads a sequence of integer numbers in a loop and adds up all numbers. If a new number is equal to 0, the program must stop the loop and output the accumulated sum. When the sum is equal or exceeded 1000 (the barrier), the program should also stop and output the value equal to sum – 1000. Note, the input can contain extra numbers. Just ignore them. Report a typo Sample Input 1: 800 101 102 300 0 Sample Output 1: 3 Sample Input 2: 103 105 109 0 1000 Sample Output 2: 317Here you can check my implementation:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
class Main { | |
public static void main(String[] args) { | |
Scanner scanner = new Scanner(System.in); | |
int sum = 0; | |
int num; | |
boolean barrier = false; | |
while (!barrier) { | |
num = scanner.nextInt(); | |
sum += num; | |
barrier = sum >= 1000; | |
if (barrier) { | |
sum -= 1000; | |
} else if (num == 0) { | |
break; | |
} | |
} | |
System.out.println(sum); | |
} | |
} |
The fifteenth was completing of a stage for the Tic-Tac-Toe project.
Stage 4/5: First move!Description Now you need to implement player's moves. Suppose the bottom left cell has the coordinates (1, 1) and the top right cell has the coordinates (3, 3) like in this table: (1, 3) (2, 3) (3, 3) (1, 2) (2, 2) (3, 2) (1, 1) (2, 1) (3, 1) The program should work in the following way: Get the 3x3 field from the input as in the previous stages, Output this 3x3 field with cells before the user's move, Then ask the user about his next move, Then the user should input 2 numbers that represent the cell on which user wants to make his X or O. (9 symbols representing the field would be on the first line and these 2 numbers would be on the second line of the user input), Then output the table including the user's most recent move. Do not delete code that checks for table state; it will be useful in the future. Note that in this stage user moves as X, not O. Keep in mind that the first coordinate goes from left to right and the second coordinate goes from bottom to top. Also, notice that coordinates start with 1 and can be 1, 2 or 3. But what if the user enters incorrect coordinates? The user could enter symbols instead of numbers or enter coordinates representing occupied cells. You need to prevent all of that by checking user's input and catching possible exceptions. The program should also check user input. If the user input is unsuitable, the program should ask him to enter coordinates again. So, you need to output a field from the first line of the input and then ask the user to enter a move. Keep asking until the user enters coordinates that represent an empty cell on the field and after that output the field with that move. You should output the field only 2 times: before the move and after a legal move. Examples The examples below show how your program should work. Example 1: Enter cells: X_X_O____ --------- | X X | | O | | | --------- Enter the coordinates: 1 1 --------- | X X | | O | | X | --------- Example 2: Enter cells: _XXOO_OX_ --------- | X X | | O O | | O X | --------- Enter the coordinates: 1 3 --------- | X X X | | O O | | O X | --------- Example 3: Enter cells: _XXOO_OX_ --------- | X X | | O O | | O X | --------- Enter the coordinates: 3 1 --------- | X X | | O O | | O X X | --------- Example 4: Enter cells: _XXOO_OX_ --------- | X X | | O O | | O X | --------- Enter the coordinates: 3 2 --------- | X X | | O O X | | O X | --------- Example 5: Enter cells: _XXOO_OX_ --------- | X X | | O O | | O X | --------- Enter the coordinates: 1 1 This cell is occupied! Choose another one! Enter the coordinates: 1 3 --------- | X X X | | O O | | O X | --------- Example 6: Enter cells: _XXOO_OX_ --------- | X X | | O O | | O X | --------- Enter the coordinates: one You should enter numbers! Enter the coordinates: one three You should enter numbers! Enter the coordinates: 1 3 --------- | X X X | | O O | | O X | --------- Example 7: Enter cells: _XXOO_OX_ --------- | X X | | O O | | O X | --------- Enter the coordinates: 4 1 Coordinates should be from 1 to 3! Enter the coordinates: 1 4 Coordinates should be from 1 to 3! Enter the coordinates: 1 3 --------- | X X X | | O O | | O X | ---------You can check my code below:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package tictactoe; | |
import java.util.Scanner; | |
public class Main { | |
public static void main(String[] args) { | |
Scanner scanner = new Scanner(System.in).useDelimiter(""); | |
char[][] state = new char[3][3]; | |
int i = 0; | |
int j = 0; | |
int size = state.length - 1; | |
System.out.print(Messages.ASK.message); | |
while (true) { | |
state[i][j] = scanner.next().charAt(0); | |
if (j < size) { | |
j++; | |
} else if ( i < size) { | |
j = 0; | |
i++; | |
} else { | |
break; | |
} | |
} | |
scanner.reset(); | |
scanner.nextLine(); | |
TikTakToeGame game = new TikTakToeGame(state); | |
System.out.println(game.getState()); | |
boolean result; | |
System.out.print(Messages.ASK_COORDINATES.message); | |
do { | |
String input = scanner.nextLine(); | |
result = game.validateUserInput(input); | |
} while (!result); | |
game.updateCoordinates('X'); | |
System.out.println(game.getState()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package tictactoe; | |
public enum Messages { | |
ASK("Enter cells: "), | |
ASK_COORDINATES("Enter the coordinates: "), | |
ERROR_ONLY_NUMBERS("You should enter numbers!"), | |
ERROR_INCORRECT_RANGE("Coordinates should be from 1 to 3!"), | |
ERROR_OCCUPIED_CELL("This cell is occupied! Choose another one!"), | |
NOT_FINISHED("Game not finished"), | |
DRAW("Draw"), | |
WINNER("%s wins"), | |
IMPOSSIBLE("Impossible"); | |
String message; | |
Messages(String message) { | |
this.message = message; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package tictactoe; | |
import java.util.Scanner; | |
public class TikTakToeGame { | |
private char[][] state; | |
private int column; | |
private int row; | |
public TikTakToeGame(char[][] initialState) { | |
this.state = initialState; | |
} | |
private void showErrorMessage(Messages message) { | |
System.out.printf(message.message + "%n" + Messages.ASK_COORDINATES.message); | |
} | |
public boolean validateUserInput(String input) { | |
Scanner scanner = new Scanner(input).useDelimiter(" "); | |
int column; | |
int row; | |
if (scanner.hasNextInt()) { | |
row = scanner.nextInt(); | |
} else { | |
this.showErrorMessage(Messages.ERROR_ONLY_NUMBERS); | |
return false; | |
} | |
if (scanner.hasNextInt()) { | |
column = scanner.nextInt(); | |
} else { | |
this.showErrorMessage(Messages.ERROR_ONLY_NUMBERS); | |
return false; | |
} | |
if (!(1 <= column && column <= 3)) { | |
this.showErrorMessage(Messages.ERROR_INCORRECT_RANGE); | |
return false; | |
} | |
if (!(1 <= row && row <= 3)) { | |
this.showErrorMessage(Messages.ERROR_INCORRECT_RANGE); | |
return false; | |
} | |
int[] coords = this.convertIndexes(column, row); | |
if (this.state[coords[0]][coords[1]] != '_') { | |
this.showErrorMessage(Messages.ERROR_OCCUPIED_CELL); | |
return false; | |
} | |
this.row = coords[0]; | |
this.column = coords[1]; | |
return true; | |
} | |
protected void updateCoordinates(char sign) { | |
this.state[this.row][this.column] = sign; | |
} | |
protected int[] convertIndexes(int column, int row) { | |
int[][][] map = { | |
{}, | |
{{0}, {2, 0}, {1, 0}, {0, 0}}, | |
{{0}, {2, 1}, {1, 1}, {0, 1}}, | |
{{0}, {2, 2}, {1, 2}, {0, 2}} | |
}; | |
return map[row][column]; | |
} | |
public String getState() { | |
StringBuilder out = new StringBuilder(); | |
out.append("---------\n"); | |
for (char[] chars : this.state) { | |
StringBuilder row = new StringBuilder(); | |
row.append("| "); | |
for (char aChar : chars) { | |
row.append(aChar).append(" "); | |
} | |
row.append("|"); | |
out.append(row).append("\n"); | |
} | |
out.append("---------"); | |
return out.toString(); | |
} | |
public String getStatus() { | |
int countOfX = 0; | |
int countOfO = 0; | |
int emptyCount = 0; | |
boolean xWins = false; | |
boolean oWins = false; | |
for (int i = 0; i < this.state.length; i++) { | |
if (i == 0) { | |
boolean equalsFirstDiagonal = this.state[i][0] == this.state[1][1] && | |
this.state[i][0] == this.state[2][2]; | |
boolean equalsSecondDiagonal = this.state[i][2] == this.state[1][1] && | |
this.state[2][0] == this.state[i][2]; | |
if (equalsFirstDiagonal || equalsSecondDiagonal && this.state[i][0] == 'X') { | |
xWins = true; | |
} else if (equalsFirstDiagonal || equalsSecondDiagonal && this.state[i][0] == 'O') { | |
oWins = true; | |
} | |
} | |
boolean equalHorizontal = this.state[i][0] == this.state[i][1] && this.state[i][0] == this.state[i][2]; | |
if (equalHorizontal && this.state[i][0] == 'X') { | |
xWins = true; | |
} else if (equalHorizontal && this.state[i][0] == 'O') { | |
oWins = true; | |
} | |
for (int j = 0; j < this.state[i].length; j++) { | |
String current = String.valueOf(this.state[i][j]); | |
if ("X".equals(current)) { | |
countOfX++; | |
} else if ("O".equals(current)) { | |
countOfO++; | |
} else { | |
emptyCount++; | |
} | |
if (i == 0) { | |
boolean equalVertical = this.state[i][j] == this.state[1][j] && | |
this.state[i][j] == this.state[2][j]; | |
if (equalVertical && "X".equals(current)) { | |
xWins = true; | |
} else if (equalVertical && "O".equals(current)) { | |
oWins = true; | |
} | |
} | |
} | |
} | |
if (oWins && xWins || Math.abs(countOfO - countOfX) >= 2) { | |
return Messages.IMPOSSIBLE.message; | |
} else if (oWins) { | |
return String.format(Messages.WINNER.message, "O"); | |
} else if (xWins) { | |
return String.format(Messages.WINNER.message, "X"); | |
} else if (emptyCount == 0) { | |
return Messages.DRAW.message; | |
} else { | |
return Messages.NOT_FINISHED.message; | |
} | |
} | |
} |
The sixteenth was completing the last stage of Tic-Tac-Toe project:
Description Now it is time to make a working game! In the last stage, make it so you can play a full game with a friend. First one of you moves as X, and then the other one moves as O. You need to create a game loop. The game starts with empty cells and ends when someone wins or there is a draw. You need to output the final result after the end of the game. Good luck gaming! Example The example below shows how your program should work. --------- | | | | | | --------- Enter the coordinates: 2 2 --------- | | | X | | | --------- Enter the coordinates: 2 2 This cell is occupied! Choose another one! Enter the coordinates: two two You should enter numbers! Enter the coordinates: 1 4 Coordinates should be from 1 to 3! Enter the coordinates: 1 3 --------- | O | | X | | | --------- Enter the coordinates: 3 1 --------- | O | | X | | X | --------- Enter the coordinates: 1 2 --------- | O | | O X | | X | --------- Enter the coordinates: 1 1 --------- | O | | O X | | X X | --------- Enter the coordinates: 3 2 --------- | O | | O X O | | X X | --------- Enter the coordinates: 2 1 --------- | O | | O X O | | X X X | --------- X winsYou can see my implementation below:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package tictactoe; | |
import java.util.Scanner; | |
public class Main { | |
public static void main(String[] args) { | |
Scanner scanner = new Scanner(System.in); | |
TikTakToeGame game = new TikTakToeGame(); | |
System.out.println(game.getState()); | |
System.out.print(Messages.ASK_COORDINATES.message); | |
while (true) { | |
boolean result; | |
do { | |
String input = scanner.nextLine(); | |
result = game.validateUserInput(input); | |
} while (!result); | |
game.updateCoordinates(); | |
System.out.println(game.getState()); | |
if (game.getResult() != Messages.NOT_FINISHED) { | |
break; | |
} | |
System.out.print(Messages.ASK_COORDINATES.message); | |
} | |
System.out.println(game.getStatusAsString()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package tictactoe; | |
public enum Messages { | |
ASK_COORDINATES("Enter the coordinates: "), | |
ERROR_ONLY_NUMBERS("You should enter numbers!"), | |
ERROR_INCORRECT_RANGE("Coordinates should be from 1 to 3!"), | |
ERROR_OCCUPIED_CELL("This cell is occupied! Choose another one!"), | |
NOT_FINISHED("Game not finished"), | |
DRAW("Draw"), | |
WINNER_X("X wins"), | |
WINNER_O("O wins"), | |
IMPOSSIBLE("Impossible"); | |
String message; | |
Messages(String message) { | |
this.message = message; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package tictactoe; | |
import java.util.Scanner; | |
public class TikTakToeGame { | |
private final char[][] state = { | |
{'_', '_', '_'}, | |
{'_', '_', '_'}, | |
{'_', '_', '_'} | |
}; | |
private int column; | |
private int row; | |
private Messages result = Messages.NOT_FINISHED; | |
private char activePlayer = 'X'; | |
private void showErrorMessage(Messages message) { | |
System.out.printf(message.message + "%n" + Messages.ASK_COORDINATES.message); | |
} | |
public boolean validateUserInput(String input) { | |
Scanner scanner = new Scanner(input).useDelimiter(" "); | |
int column; | |
int row; | |
if (scanner.hasNextInt()) { | |
row = scanner.nextInt(); | |
} else { | |
this.showErrorMessage(Messages.ERROR_ONLY_NUMBERS); | |
return false; | |
} | |
if (scanner.hasNextInt()) { | |
column = scanner.nextInt(); | |
} else { | |
this.showErrorMessage(Messages.ERROR_ONLY_NUMBERS); | |
return false; | |
} | |
if (!(1 <= column && column <= 3)) { | |
this.showErrorMessage(Messages.ERROR_INCORRECT_RANGE); | |
return false; | |
} | |
if (!(1 <= row && row <= 3)) { | |
this.showErrorMessage(Messages.ERROR_INCORRECT_RANGE); | |
return false; | |
} | |
int[] coords = this.convertIndexes(column, row); | |
if (this.state[coords[0]][coords[1]] != '_') { | |
this.showErrorMessage(Messages.ERROR_OCCUPIED_CELL); | |
return false; | |
} | |
this.row = coords[0]; | |
this.column = coords[1]; | |
return true; | |
} | |
protected void updateCoordinates() { | |
this.state[this.row][this.column] = this.activePlayer; | |
this.updateStatus(); | |
this.activePlayer = this.activePlayer == 'X' ? 'O' : 'X'; | |
} | |
protected int[] convertIndexes(int column, int row) { | |
int[][][] map = { | |
{}, | |
{{0}, {2, 0}, {1, 0}, {0, 0}}, | |
{{0}, {2, 1}, {1, 1}, {0, 1}}, | |
{{0}, {2, 2}, {1, 2}, {0, 2}} | |
}; | |
return map[row][column]; | |
} | |
public String getState() { | |
StringBuilder out = new StringBuilder(); | |
out.append("---------\n"); | |
for (char[] chars : this.state) { | |
StringBuilder row = new StringBuilder(); | |
row.append("| "); | |
for (char aChar : chars) { | |
row.append(aChar).append(" "); | |
} | |
row.append("|"); | |
out.append(row).append("\n"); | |
} | |
out.append("---------"); | |
return out.toString(); | |
} | |
public Messages getResult() { | |
return this.result; | |
} | |
private void updateStatus() { | |
int countOfX = 0; | |
int countOfO = 0; | |
int emptyCount = 0; | |
boolean xWins = false; | |
boolean oWins = false; | |
for (int i = 0; i < this.state.length; i++) { | |
if (i == 0) { | |
boolean equalsFirstDiagonal = this.state[i][0] == this.state[1][1] && | |
this.state[i][0] == this.state[2][2]; | |
boolean equalsSecondDiagonal = this.state[i][2] == this.state[1][1] && | |
this.state[2][0] == this.state[i][2]; | |
if ((equalsFirstDiagonal || equalsSecondDiagonal) && this.state[1][1] == 'X') { | |
xWins = true; | |
} else if ((equalsFirstDiagonal || equalsSecondDiagonal) && this.state[1][1] == 'O') { | |
oWins = true; | |
} | |
} | |
boolean equalHorizontal = this.state[i][0] == this.state[i][1] && this.state[i][0] == this.state[i][2]; | |
if (equalHorizontal && this.state[i][0] == 'X') { | |
xWins = true; | |
} else if (equalHorizontal && this.state[i][0] == 'O') { | |
oWins = true; | |
} | |
for (int j = 0; j < this.state[i].length; j++) { | |
char current = this.state[i][j]; | |
if ('X' == current) { | |
countOfX++; | |
} else if ('O' == current) { | |
countOfO++; | |
} else { | |
emptyCount++; | |
} | |
if (i == 0) { | |
boolean equalVertical = this.state[i][j] == this.state[1][j] && | |
this.state[i][j] == this.state[2][j]; | |
if (equalVertical && 'X' == current) { | |
xWins = true; | |
} else if (equalVertical && 'O' == current) { | |
oWins = true; | |
} | |
} | |
} | |
} | |
if (oWins && xWins || Math.abs(countOfO - countOfX) >= 2) { | |
this.result = Messages.IMPOSSIBLE; | |
} else if (oWins) { | |
this.result = Messages.WINNER_O; | |
} else if (xWins) { | |
this.result = Messages.WINNER_X; | |
} else if (emptyCount == 0) { | |
this.result = Messages.DRAW; | |
} else { | |
this.result = Messages.NOT_FINISHED; | |
} | |
} | |
public String getStatusAsString() { | |
return this.result.message; | |
} | |
} |
The seventeenth was completing the Tic-Tac-Toe project and publishing it to Github.
Тhe eighteenth was completing a daily step:
You are creating a calculator that manipulates complex numbers. Write a class named Complex. It must have two double fields named real and imaginary.Below you can check my code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Complex { | |
double real; | |
double imaginary; | |
} |