Array out of bounds Java Code - java

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.

Related

Passing array to a function and using that array in an Enhanced for loop

When I pass the array "bucky" to the change function and in the change function if I use an enhanced for loop, the variable counter gives the error "The value of the local variable counter is not used"
But if I put the body of the for loop in an System.out.println(counter+=5) the error does not appear
class apples{
public static void main(String[] args) {
int bucky[]={3,4,5,6,7};
change(bucky);
}
public static void change(int x[]){
for(int counter: x){
counter+=5;
}
}
}
Why does this code give the error I mentioned above since I'm using the counter variable in the enhanced for loop?
Edit - my objective is to change values of the array inside the "change" function and return it back to main.
Question is about updating original array values, then you have to use normal for loop so that each index values can be updated:
class apples{
public static void main(String[] args) {
int bucky[]={3,4,5,6,7};
bucky = change(bucky);
for(int b:bucky) {
System.out.println(b);
}
}
public static void change(int x[]){
for (int i = 0; i < x.length; i++) {
x[i]=x[i]+5;
}
return x;
}
}

return parameters from command line program

I'm trying to pass a String via Command Line in java, but it returns only the first value i.e. args[0]
Below is what I've done
public class CommandLine
{
public static void main(String[] args)
{
int i;
i = args[0].length(); //throws error here if args.length();
System.out.println(i); //checking length, return with args[0] only
while(i>0)
{
System.out.println(args[0]);
i++;
}
}
}
What should I do to improve this and make it working?
Here are few things to be addressed
In your logic command line arugment length is taken in wrong way.
Loop condition is not apt for your requirement, moreover It is an infinite loop or never ending loop which reduces the performace of the code.Should never use infinite loops in the code.
3.you are printing the same index ie.. args[0] every time inside loop.
Code:
public static void main(String[] args)
{
int i=0;
int len = args.length; //use length only in this case;
System.out.println(len); // this will return it properly now
while(i<len)
{
System.out.println(args[i]);
i++;
}
}

Code doesn't compile on Hackerrank

The following code works fine on my IDE but I keep getting a "Compile Time Error" when I add it to Hackerrank. What am I doing wrong?
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String input = in.next();
System.out.println(delete(input));
}
public static int delete(String in){
char[] arr = in.toCharArray();
int del = 0;
for(int x=0; x < arr.length-1; x++){
if(arr[x] == arr[x+1]){
del++;
}
}
return del;
}
}
Your code works fine in Intellij too. But there is a wrong exist. Both main and delete methods are static. You use 'in' for both methods. Therefore just change the name of the string in delete method.

why does it stop half way through my code?

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)

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