Char array indexes not accepting - java

I'm having an issue with a mock game of Tic tac toe. I'm using a two-dimensional array to represent the playing board, and have instantiated it as follows. It's required that I use a char type array. I realize that I shouldn't have to specify that each index is null, as that's the default for char, but I thought I would give it a try.
public TicTacToe2D()
{
board = new char[3][3];
for(int i = 0; i < board.length; i++)
{
for(int j = 0; j < board[i].length; j++)
{
board[j] = null;
}
board[i] = null;
}
}
Here I'm checking for a win condition, seeing if indexes are equal to each other and not null (the default) though I have attempted using ' ' for my array initial value. In that case I got the error: "incompatible types: char cannot be converted to char[]"
public char isWin()
{
//Check for row wins
if (board[0][0] == board[0][1] && board[0][1] == board[0][2] && board[0][0] != null)
return true;
if (board[1][0]==board[1][1] && board[1][1]==board[1][2] && board[1][0] != null)
return true;
if (board[2][0]==board[2][1] && board[2][1]==board[2][2] && board[2][0] != null)
return true;
//Check for column wins
if (board[0][0]==board[1][0] && board[1][0]==board[2][0] && board[0][0] != null)
return true;
if (board[0][1]==board[1][1] && board[1][1]==board[2][1] && board[0][1] != null)
return true;
if (board[0][2]==board[1][2] && board[1][2]==board[2][2] && board[0][2] != null)
return true;
//Check for diagonal wins
if (board[0][0]==board[1][1] && board[1][1]==board[2][2] && board[0][0] != null)
return true;
if (board[2][0] == board[1][1] && board[1][1] == board[0][2] && board[2][0] != 0)
return true;
else return false;
}
When checking if an index is null I get the error "incomparable types: char and "
Any help would be greatly appreciated!

The datatype char is primitive, so it can't be null. But the default value is the null character, \0 (or \u0000). JLS Section 4.12.5 gives default values:
For type char, the default value is the null character, that is, '\u0000'.
Try comparing it to \0 or \u0000 instead of null.

a char is not an object, it's a primitive type.
that means that a char is like an integer, or float, or Boolean, that have a fixed length and its initial value is zero (or false).
As far as I remember char is an 8bit, but I might be wrong. Said all that, a char you can compare to a letter, for example: 'a' or with an actual number, for example 0 or 1.

board is declared as char[][]. It is thus an array of char arrays. So board[i] is a char array (a row of your board). And board[i][j] is a char (the value of a cell of your board).
The default value of each cell of such a 2D array is 0. Not null. A primitive type can't be null.

Related

Color Game (Counter Loop not running)

I've been trying to figure out for the life of me why my counter loop isn't running. I have this snippet of my code that will not run even when I qualify the requirements of it being that (counter>=10). It should run the line saying that I lost the Game but it won't do so regardless. I initially thought it was because the counter was within the loop and since it'll keep going it won't ever meet the condition but even then it still won't go. My apologize if its not the best looking code far as spacing goes I'm still new to coding
void draw ()
{
int name=5, strikes=1;
int [][] scores= new int [name][strikes];
int score1=0;
keyPressed();
{
for (int x=0; x<10; x++)
{
first();
if (key == 'r' || key == 'R')
{
secoend();
}
if (key != 'r' || key != 'R')
{
score1++;
} else if (score1>=10)
{
background(255);
String text="You Lost the Game";
text(text, 411, 90);
}
}
}
}
This if-statement is always true, and so it will never enter the else-branch:
if (key != 'r' || key != 'R')
key can only be one thing so either of those is always true
I think you ment:
if (key != 'r' && key != 'R')
Check your if statements, you're always incrementing score1 because if(key != 'r' || key != 'R') will always be true.

Infinite loop with do-while condition

