How I can print the printBoard with modification? - java

I write a TicTacToe game.
Here I create a 3x3 table with char [][] board, then call method printBoard(). I input for example X_X_O____, and print this table with these characters.
In the changeBoard() method I want to input coordinates of board[][] and if there is char _ this will be replaced with X. I give the coordinates at compile to see that the coordinate is _ but when call method printBoard(), the console prints the same board without any changes. Can you please help me as I don't know what I am doing wrong?
import java.util.Scanner;
public class TicTacToe {
private char[][] board = new char[3][3];
private String state;
private int n;
private int m;
private int i;
private int j;
Scanner sc = new Scanner(System.in);
public TicTacToe() {
System.out.print("Enter cells: ");
this.state = sc.nextLine();
}
public void printBoard() {
int nextChar = 0;
System.out.println("---------");
for (i = 0; i < 3; i++) {
System.out.print("| ");
for (j = 0; j < 3; j++) {
board[i][j] = state.charAt(nextChar++);
System.out.print(board[i][j] + " ");
}
System.out.println("|");
}
System.out.println("---------");
}
public void changeBoard() {
while (true) {
System.out.print("Enter the coordinates: ");
n = sc.nextInt();
m = sc.nextInt();
if (n < 1 || n > 3 || m < 1 || m > 3) {
System.out.println("Coordinates should be from 1 to 3!");
} else {
int x = n - 1;
int y = m - 1;
this.i = x;
this.j = y;
if (board[i][j] == '_') {
this.board[i][j] = 'X';
break;
} else {
System.out.println("This cell is occupied! Choose another one!");
}
}
}
// printBoard();
}
}

Why you use fields for your n, m, i, j? If you remove it, code will be cleaner.
Also, you change your board in changeBoard, but then in line board[i][j] = state.charAt(nextChar++); you erase your changes. You can move this from printBoard to constructor.
I think want to write something like this
class TicTacToe {
private char[][] board = new char[3][3];
Scanner sc = new Scanner(System.in);
public TicTacToe() {
int nextChar = 0;
System.out.print("Enter cells: ");
String state = sc.nextLine();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = state.charAt(nextChar++);
}
}
}
public void printBoard() {
System.out.println("---------");
for (int i = 0; i < 3; i++) {
System.out.print("| ");
for (int j = 0; j < 3; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println("|");
}
System.out.println("---------");
}
public void changeBoard() {
while (true) {
System.out.print("Enter the coordinates: ");
int n = sc.nextInt();
int m = sc.nextInt();
if (n < 1 || n > 3 || m < 1 || m > 3) {
System.out.println("Coordinates should be from 1 to 3!");
} else {
int x = n - 1;
int y = m - 1;
if (board[x][y] == '_') {
this.board[x][y] = 'X';
break;
} else {
System.out.println("This cell is occupied! Choose another one!");
}
}
}
printBoard();
}
}

Related

Rhombus with letters - Java

