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.
Related
public static void main(String args[]){
extract("e:\\");
}
public static void extract(String p){
File f=new File(p);
File l[]=f.listFiles();
int counter = 0;
for(File x:l){
if(x.isDirectory()) extract(x.getPath());
else if(x.getName().endsWith(".mp3"))){
counter = counter + 1;
}
}
// I want to count and return value at last
}
Using this method(above), resets the counter every time when for loop ends.
So here, I want to count even when the for loop ends so that I can keep track of the number of .mp3 files.
I want to count and return value at last.
Return the current counter and make sure you add the response when you call recursively back to the counter.
public static void main(String args[]) {
int count = extract("../");
}
public static int extract(String p) {
File f = new File(p);
File l[] = f.listFiles();
int counter = 0;
for (File x : l) {
if (x.isDirectory()) {
counter += extract(x.getPath());
} else if (x.getName().endsWith(".mp3")) {
counter++;
}
}
return counter;
}
You should not use recursion like that. (Recursion should always have a termination condition to avoid running in a loop forever!
I think the problem is, that you create new Integers every time you call your method, so you will eventually override your old value or even use many different Integers to count.
You can wrap everything in a class in which you keep track of one integer.
Some pseudo-code:
public class Mp3Counter {
private int numberOfMp3 = 0;
public void extract(...) {
if (foundMp3) {
this.numberOfMp3 += 1;
}
}
}
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.
I am writing a very simple program in Java that tries to divide 10 by a user-entered number and catches a DivideByZeroException. Here is the code:
public class EnhancedCatchExceptions6 {
public static void main(String[] args) {
System.out.println();
for (int i = 0 ; i < i; i++) {
try {
int b = Input.getInt("Enter an integer to divide by:");
divide(10, b);
break;
} catch (DivideByZeroException e) {
System.out.println("Error: Divided by zero. Try again.\n");
}
}
}
public static int divide(int x, int y) throws DivideByZeroException {
System.out.println();
int result = 0;
try {result = x/y;}
catch (ArithmeticException e) {throw new DivideByZeroException(y);}
return result;
}
}
For some reason is returns an error: cannot find symbol for every 'DivideByZeroException.' If I change DivideByZeroException to Exception it does not return that error. The same error appears when I was writing other programs with other exceptions.
I don't understand why this error is returned and I would appreciate any help. Thanks!
Most likely this is happening because you forget to import your DivideByZeroException. Change the first lines of your class adding:
import your.package.name.DivideByZeroException;
and you should be fine. Do not forget to use real package name of yours, of course.
The other guess - if you want a class that represents an exception and comes with JDK, not your own, consider replacing DivideByZeroException with ArithmeticException.
So the first part creates a vector and adds a digit to the 10 slots. Then after this nothing happens, i have no errors in my code but it just stops.. why?
package ovn7;
import java.util.Scanner;
public class ovn7a {
int []vektor;
Scanner scan = new Scanner(System.in);
public static void main(String []args) {
int []vektor = new int[10];
for(int k=1; k<10; k++){
vektor[k]=0+k;
System.out.println(k);
}
}
public int find(int tal) {
System.out.println("tal");
tal = scan.nextInt();
int i = 0;
while(i<10 && vektor[i] != tal) {
i++;
}
return (i <10) ? i : -1;
}
}
This is your main method:
public static void main(String []args) {
int []vektor = new int[10];
for(int k=1; k<10; k++){
vektor[k]=0+k;
System.out.println(k);
}
}
That's all your program does - when it hits the closing right brace of the main method, execution ends. If you want it to execute public int find(int tal) as well, you need to include a method call to your main method:
int index = find(5); //for example
Remember, the main method is the only one that is called automatically when executing the program! You'll have to call find yourself inside main.
EDIT: per request, an example of main with the method call included:
public static void main(String []args) {
int []vektor = new int[10];
for(int k=1; k<10; k++){
vektor[k]=0+k;
System.out.println(k);
}
int index = find(5); // <-- this find(5) here is a method call for find!
System.out.println("The method returned a value of " + index + ".");
}
You can replace that "5" with any integer, as the method find accepts an integer as an argument. (as a side note, it doesn't matter which integer you pass to find - it overwrites the argument with a new value anyway)
Please help me to figure out array index out of bounds error in following simple code. I am running this code in eclipse.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Union_Find {
public static void intialization(int arr[])
{
for(int i=0;i<arr.length;i++)
{
arr[i]=i;
}
}
public static void print(int arr[])
{
int i;
for(i=0;i<arr.length;i++);
{
System.out.print(" "+arr[i]);
}
}
/**
* #param args
*/
public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter array size");
int n=Integer.parseInt(br.readLine());
int arr[]=new int[n];
intialization(arr);
print(arr);
}
}
Notice the semi-colon after the loop in your print method:
for(i=0;i<arr.length;i++);
now this for loop will run till i == arr.length - 1, and do nothing. And as the value is equal to arr.length, it ends, and then the next block, which is just a local block unrelated to for loop:
{
System.out.print(" "+arr[i]);
}
is executed, and throws ArrayIndexOutOfBounds exception, as it is really trying to access arr[arr.length].
Coincidentally, you have also declared int i outside the loop in that method only, else the compiler would have marked that print statement as error.