i'm doing an easy exercise for school, everything work except for this method. i want to insert some teams in a vector, but the array "serie" can only be A or B, upper or lower. I check with the debug and the while condition doens't work even if serie[i]=a.
public static void popolamento(String squadre[], char serie[], int punti[]) {
Scanner in= new Scanner(System.in);
for (int i=0;i<punti.length;i++) {
System.out.println("How many teams?");
squadre[i]=in.next();
do {
serie[i]=in.next().charAt(0);
System.out.println(serie[i]);
}
while (serie[i]!='a' || serie[i]!='A' || serie[i]!='b' || serie[i]!='B');
punti[i]=in.nextInt();
}
System.out.println("teams entered correctly ");}
The condition
(X != a || X != b || X != c || X != d)
should have been
(X != a && X != b && X != c && X != d)
Such a pattern is very likely an error, as to fail, all terms must fail
When X == u (X != u fails) then X != v holds (different cases assumed), hence always true.
If you read something like this, you know it is in 99.9% an error.

Java -NullPointerException thrown and I'm not sure why [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 6 years ago.
Improve this question
I am writing a program, in which, I have a method called "equals" to test whether two 2-dimensional arrays are "equal" to each other. equals returns whether the two args are equivalent in the sense that
If both args are null, return true
If one arg is null and the other isn't, return false;
If the 2 arrays have a different number of rows, return false
else, return whether each element in arr1 is equivalent to the corresponding element in arr2 in the sense that both elements are null, or both elements refer to arrays with the same number of ints with the same values in the same order.
equals method definition:
public static boolean equals( int[][] arr1, int[][] arr2){
//both are null references
if(arr1 == null && arr2 == null)
return true;
//only one is a null reference
if ((arr1 == null && arr2 != null) || (arr1 == null && arr2 != null))
return false;
//number of rows not identical
if( arr1.length != arr2.length )
return false;
for(int i = 0 ; i < arr1.length; i++){ //checking row equivalence
if(arr1[i] == null && arr2[i]==null){ //both null
continue;
}
if(arr1[i] == null || arr2[i] == null) //one is null
return false;
else if(arr1[i].length != arr2[i].length){
return false;
}
else{
for(int j = 0; j < arr1[i].length; i++){ //#of columns equal, compare them
System.out.println(i + "," + j); //helps debug
if(arr1[i][j] != arr2[i][j])
return false;
}
}
}
return true;
} //equals
When I call
equals( new int[][]{{1,2},{3,4},null}, new int[][]{{1,2},null,{3,4}} )
my program crashes, throwing the NullPointerException.
Eclipse says that it failed at this line:
if(arr1[i][j] != arr2[i][j])
The problem is, as far as I can tell, my program shouldn't be entering the enclosing for-loop where this line is located to begin with. It should return false at this point:
if(arr1[i] == null || arr2[i] == null) //one is null
return false;
What am I doing wrong here? Thank you.
You have a defect here,
if ((arr1 == null && arr2 != null) || (arr1 == null && arr2 != null))
should be
if ((arr1 == null && arr2 != null) || (arr1 != null && arr2 == null))
because otherwise you aren't testing both are arr1 and arr2. However, I would prefer Arrays.deepEquals(Object[], Object[]) which returns true if the two specified arrays are deeply equal to one another... Two array references are considered deeply equal if both are null, or if they refer to arrays that contain the same number of elements and all corresponding pairs of elements in the two arrays are deeply equal. like
public static boolean equals(int[][] arr1, int[][] arr2) {
return Arrays.deepEquals(arr1, arr2);
}

Check Rows in a game of tic tac toe that is four layers, four wide by four tall