I am new to programming and started with learning c# and now java. I came across a task creating a rhombus where the user inputs the height (odd numbers only) and the char for the rhombus.
I created a for loop for the height and another loop for the characters. Here is my output:
h: 7
c: k
k
jkj
ijkji
hijkjih
ghijkjihg
But I want the output to be:
h: 7
c: k
k
jkj
ijkji
hijkjih
ijkji
jkj
k
How can I develop my logic to apply it to my code.
Here is my code:
Scanner in = new Scanner(System.in);
System.out.print("h: ");
int h = in.nextInt();
System.out.print("c: ");
char c = in.next().charAt(0);
if(h%2==0){
System.out.println("Invalid number!");
return;
}
int count = 1;
int space = 1;
for (int i = 2; i < h; i++)
{
for (int spc = h - space; spc > 0; spc--)
{
System.out.print(" ");
}
if (i < h)
{
space++;
}
else {
space--;
}
for (int j = 0; j < count; j++)
{
System.out.print(c);
if (j < count/2)
{
c++;
}
else {
c--;
}
}
if (i < h)
{
count = count + 2;
}
else {
count = count - 2;
}
System.out.println();
}
Any help is highly appreciated.
Your code contains the following flaws:
count and space variables depend on the values of i and h, which makes it very hard to keep track of and understand. You should avoid hidden dependencies in your code in general
you change the value of c all the time. It makes it very hard to keep track of. You should never change its value
your function is too big
strange values like i = 2, count/2, incrementing by 2
incorrect conditions
You have one loop which increments i. What you need is a second loop which decrements the value of i. And you should also use the same approach for printing of the characters (2 loops for both sides). Let me show you:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// load parameters
System.out.print("h: ");
int h = in.nextInt();
System.out.print("c: ");
char c = in.next().charAt(0);
// validate parameters
if (h % 2 == 0) {
System.out.println("Invalid number!");
return;
}
for(int i = 0; i <= h/2; i++) {
printSpaces((h+1) / 2 - i - 1);
printLine(c, i);
System.out.println();
}
for(int i = h/2-1; i >= 0; i--) {
printSpaces((h+1) / 2 - i - 1);
printLine(c, i);
System.out.println();
}
}
private static void printLine(char character, int sideWidth) {
for (int j = sideWidth; j >= 0; j--)
System.out.print((char) (character - j));
for (int j = 1; j <= sideWidth; j++)
System.out.print((char) (character - j));
}
private static void printSpaces(int numberOfSpaces) {
for (int i = 0; i < numberOfSpaces; i++) {
System.out.print(" ");
}
}
which gives you the desired output.
public class Rhombusstar
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter N : ");
int n=sc.nextInt();
System.out.print("Enter Symbol : ");
char c = sc.next().charAt(0);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n-i;j++)
{
System.out.print(" ");
}
for(int j=1;j<=n;j++)
{
System.out.print(c);
}
System.out.println();
}
}
}

Extra line printed by bubble sort code

Writing a bubble sort algorithm in java for school and randomly getting an extra line printed to the screen, and I can't figure out why it is doing this. Here is my code.Code result here
import java.util.Scanner;
public class Assignment7 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter the # of numbers to be sorted: ");
int number = input.nextInt();
System.out.print("Enter 1 for ints or 2 for doubles: ");
int intdou = input.nextInt();
if (intdou == 1) {
int x = 0;
int[] num = new int[number];
for (int q = 0; q < number; q++) {
System.out.print("Enter number: ");
num[q] = input.nextInt();
}
for (int w = 0; w < number; w++) {
for (int e = 1; e < (number - w); e++) {
if (num[e - 1] > num[e]) {
x = num[e - 1];
num[e - 1] = num[e];
num[e] = x;
for (int r = 0; r < number; r++) {
System.out.print(num[r] + ", ");
}
}
System.out.print("\n");
}
}
} else if (intdou == 2) {
double x = 0;
double[] num = new double[number];
for (int q = 0; q < number; q++) {
System.out.print("Enter number: ");
num[q] = input.nextInt();
}
for (int w = 0; w < number; w++) {
for (int e = 1; e < (number - w); e++) {
if (num[e - 1] > num[e]) {
x = num[e - 1];
num[e - 1] = num[e];
num[e] = x;
for (int r = 0; r < number; r++) {
System.out.print(num[r] + ", ");
}
}
System.out.print("\n");
}
}
}
}
}
Do you mean the extra blank line? Just move "System.out.print("\n");" inside the if block.

How to make a trust for the last christmas tree?

