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

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!

Related

Reordering numbers in an array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am trying to solve a leetcode problem :
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
And I think I have the correct solution but I'm just not sure why I'm getting it incorrect.
class Solution {
public void moveZeroes(int[] nums) {
for (int i = 0; i > nums.length;i++) {
int j= i;
while ((j<nums.length) && (nums[j]==0)){
j++;
}
if (j<nums.length){
nums[i]=nums[j];
nums[j]=0;
}
}
}
}
You can solve this problem O(N) with one pointer. This'd pass through:
public class Solution {
public static void moveZeroes(int[] nums) {
if (nums == null || nums.length == 0)
return;
int pos = 0;
for (int num : nums)
if (num != 0)
nums[pos++] = num;
while (pos < nums.length)
nums[pos++] = 0;
}
}
References
For additional details, you can see the Discussion Board. There are plenty of accepted solutions with a variety of languages and explanations, efficient algorithms, as well as asymptotic time/space complexity analysis1, 2 in there.
The for loop isn't correct (has to be i < nums.length), also, your solution doesn't work if there is nothing to do:
final int[] expectedArray = {1,2,0,0};
final String expectedString = Arrays.toString(expectedArray);
int[] nothingToDo = {1,2,0,0};
moveZeroes(nothingToDo);
assertEquals(expectedString, Arrays.toString(nothingToDo));
yields in:
org.junit.ComparisonFailure: expected:<[[1, 2], 0, 0]> but was:<[[0, 0], 0, 0]>
Just write some test cases yourself and see what's wrong.
In your case:
if (j<nums.length){
nums[i]=nums[j];
nums[j]=0;
}
is wrong because you're swapping i with j, even if i == j and nums[i] != 0.
Since I don't think you're asking for a working solution, I won't provide one. But here are my test cases:
#Test
public void testEmptyArray() {
int[] array = new int[0];
moveZeroes(array);
assertEquals(0,array.length);
}
#Test
public void testZeroOnlyArrays() {
int[] array = {0,0,0,0};
final String arrayString = Arrays.toString(array);
moveZeroes(array);
assertEquals(arrayString, Arrays.toString(array));;
}
#Test
public void mixedTest() {
int[] array = {0,1,0,2};
final int[] expectedArray = {1,2,0,0};
final String expectedString = Arrays.toString(expectedArray);
moveZeroes(array);
assertEquals(expectedString, Arrays.toString(array));;
int[] nothingToDo = {1,2,0,0};
moveZeroes(nothingToDo);
assertEquals(expectedString, Arrays.toString(nothingToDo));
}
The 'for' loop should be: for (int i = 0; i < nums.length;i++)
then, your loop will run on the array indexes from 0 until it reaches the length of the array.
The current code will not even enter the loop as you have defined i=0 and the loop condition is run the loop only if it is larger than the array size: (i > nums.length) which of course is not true
You are using i > nums.length that's why loop is not executed
You need an index for non-zero value. Here in my solution j is for non-zero value index means when you find a non-zero value set j index and increment it. If j is smaller than i or equal that's means there will be zero found then set it.
public void moveZeroes(int[] nums) {
int j = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
nums[j] = nums[i];
j++;
}
if (j <= i) {
nums[i] = 0;
}
}
}

How to loop through an array and get how many zeros there are

I have a 2D array and it's like a maze.
So I loop through the first row to see if there is a zero (This zero is the opening) and then I go down to see if there is another zero below that zero.
The problem is that after the first 2 rows I don't know how I can write code to check left,right or down of that zero and move there and continue until I cannot do so any longer.
import java.util.Scanner;
public class AssignmentTwo
{
//int[rows][columns]
int[][] gasCavern = {{1,1,1,1,1,0,1},
{1,0,0,1,1,0,1},
{1,1,1,0,0,0,1},
{1,1,0,0,1,1,1},
{1,0,1,0,1,0,1},
{1,0,1,0,0,0,1},
{0,0,0,1,1,1,0},
{1,1,1,0,0,0,1}};
int counter = 0;
boolean checked = false;
// forLoop that deals with the first 2 rows.
// First check 1st row for a zero.
// Then check down and increment counter which ultimately shows area.
for(int column = 0; column < gasCavern[0].length; column++)
{
//Checking for opening in 1st row
if(gasCavern[0][column]== 0)
{
counter++;
gasCavern[0][column] = 2;
if(gasCavern[1][column]==0)
{
counter++;
}
}
}
for(int i=1; i<gasCavern.length; i++)
{
for(int j=0; j < gasCavern.length; j++)
{
if(gasCavern[i][j])
{
//Looking left
if(gasCavern[i][j-1]==2)
{
gasCavern[i][j-1]=2;
counter++;
}
//Looking Right
if(gasCavern[i][j+1]==2)
{
gasCavern[i][j+1]=2;
counter++;
}
//Looking up
if(gasCavern[i+1][j]==2)
{
gasCavern[i+1][j]=2;
counter++;
}
//Looking down
if(gasCavern[i-1][j]==2)
{
gasCavern[i-1][j]==2
counter++;
}
}
}
}
public boolean checkedForZeros()
{
//If returning false,go through while loop again
}
}
This is the code I have so far. In case I wasn't clear this is what I want to happen:
http://imgur.com/YOr86xs
I think with a bit more thought you would have got it!
Think about it, all you have to do is check the adjacent elements in the row you are looking at, which are just the columns in each side. Therefore:
[column+1]
Would check the element to the right, and:
[column-1]
Would check the element to the left.
Just be sure you don't accidentally go out of bounds.
EDIT: Let us know how you get on, if you are still struggling, I will provide more code, but try first.
This should work:
for (int x = 0; x < gasCavern.length; x++) {
for (int y = 0; y < gasCavern[x].length; y++) {
int num = gasCavern[x][y];
if (num == 0) {
// if it is a zero
} else {
// if it's not a zero (a one)
}
}
}

Tic Tac Toe in Java [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 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!).

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