public boolean checkWin() {
if(states[0][0][0] == 1 && states[0][0][1] == 1 && states[0][0][2] ==1 && states[0][0][3] ==1) { // Checks 0th layer, 0th row
return true;
}
else if (states[0][1][0] == 1 && states[0][1][1] == 1 && states[0][1][2] ==1 && states[0][1][3] ==1) { // Checks 0th layer, 1st row
return true;
}
else if (states[0][2][0] == 1 && states[0][2][1] == 1 && states[0][2][2] ==1 && states[0][2][3] ==1) { // Checks 0th layer, 2nd row
return true;
}
else if (states[0][3][0] == 1 && states[0][3][1] == 1 && states[0][3][2] ==1 && states[0][3][3] ==1) { // Checks 0th layer, 3rd row
return true;
}
}
This code is hard coded to check the 0 th layer, and the 4 rows on that layer. I could hard code the rest but of course that would be very time consuming and bad code. When I try and make a loop it stops after three clicks
public boolean checkWin() {
for (int i=0; i<=3; i++) {
if(states[0][0][i] == 1){ // Checks 0th layer, all rows
return true;
}
}
return false;
}
This is how I tried to make the loop, but it doesn't work.
This game is a nice example of how a data driven approach can simplify our code. Consider:
there are 64 cells, that can be empty or contain a token; the number of tokens depends on the number of players. This can be represented as a one dimensional array of 64 elements.
the cells are in 76 rows. This can be represented as a array of 76 rows of 4, each cell containing a subscript for an element in the first array. (In C or C++ you could also store pointers, in Java you can store references).
To check for a winning row, you can then just iterate through the 76 rows, and check if every cell in a row of the first array has the value you assigned to one player or the other.
Your current code checks only for rows in the third dimension. You should check the other dimensions as well:
for(int i = 0;i < 4;i++) {
for(int j = 0;j < 4;j++) {
if(
(states[i][j][0] == 1 && states[i][j][1] == 1 && states[i][j][2] == 1 && states[i][j][3] == 1) ||
(states[i][0][j] == 1 && states[i][1][j] == 1 && states[i][2][j] == 1 && states[i][3][j] == 1) ||
(states[0][i][j] == 1 && states[1][i][j] == 1 && states[2][i][j] == 1 && states[3][i][j] == 1)) {
return true;
}
}
}
You could make it more abstract than this by looping also over the last dimension, but that'd require boolean variables or break/continue statements so I think this is about as clear as the code is going to get.
You need to rewrite you loop like so:
public boolean checkWin() {
for (int layer=0; layer<=3; layer++) {
for (int row=0; row<=3; row++) {
if(states[layer][row][0] == 1){
return true;
}
}
}
return false;
}
This logic checks only for row based wins. Note however that in a TicTacToe, you also need to check for Column based win and diagonal win.

Comparing a character in Java

I'm having an issue comparing a character in Java. I'm trying to find a valid binary number, so I'm passing a string with the binary digits into a function and making sure they're either 0's or 1's. I loop through and check each character in the string, however, my function is telling me that it's bad (even when I know I've given it a proper binary number).
Here is the function:
public boolean isValidBinary(String s) {
//First we get the string length
int strLen = s.length();
//Now we loop through each character of the string
for(int x = 0; x < strLen; x++) {
//Assign the character to a variable each loopthrough
char c = s.charAt(x);
//Check if it's either a 0 or a 1
if(c != '0' || c != '1') {
return false;
}
}
//This is reached when all char's have been evaluated as 0 or 1
return true;
}
I have stared at this problem for quite some time and have been unable to figure it out, so any help would be appreciated.
That's a logical error. You meant && instead of ||.
You could use a regular expression for this anyway:
// must contain at least one digit, and only 0 or 1
public boolean isValidBinary(String s)
{
return s.matches("^[01]+$");
}
Rethink the logic in your inner condition: if(c != '0' || c != '1'). You want to use an AND here: if ((c != '0') && (c != '1')). This means that if both the conditions are true, then the input should be considered invalid, i.e,c is an invalid character if it isn't 0 and also isn't 1.
Consider the case where your code is checking a 1 character: it begins with the left side of the test: c != 0. This is true, and since the OR short-circuits, the result of your entire condition is true, and your function returns false, even though the current character being tested, 1, shouldn't invalidate the input.

Categories

Resources