public class Xmas{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("program.");
System.out.print("Height: ");
int n = sc.nextInt();
if (n <= 0) {
System.out.println("Height can only be positive.");
}
else {
System.out.print("Levels: ");
int sz = sc.nextInt();
if (sz <= 0) {
System.out.println("Levels can only be positive.");
}
else
for (int s = 0; s < sz; s++) {
for(int i=0; i<n; i++) {
for(int j=0; j<n-i-1; j++) {
System.out.print(" ");
}
for(int k=0; k<=2*i; k++) {
System.out.print("*");
}
System.out.println();
}
}
}
}
}
I need this for the last tree:
I have to do a 3*3 strut in the middle of the tree.
*
***
*****
*******
*********
***
***
***
I have no idea how to do that.
please help me and give me a code! Thanks!
The code below is maybe that what you are searching for. The additional loop prints the asterisks depending on the height. Three lines with 3 asterisks.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("program.");
System.out.print("Height: ");
int n = sc.nextInt();
if (n <= 0) {
System.out.println("Height can only be positive.");
} else {
System.out.print("Levels: ");
int sz = sc.nextInt();
if (sz <= 0) {
System.out.println("Levels can only be positive.");
} else {
for (int s = 0; s < sz; s++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - i - 1; j++) {
System.out.print(" ");
}
for (int k = 0; k <= 2 * i; k++) {
System.out.print("*");
}
System.out.println();
}
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < n - 1; j++) {
if (j == n - 2) {
System.out.println("***");
continue;
}
System.out.print(" ");
}
}
}
}
}

Java Program to display the amount of connected compoments in an Undirected Graph using DFS and an adjacency matrix provided by user

As the title says I need to create a Java program that will calculate how many connected components are within an undirected graph, using the adjacency matrix provided by the user. I have spend many hours and managed to successfully get the adjacency matrix and calculate how many vertices are not connected to my "source" vertex. However, I can't wrap it up and count the connected components. It's just too hard for me. Please help, thanks . This is the current state of my code:
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Stack;
import java.util.Arrays;
public class UndirectedConnectivityDfs
{
private Stack<Integer> stack;
public UndirectedConnectivityDfs()
{
stack = new Stack<Integer>();
}
public void dfs(int adjacency_matrix[][], int source)
{
int number_of_nodes = adjacency_matrix[source].length - 1;
int visited[] = new int[number_of_nodes + 1];
visited[0]=1;
int element = source;
int i = source;
int cc=1;
for (int k = 1; k <= number_of_nodes; k++){
if (visited[k] == 0)
{
visited[source] = 1;
stack.push(source);
while (!stack.isEmpty())
{
element = stack.peek();
i = element;
while (i <= number_of_nodes)
{
if (adjacency_matrix[element][i] == 1 && visited[i] == 0)
{
stack.push(i);
visited[i] = 1;
element = i;
i = 1;
continue;
}
i++;
}
stack.pop();
}
boolean connected = false;
for (int vertex = 1; vertex <= number_of_nodes; vertex++)
{
if (visited[vertex] == 1)
{
connected = true;
} else
{
connected = false;
}
}
}else
{
System.out.print("There are ");
System.out.print(cc);
System.out.println(" connected compoments");
}
}
}
public static void main(String...arg)
{
int number_of_nodes, source;
Scanner scanner = null;
try
{
System.out.println("Enter the number of nodes in the graph");
scanner = new Scanner(System.in);
number_of_nodes = scanner.nextInt();
int adjacency_matrix[][] = new int[number_of_nodes + 1][number_of_nodes + 1];
System.out.println("Enter the adjacency matrix");
for (int i = 1; i <= number_of_nodes; i++)
for (int j = 1; j <= number_of_nodes; j++)
adjacency_matrix[i][j] = scanner.nextInt();
for (int i = 1; i <= number_of_nodes; i++)
{
for (int j = 1; j <= number_of_nodes; j++)
{
if (adjacency_matrix[i][j] == 1 && adjacency_matrix[j][i] == 0)
{
adjacency_matrix[j][i] = 1;
}
}
}
System.out.println("Enter the source for the graph");
source = scanner.nextInt();
UndirectedConnectivityDfs undirectedConnectivity= new UndirectedConnectivityDfs();
undirectedConnectivity.dfs(adjacency_matrix, source);
}catch(InputMismatchException inputMismatch)
{
System.out.println("Wrong Input format");
}
scanner.close();
}
}
Your solution is almost done. You had to adjust the variables' scope to be within the for loop that checks the visited array. Also you have to use indexes that start from 0 because u can cause an ArrayIndexOutOfBoundsException. Also you do not have to give source as input.
Here is the fixed code:
public class UndirectedConnectivityDfs
{
private Stack<Integer> stack;
public UndirectedConnectivityDfs()
{
stack = new Stack<Integer>();
}
public void dfs(int adjacency_matrix[][])
{
int number_of_nodes = adjacency_matrix[0].length;
int visited[] = new int[number_of_nodes];
int cc = 0;
for (int vertex = 0; vertex < number_of_nodes; vertex++)
{
if (visited[vertex] == 0)
{
int element = vertex;
int i = vertex;
visited[vertex] = 1;
cc++;
stack.push(vertex);
while (!stack.isEmpty())
{
element = stack.peek();
i = element;
while (i < number_of_nodes)
{
if (adjacency_matrix[element][i] == 1 && visited[i] == 0)
{
stack.push(i);
visited[i] = 1;
element = i;
i = 1;
continue;
}
i++;
}
stack.pop();
}
}
}
System.out.println("Number of Connected Components: " + cc);
}
public static void main(String...arg)
{
int number_of_nodes;
Scanner scanner = null;
try
{
System.out.println("Enter the number of nodes in the graph");
scanner = new Scanner(System.in);
number_of_nodes = scanner.nextInt();
int adjacency_matrix[][] = new int[number_of_nodes][number_of_nodes];
System.out.println("Enter the adjacency matrix");
for (int i = 0; i < number_of_nodes; i++)
for (int j = 0; j < number_of_nodes; j++)
adjacency_matrix[i][j] = scanner.nextInt();
for (int i = 0; i < number_of_nodes; i++)
{
for (int j = 0; j < number_of_nodes; j++)
{
if (adjacency_matrix[i][j] == 1 && adjacency_matrix[j][i] == 0)
{
adjacency_matrix[j][i] = 1;
}
}
}
UndirectedConnectivityDfs undirectedConnectivity= new UndirectedConnectivityDfs();
undirectedConnectivity.dfs(adjacency_matrix);
}catch(InputMismatchException inputMismatch)
{
System.out.println("Wrong Input format");
}
scanner.close();
}
}

