Tic Tac Toe in Java [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am writing a tic tac toe game in java. Right now I am currently stuck on the display board method. The board I am trying to create has lines in which the X's and O's will go into. The error I am currently getting is
TicTac2.java:56: error: illegal start of type
return result;
^
TicTac2.java:56: error: ';' expected
return result;
I will update this code as I go along it with little problems I encounter. I love this site because it helps so much! Anyway here is my code:
import java.util.*;
public class TicTac2{
//declare a constant variable
public enum Cell {E, X, O}; //this is an O, not 0
public Cell[][] board;
public static final int SIZE = 3; //size of each row and each column
public static void main(String[] args) {
displayBoard a = new displayBoard();
System.out.println(a);
}
//displayBoard method
public static void drawLine() {
for (int i = 0; i <= 4 * SIZE; i++) {
System.out.print("-");
}
System.out.println();
}
public static void displayBoard(char[][] board) {
drawLine();
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
SIZE[i][j] = Cell.E;
System.out.print("| " + board[i][j] + " ");
}
System.out.println("|");
drawLine();
}
System.out.println();
}
public String toString(){
String result = "";
for(Cell[] row : board) {
for(Cell col : row)
result += col;
}
result =+ "\n";
}
return result;
}

You are missing a { bracket
for(Cell col : row) { // <--- add this guy
result += col;
}
Consider learning to use an IDE. An IDE will point out these errors almost immediately. It will also find all other syntax errors.

displayBoard a = new displayBoard();
System.out.println(a);
I'm confused by these lines.
You are defining DisplayBoard as a method that takes in a two-dimensional array of Cells, but in the code above you are treating it like a class.
You don't want to create a displayBoard object (as it isn't a class), you just want to call the methods (and pass in board!).

Related

