Main seems to skip over one of my methods - java

Apologies for posting a bit of a foolish question, but I cant seem to understand why my method startEndCoords does not seem to run properly through my main method here:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class MazeSolver {
// The name of the file describing the maze
static String mazefile;
// set global variables
static int arrayHeight;
static int arrayWidth;
static int startRow;
static int startColumn;
static int endRow;
static int endColumn;
static int cellsize;
static int borderwidth;
static int sleeptime;
static char [][] maze;
public static void main(String[] args) throws FileNotFoundException {
if (handleArguments(args)) {
maze = readMazeFile(args[0]);
startEndCoords(maze);
if (solveMaze(startRow, startColumn))
System.out.println("Solved!");
else
System.out.println("Maze has no solution.");
}
}
// get starting & ending points
static boolean startEndCoords(char[][] mazeAsArray){
for (int r = 0; r < MazeSolver.arrayHeight; r++) {
for (int c = 0; c < MazeSolver.arrayWidth; c++) {
if (mazeAsArray[r][c] == 'S') {
MazeSolver.startRow = r;
System.out.println(startRow);
MazeSolver.startColumn = c;
System.out.println(startColumn);
}
if (mazeAsArray[r][c] == 'E') {
MazeSolver.endRow = r;
System.out.println(endRow);
MazeSolver.endColumn = c;
System.out.println(endColumn);
return true;
}
}
}
return false;
}
The print statements within the method will not execute, not sure what im missing.
Thanks for your help.
full code

It appears that your readMazeFile method is intended to set some of the global variables you declare, but it actually doesn't. It instead declares its own local variables that happen to have the same names, and sets those. This leaves MazeSolver.arrayHeight at its default value of 0, so of course the for loop instantly bails before even running once.
Remove the int from the lines in readMazeFile that set arrayHeight and arrayWidth. This will make it use and set the existing static variables instead of creating new local ones.

Related

Private and final methods

I am trying to get a better understanding of private and public methods. I am trying to make a private method called GRID_SIZE and let that equal the length(m) of my grid, however, I am getting a message saying that it cannot be resolved into a variable. My understanding is that if a method is private only the class can access it and if a method is public any class can enter. So I am confused as to why I can't take a variable from the public method to a private method.
public class trial1 {
private static final int GRID_SIZE = m;
public static void main(String[] args) {
int m = 8;
char[][] grid = new char[m][m];
for (int i=0; i<grid.length; i++) {
for(int j = 0; j<grid[i].length; j++) {
grid[i][j] = '*';
StdOut.print(grid[i][j]);
}
StdOut.println();
}
}
}
You're creating a static field, not a method. The visibility is not relevant to the question.
Static (class) variables simply cannot be set before the class is initialized; there is no m until the main method is executed (after the class is instantiated by the JVM). Plus, you've made the field final, so it cannot be modified within the main method, anyway.
Perhaps you want this?
public class Trial1 {
private static final int GRID_SIZE = 8;
public static void main(String[] args) {
char[][] grid = new char[GRID_SIZE][GRID_SIZE];
Your problem here is around scope.
Variables defined within a method are only visible within that method. So in your code the variable m is only accessible by code inside the main class.
GRID_SIZE is a private static field (not a method) and that means it is accessible by all code within the class.
If you want GRID_SIZE to be assigned a value defined in method scope (e.g. m) then you need to remove the final from GRID_SIZE and set it from within the main method.
Something like:
public class Trial1 {
private static int GRID_SIZE ;
public static void main(String[] args) {
int m = 8;
GRID_SIZE = m;
char[][] grid = new char[m][m];
for (int i=0; i<grid.length; i++) {
for(int j = 0; j<grid[i].length; j++) {
grid[i][j] = '*';
StdOut.print(grid[i][j]);
}
StdOut.println();
}
}
}
Please note this is just an example of how to change GRID_SIZE. If you just want GRID_SIZE to always be a particular value then as the previous answer states you could just set it directly to 8.

Accessing scope of a variable once declared outside class

Hi I have this code to get shortest word in a string:-
import java.util.Arrays;
public class Kata {
public static int findShort(String s) {
int shortestLocation = null;
String[] words = s.split("");
int shortestLength=(words[0]).length();
for(int i=1;i<words.length;i++){
if ((words[i]).length() < shortestLength) {
shortestLength=(words[i]).length();
shortestLocation=shortestLength;
}
}
int p = shortestLocation;
return p;
}
}
It returns error that variable shortestLocation cannot be converted to int:-
java:6: error: incompatible types: <null> cannot be converted to int
int shortestLocation = null;
My question is how do you access the scope of a variable,like in this case I know what is wrong. The variable shortest location is defined outside the scope of if statement,hence it considers only the value with which it was initialized.
How do i make it so that the initial value is changed to the if-statement value. It is a scope problem,please help i am beginner.
import java.util.Arrays;
public class Kata {
public static int findShort(String s) {
int shortestLocation = null;
this ^^ line needs to be initialized to an integer... not 'null' 0 is fine
String[] words = s.split("");
int shortestLength=(words[0]).length();
for(int i=1;i<words.length;i++){
your problem starts here ^^ you never iterate through all of the words as you stop at i<words.length the problem with that is you begin at i=1. for loops work like this for (begin here; until this is not met; do this each time) when i=words.length the condition is no longer met.
if ((words[i]).length() < shortestLength) {
shortestLength=(words[i]).length();
shortestLocation=shortestLength;
}
}
int p= shortestLocation;
No need to initialize p here... just return shortest location.
return p;
}
}
that leaves the final code like this
import java.util.Arrays;
public class Kata {
public static int findShort(String s) {
int shortestLocation = 0;
String[] words = s.split("");
int shortestLength=(words[0]).length();
for(int i=0;i<words.length;i++){
if ((words[i]).length() < shortestLength) {
shortestLength=(words[i]).length();
shortestLocation=shortestLength;
}
}
return shortestLocation;
}
}
Keep in mind, to get a 'good' result it HEAVILY weighs on the words list
As pointed out in the comments initializing your original 'int p' could help with debugging.

removing a column from a 2d array

I am trying to write a class that will remove a column from a 2d array, but I keep running into errors that I don't understand. I think I am misunderstanding something very basic here, any help would be appreciated
public class CollumnSwitch
{
int[][] matrix;
int temp;
public static void coldel(int[][] args,int col)
{
for(int i =0;i<args.length;i++)
{
int[][] nargs = new int[args.length][args[i].length-1];
for(int j =0;j<args[i].length;j++)
{
if(j!=col)
{
int temp = args[i][j];
}
nargs[i][j]= temp;
}
}
}
public void printArgs()
{
for(int i =0;i<nargs.length;i++)
{
for(int j =0;j<nargs[i].length;j++)
{
System.out.print(nargs[i][j]);
}
System.out.println();
}
}
}
You cannot access a non-static variable from a static context, you need to change int temp; to static int temp; or you can remove static from your method declaration.
You declare your nargs array in the coldel method, so it is not accessible from other methods. Meaning this doesn't work:
for(int i =0;i<nargs.length;i++) //You try to access nargs which is not possible.
{
for(int j =0;j<nargs[i].length;j++)
...
Maybe you want it to be the matrix array you have in your class? Like this:
in coldel:
matrix= new int[args.length][args[i].length-1];
and in printArgs
for(int i =0;i<matrix.length;i++)
{
for(int j =0;j<matrix[i].length;j++)
...
This require matrix to be static also (again, you can also remove static from coldel)
you can try like this:
static int[][] nargs;
public static void deleteColumn(int[][] args,int col)
{
if(args != null && args.length > 0 && args[0].length > col)
{
nargs = new int[args.length][args[0].length-1];
for(int i =0;i<args.length;i++)
{
int newColIdx = 0;
for(int j =0;j<args[i].length;j++)
{
if(j!=col)
{
nargs[i][newColIdx] = args[i][j];
newColIdx++;
}
}
}
}
}
public static void printArgs()
{
if(nargs != null)
{
for(int i =0;i<nargs.length;i++)
{
for(int j =0;j<nargs[i].length;j++)
{
System.out.print(nargs[i][j] + " ");
}
System.out.println();
}
}
}
Your difficulties are arising due to using variables outside of their scope. In java, variables basically only exist within the most immediate pair of braces from which they were declared. So, for example:
public class Foo {
int classVar; // classVar is visible by all code within this class
public void bar() {
classVar = classVar + 1; // you can read and modify (almost) all variables within your scope
int methodVar = 0; // methodVar is visible to all code within this method
if(methodVar == classVar) {
int ifVar = methodVar * classVar; // ifVar is visible to code within this if statement - but not inside any else or else if blocks
for(int i = 0; i < 100; i++) {
int iterationVar = 0; // iterationVar is created and set to 0 100 times during this loop.
// i is only initialized once, but is not visible outside the for loop
}
// at this point, methodVar and classVar are within scope,
// but ifVar, i, and iterationVar are not
}
public void shoo() {
classVar++; // shoo can see classVar, but no variables that were declared in foo - methodVar, ifVar, iterationVar
}
}
The problem you are having is because you are declaring a new 2-d array for each iteration of the for loop and writing one column to it, before throwing that away, creating a new array, and repeating the process.

Array of queues not compiling - cannot find symbol error

I'm trying to get a radix sort going with an array of queues to avoid long rambling switch statements but I'm having some trouble getting the array properly initialized. The constructor and an example of an implementation are given below.
I'm just getting a cannot find symbol error when I try to compile though.
public static radixj(){
IntQueue[] buckets = new IntQueue[10];
for (int i = 0; i < 10; i++)
buckets[i] = new IntQueue();
}
public static void place(int temp, int marker)
{
int pos = temp % marker;
buckets[pos].put(temp);
}
I'm pretty sure it is a really simple mistake that I'm making but I can't find it. Any help would be greatly appreciated.
In your code
IntQueue[] buckets = new IntQueue[10];
is a local variable to the function
public static radixj()
which must have a return type
public static void radixj()
So then you can't use it in another function
buckets[pos].put(temp);
You should declare a static class variable
class Foo {
static IntQueue[] buckets = new IntQueue[10];
...
and access it using: Foo.buckets
class Foo {
public static IntQueue[] buckets = new IntQueue[10];
public static void radixj() {
for (int i = 0; i < 10; i++) {
Foo.buckets[i] = new IntQueue();
}
}
public static void place(int temp, int marker) {
int pos = temp % marker;
Foo.buckets[pos].put(temp);
}
}
the return type in radixj() is missing and buckets cannot be resolved to a variable

Why does this program loop infinitely?

I have the following code (it doesn't matter what it does, but for the curious, it's the start of an implementation of a square bending algorithm).
The problem is, it loops for no reason:
import java.util.*;
import java.io.*;
import java.lang.*;
class Solution
{
public static class kll
{
int ni;
int nj;
int pi;
int pj;
int v;
kll(){};
}
public static class g
{
static kll[][] a;
static int wh;
}
public static void f(int i1,int i2,int j1,int j2)
{
int nj1,nj2;
while (g.a[i1][i2].ni!=g.wh && g.a[i1][i2].nj!=g.wh)
{
i1=g.a[i1][i2].ni;
i2=g.a[i1][i2].nj;
}
while (g.a[j1][j2].ni!=g.wh && g.a[j1][j2].nj!=g.wh)
{
j1=g.a[j1][j2].ni;
j2=g.a[j1][j2].nj;
}
while (j1!=0)
{
nj2=g.a[j1][j2].pj;
nj1=g.a[j1][j2].pi;
g.a[i1][i2].ni=j1;
g.a[i1][i2].nj=j2;
g.a[j1][j2].pi=i1;
g.a[j1][j2].pj=i2;
i1=j1;
i2=j2;
j1=nj1;
j2=nj2;
}
g.a[i1][i2].ni=g.wh;
g.a[i1][i2].nj=g.wh;
}
public static void main(String[] args)
{
try
{
FileWriter oos1 = new FileWriter("output.txt");
File inTxt=new File("input.txt");
Scanner kbd = new Scanner(inTxt);
int input=kbd.nextInt();
kbd.close();
int number=(int)Math.pow(4,input);
g.wh=(int)Math.sqrt(number);
g.a=new kll[g.wh+1][g.wh+1];
for(int i=0;i<g.wh+1;i++)
for(int j=0;j<g.wh+1;j++)
g.a[i][j]=new kll();
for(int i=0;i<g.wh;i++)
for(int j=0;j<g.wh;j++)
{
g.a[i][j].ni=g.wh;
g.a[i][j].nj=g.wh;
g.a[i][j].pi=0;
g.a[i][j].pj=0;
g.a[i][j].v=0;
}
int separator=g.wh;
int half;
while(separator>1)
{
half=separator/2;
for(int i=0;i<half;i++)
for(int j=0;j<separator;j++)
f(j,i,j,separator-1-i);
for(int i=0;i<half;i++)
for(int j=0;j<separator;j++)
f(i,j,separator-1-i,j);
separator=half;
}
}
catch (FileNotFoundException ex) {}
catch(IOException ex) {}
}
}
Where have I gone wrong? That is, where is the infinite loop? What is causing it, and how can I fix it?
EDIT:
I have tried the debugger and it showed me that the infinite loop is here:
while (j1!=0)
{
nj2=g.a[j1][j2].pj;
nj1=g.a[j1][j2].pi;
g.a[i1][i2].ni=j1;
g.a[i1][i2].nj=j2;
g.a[j1][j2].pi=i1;
g.a[j1][j2].pj=i2;
i1=j1;
i2=j2;
j1=nj1;
j2=nj2;
}
I don't have any idea why it's infinite. j1 has got to be zero when it takes nj1 which is also zero. What's going wrong?
Simply put, j1 is never set to 0, because nj1 is never set to 0, because g.a[ji][j2].pi is never set to 0.
Place breakpoints and inspect g.a[ji][j2].pi -- you will see that it is never 0, given a particular set of arguments.
In particular, you will want to look at the arguments that feed your f() function that are causing that function to infinitely loop.
Once you have determined the problematic arguments, you can place an if-statement that causes a breakpoint to be hit before that function is called -- if you have not already determined why f() fails.

Categories