Make smaller christmas tree

So I'm beginning in the world of java programming language and I'm trying to print a christmas tree of X height. So far its working, but if for example the user input 4, it will print 4 rows + the christmas tree stump, wich mean 5. However, I would like it to be 4 INCLUDING the stump.So far I have this:
public class xmas {
public static void main(String[] args)
{
Scanner scan = new Scanner(in);
out.print("please enter a number: ");
int temp = scan.nextInt();
int x = (temp-1)*2 +1;
int y = x/2;
int z = 1;
for(int i=0; i<temp; i++)
{
for(int j=0; j<=y; j++)
{
out.print(" ");
}
for(int k = 0; k<z; k++)
{
out.print("*");
}
out.println();
y--;
z+=2;
}
for(int i =0; i<=x/2; i++)
{
out.print(" ");
}
out.println("*");
}
}
I don't know how to do that. Thanks!
Try using temp-- just after the input, like that:
int temp = scan.nextInt();
temp--;
Or decreasing your loop condition:
for(int i=0; i<temp-1; i++)
Output in both cases:
*
***
*****
*
If you just subtract one from the input, your christmas tree should be the right size. Here's what it would look like (using the Java style conventions):
public class ChristmasTree {
public static void main(String[] args) {
Scanner scanner = new Scanner(in);
out.print("Please enter a number: ");
int temp = scanner.nextInt() - 1; // note the `- 1`
int x = (temp - 1) * 2 + 1;
int y = x / 2;
int z = 1;
for(int i = 0; i < temp; i++) {
for(int j = 0; j <= y; j++) {
out.print(" ");
}
for(int j = 0; j < z; k++) {
out.print("*");
}
out.println();
y--;
z += 2;
}
for(int i =0; i<=x/2; i++) {
out.print(" ");
}
out.println("*");
}
}

Categories