Below pattern code is not working as expected [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
The below pattern code is not working as expected.
public class pattern_print {
public static void main (String args[]){
int i = 1, j = 5, n = 5;
while (i <= n) {
while (j >= i) {
System.out.print("*");
j--;
}
System.out.print("\n");
i++;
}
}
}
Who can help me?
What are you expecting?
The code that you wrote is displaying the following chars:
*****
If you want to display something like:
*****
****
***
**
*
Then the correct code is:
public class pattern_print {
public static void main (String args[]) {
int i = 1, j = 5, n = 5;
while (i <= n) {
while (j >= i) {
System.out.print("*");
j--;
}
System.out.print("\n");
j=5;
i++;
}
}
}
Now depends what you expect to be displayed.
If the following triangle pattern is expected:
*****
****
***
**
*
the value of j needs to be reset to n as Andreea Frincu suggested.
However, for loops may be more preferable when printing patterns.
Also, since Java 11 released back in Sep 2018 there is method String::repeat which allows to avoid redundant nested loops and the same triangle pattern may be printed as simply as:
for (int i = 5; i >= 0; i--) {
System.out.println("*".repeat(i));
}

Why wont java let me have this else if statement? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I dont seem to understand why java will not allow me to have the else if statement in the solve method under the while loop, it tells me it is a syntax error. I thought that with a condition after the else if statement it would be the correct syntax but it is not working for me.
//Class to solve simple N Queens problem with backtracking, but without using recursion in a 1-d array.
public class NQueens
{
private int N;
private int board[];
public NQueens(int n)
{
this.N = n;
this.board = new int[N];
for(int i = 0; i<N; i++)
{
this.board[i]=-1;
}
}
//checks the place for any attack queens in the same column, or diagnol
public boolean safePlace(int row, int col, int [] board)
{
for (int i = 0; i<row; i++)
{
if((board[i] == col)|| (i-row)==(board[i]-col)|| (i-row)==(col-board[i]))
return false;
}
return true;
}
//solves N Queens problem using backtracking
public void solve()
{
int row=0;
while(row<this.N && row>-1)
{ // condition that the row is empty and the queen is safe to place
int col=0;
if(this.board[row]==-1 && safePlace(row, col, this.board));
{
this.board[row]=col;
row++;
}
//condition that the row is not empty
else if(this.board[row]>-1)
{
//start at column after the previous queen's column position.
col=this.board[row-1]+1;
//checks for safety
if(safePlace(row, col, this.board))
{
this.board[row]=col;
}
}
else //condition that no safe column can be found so queen in row is removed and we move back one row
{
this.board[row]=-1;
row--;
}
}
printBoard();
}
public void printBoard()
{
System.out.println("got to solve loop");
for(int i = 0; i<N; i++)
{
int chessBoard[]=new int[N];
chessBoard[this.board[i]] = 1;
if(chessBoard[i]==0)
System.out.print("* ");
else
System.out.print("Q ");
}
}
public static void main(String[] args)
{
NQueens q = new NQueens(4);
q.solve();
}
}
You have a semi-colon in the if statement which must be removed:
// semi-colon acts as an empty statement
if(this.board[row]==-1 && safePlace(row, col, this.board));
Remove semicolon
if(this.board[row]==-1 && safePlace(row, col, this.board));
semiolon is used to end the statement so the else part will say that there is no if which gives you the error.
Remove the semicolon after the first if statement and you should be good to go!

Java Square Class [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Here is what I am asked to do:
1. Create a class called Square that takes a width parameter in the constructor. The Square class should have a draw() method that will draw the square on the screen. Create a class called TestSquare that will take width from the user, create an object of Square, and invoke the draw() method on the square object.
Here is what I have, but the problem I am having is passing the draw() method to the test method. I know see that I need to move the for loops from the test to the class, so that i can call it in the test main method.
public class Square {
/** the width of square*/
int width;
/** construct the square*/
Square(){
}
/**construct a square */
Square(int newWidth){
width = newWidth;
}
/**show the square*/
void draw(){
for (int i=0; i<width; i++)
{
for (int j=0; j<width; j++)
{ System.out.print("* ");}
System.out.println();
}
}
}
import java.util.Scanner;
public class TestSquare {
/** Main method */
public static void main(String[] args) {
// Create a scanner input
Scanner input = new Scanner(System.in);
// prompt user to enter width
System.out.println("Creating a Square ...");
System.out.print("Please enter its width:");
int width = input.nextInt();
Square square = new Square(width);
System.out.println("Here is the Square:");
square.draw();
}
}
Change your loop into this:
for (int i=0; i<width; i++)
{
for (int j=0; j<width; j++)
{ System.out.print("*"); }
System.out.println();
}
As said, remove semicolons after loops because this makes your loop end immediately without arguments. i should be set to 1 so that it would reiterate in the correct number of times
And edit your getWidth() method into this:
int getWidth() {
return width;
}
Using width*width would make the method return n^2 of the width. It's supposed to be width not area.
Edit: I'm not sure if this is what you're trying to do but try putting this inside Square class:
void draw() {
for (int i=0; i<width; i++)
{
for (int j=0; j<width; j++)
{ System.out.print("*"); }
System.out.println();
}
}
Remove the getWidth() method completely. Then replace your getWidth() invocation with this:
square.draw();
There are a few problems.
Either rename this method to "getArea" or return width only:
int getWidth() {
return width*width;
}
Do not put a semicolon at the end of the for loop declarations. That makes the for loop do nothing. Also, the outer for loop should start at 0 (not 1):
for (int i=1; i<width; i++); //remove this trailing semicolon
{
for (int j=0; j<width; j++); //remove this trailing semicolon
System.out.print("*");
System.out.println();
}

Array out of bounds exception:100 [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
This program is giving me array out of bounds exception :100
How to resolve??? also tell me whether my printing method of array is correct or not?
import java.util.Random;
import java.lang.Math;
class MersennePrime {
public int[] MersennefindPrime() {
int i=0;
int k=0;
int array[] = new int[100];
for(i=2;i<100;i++)
{
int count=0;
for(int j=2;j<=Math.sqrt(i);j++ )
{
if(i%j==0)
{
}
else
{
array[k]=i;
k++ ;
}
}
}
return array;
}
}
public class MersenneRandomNumbers
{
public static void main(String[] args)
{
MersennePrime mrn = new MersennePrime();
int array[] =mrn.MersennefindPrime();
for(int s=0;s<=array.length;s )
System.out.println("array is " array[s]);
}
}
}
This
for(int s=0;s<=array.length;s )
System.out.println("array is " array[s]);
}
should be like this
for(int s=0; s<array.length; s++) {
System.out.println( "array is " + array[s] );
}
Note the change from <= to <!
In your code, within the last loop s equals array.length, which is just the first index outside the boundaries of the array.
EDIT
Beside the upper syntactic error, there is a logical one here as well. In MersennefindPrime() the outer loop runs from 0 to 100, while the inner loop runs ("worst case") from 2 to 10. So there might be about 10 * 100 times, where you increase k and try to set the respective index in the array. This is far more, than the 100 items you allocated the array for!
If you can't be sure about the extent of your array at initialization, use some class, that implements the interface List. This could then look like this:
public List<Integer> MersennefindPrime() {
ArrayList<Integer> array = new ArrayList<Integer>();
for(int i=2;i<100;i++)
{
for(int j=2;j<=Math.sqrt(i);j++ )
{
if(i%j==0)
{
}
else
{
array.add( i );
}
}
}
return array;
}
You would have to adjust the code in main() accordingly!

Return an array with method in Java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a doubt.
I am developing the following code which will be a multplication table for a number that you manually introduce. What I cannot get is to print the table. I don't know what is going on because as far as I know, all the code is right written.
public class Tabla
{
public static void main (String[] args)
{
int n=4;
Tabla table = new Tabla ();
int dato [];
dato=table.producto(n);
for (int j=1;j<=10;j++)
{System.out.println(dato[j]);}
}
public int [] producto(int num)
{
int a[]={'0'};
for (int i=1;i<=10;i++)
{a[i]=num*i;}
return a;
}
}
Any ideas??
Thanks in advance!
**I changed the code to:
public class Tabla
{
public static void main (String[] args)
{
int n=4;
int j;
Tabla table = new Tabla ();
int dato[]=new int [10];
dato=table.producto(n);
for (j=0;j<10;j++)
{System.out.println(dato[j]);
}
}
public int [] producto(int num)
{
// make a 10-element array
int a[] = new int[10];
// fill up the array with products
for (int i = 0; i < 10; i++)
{a[i] = num * (i+1); }
return a;
}
}
Works like a charm!
Now I am wondering why the compiler threw the "ArrayIndexOutOfBoundsException" when I had the for cycle as for (int i = 1; i <=10; i++)
Thanks for the help! :D
Building off of Wasserman's answer, what you should have written is as follows:
public int[] producto(int num)
{
// make a 10-element array
int a[] = new int[10];
// fill up the array with products
for (int i = 0; i < 10; i++)
a[i] = num * (i + 1);
return a;
}
You created a single-element array, whereas you wanted a 10-element array to fill up.
Two problems:
int a[]={'0'};
This line creates an array a with only one element -- not the 11 you're trying to fill -- and moreover, that one element is the ASCII code for the character 0, which is almost certainly not what you want.

Categories

Resources