print all binary numbers of size n using recursion - java

i am trying to print all size n binary numbers, for example if size is 3 , i want to print all numbers from 0 to (2^3)-1 in binary form, below if my code implementating, it prints 000 and gives me this error
"Exception in thread "main" java.lang.StackOverflowError
at java.lang.String.getChars(String.java:854)
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:391)
at java.lang.StringBuilder.append(StringBuilder.java:119)
at java.lang.StringBuilder.<init>(StringBuilder.java:93)
at NBinary.tobinary(NBinary.java:11)
at NBinary.tobinary(NBinary.java:12)".
String temp = str+x; is line 11
tobinary(temp, size); is line 12
below is my code
public class NBinary {
static int arr[] = {0,1};
static void tobinary(String str,int size){
if(str.length() == size){
System.out.println(str);
}
for(int x : arr){
String temp = str+x;
tobinary(temp, size);
}
}
public static void main(String[]args){
tobinary("", 3);
}
}
please help me find the error. thanks

One problem is that you are not giving any Recursion Termination condition.
So the function recurses infinitely. No condition is there to cease the calling.
That is why the stack allocated for the function call runs out of space and you get StackOverflowError.
See more here:
http://docs.oracle.com/javase/7/docs/api/java/lang/StackOverflowError.html
What is a StackOverflowError?

Related

Code written after infinite loop executes

The following code shows an empty infinite loop and code written after the loop prints "Hello, World".
In this example, the println statement to print the statement synchronously and thus theoretically, after the infinite loop nothing should be printed, but still when on running the code, it prints "Hello, World".
So, why is the code written after an infinite loop executing?
public class Main{
public static void main(String[] args){
for(int i=0; i>=0; i++){}
System.out.println("Hello, World"); // This is printed on the console
}
}
I tried searching goole and stackoverflow for it, but could not find an answer for the problem.
Thank you.
When i becomes greater than max value(2147483648 - that can be represented in 32 bits), it overflows to its min value.
It runs exaclty Integer.MAX_VALUE times, because Integer.MAX_VALUE + 1 is Integer.MIN_VALUE, a negative number.
You can visualize your code like this :
class Main {
public static void main(String[] args) {
int i = 0;
for(i=0; i>=0; i++){}
System.out.println("Hello, World : "+ i);
}
}
This loop is not an infinite loop. It goes until the i reaches Integer.MAX_VALUE. Then i becomes Integer.MIN_VALUE which is a negative value. Run the code below and check the output.
int x = Integer.MAX_VALUE;
x++;
System.out.println(x);
If you want the loop to be infinite use,
for ( ; ; ){
}
Either the compiler smartened up and knew that nothing was done in that loop (which shouldn't matter, because even the for conditions can edit stuff)
or i looped 2 million something times and overflowed into negative numbers, making it less than 0.

compare two strings in java

I am trying to compare to strings by using an algorithm as you see below
My code does not work .. eclipse does not show any error before I run the code
public class MysteryClass {
public static void mystery(String n) {
String k= "alla";
if (k.charAt(k.length())==n.charAt(n.length())) {
System.out.println("palindrom");
} else {
System.out.println("not palindrom");
}
}
public static void main(String[] args) {
MysteryClass.mystery("alla");
}
}
but we I run the code I get
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(String.java:658)
at shapes.MysteryClass.mystery(MysteryClass.java:6)
at shapes.MysteryClass.main(MysteryClass.java:15)
How to fix that??
thanks
Not sure what you want, but your StringIndexOutOfBoundsException is cause by access an array's index which is does not exist.
Take your String k = "alla" as example, k.length() will return 4 because "alla" have four characters, and you are accessing k.charAt(4), the "alla"break into as follows:
a l l a // string
0 1 2 3 // index
As you can see the last index of "alla" is 3, that's why you get StringIndexOutOfBoundsException. But you can solve it using .length() -1 as follow:
if (k.charAt(k.length()-1)==n.charAt(n.length()-1)) {
System.out.println("palindrom");
} else {
System.out.println("not palindrom");
Alternative:
If you want to compare two string, you can use .equals method too, as follow:
if (k.equals(n)) {
System.out.println("palindrom");
} else {
System.out.println("not palindrom");
Two issues with your code:-
1)By your logic, tigert is also palindrome but it is actually not.Palindrome is when the word is completely reversed and it is still the same.Currently,you are checking only the first and last character
2)String is internally held as a char array and arrays have indexing from 0 to length -1
The error is caused by the statement if (k.charAt(k.length())==n.charAt(n.length()))
Above k.length() returns 4. the statement then resolves to:
(k.charAt(4)
This will through error because the function charAt counts from the index 0. So it counts the characters at index 0, 1, 2, 3 and you are asking it to fetch character at index 4 which does not exist.
A suggested alternative is :
(k.charAt(k.length() -1)==n.charAt(n.length()-1))

why this code send me Stackoverflow in java

I've try to use long and double with c, k, n variables but netbeans shows me a stack overflow error:
public class Main {
public static void main(String[] args) {
double c=0; //combinatorial
double n=5;
double k=15;
c= factorial(n)/(factorial(k)*factorial(n-k));
System.out.print(n+" combinatorial "+k+" between "+c+"\n");
}
static double factorial (double number) {
if (number == 0)
return 1;
else
return number * factorial(number-1);
}
}
Exception in thread "main" java.lang.StackOverflowError
at co.combinatorial.Main.factorial(Main.java:26)
at co.combinatorial.Main.factorial(Main.java:29)
at co.combinatorial.Main.factorial(Main.java:29)
at co.combinatorial.Main.factorial(Main.java:29)
......
Java Result: 1
Do I have to use integer literals or long.parselong
What I am doing wrong?
From the initial values, n-k = -10. Since this is less than 0, your factorial method will never return
(number == 0) may not happen due to binary representation of number. Even with some tolerance level added, it is still incomplete this way. You may need negative number conformance. (10-10 maybe not zero)
Each time it goes deeper in function stack because of recursivity, it consumes more memory for function variables and parameters until java cannot plea more from operating system.
c= factorial(n)/(factorial(k)*factorial(n-k));
For n=5 and k=15,
factorial(n-k) would become: factorial(-10)
and then..
number*factorial(number-1) would give us: -10*factorial(-11),
and like this it would
continue indefinitely never reaching 0.
hence the stack will overflow.

What causes the ArrayIndexOutOfBoundsException?

This is a question in the book "Cracking the Coding Interview". Here is Java code, but why does it cause the ArrayIndexOutOfBoundsException? I just copied from the book.
class Q1_3{
public static void removeDuplicates(char[] str){
if(str==null) return;
int len=str.length;
if(len<2) return;
int t=1;
for(int i=1;i<len;++i){
int j;
for(j=0;j<t;++j){
if(str[i]==str[j])
break;
}
if(j==t){
str[t]=str[i];
++t;
}
}
str[t]=0; //why ?
}
public static void main(String[] args){
char ss1[] = {'a','b','c','d'};
char ss2[] = {'a','a','a','a'};
char ss3[] = {};
char ss4[] = {'a','a','b','b'};
removeDuplicates(ss1);
removeDuplicates(ss2);
removeDuplicates(ss3);
removeDuplicates(ss4);
System.out.println(ss1);
System.out.println(ss2);
System.out.println(ss3);
System.out.println(ss4);
}
}
It's really weird code, the naming and the use of control structures its... questionable...
The code breaks when there is no duplicated chars, t increases his value in all iterations and at the end is 4, this is what causes de exception.
in the example the code only crash with ss1, and "works" with the others.
If you debug the code closely, you will find that after comparing the value for the last element in the inner for loop you increment the value of t, thus the value of t will be str.length. But, array index start from 0 till str.length-1. So eventually, when you try to insert value at index str.length you will get the exception.

Exception in thread ArrayIndex

I was doing some beginner programming with series and input but im having the same problem constantly.Cant find the solution.Basically what i want my program to do for now i input a list of numbers and print them out.And im getting the same error over and over whatever i change in program.Here is my code.
import java.util.Scanner;
public class Test437 {
public static void main(String[] args) {
int limit = 25;
int cnt;
int addtion;
double dbt; //Devided by two % 2
Scanner input = new Scanner(System.in);
int [] ya = new int[8];
for(cnt = 0;cnt < ya.length;cnt++)
{
System.out.print("ya[" + cnt + "]= ");
ya[cnt] = input.nextInt();
}
System.out.println(ya[cnt]);
}
}
Im getting this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
at Test437.main(Test437.java:22)
System.out.println(ya[cnt]); this line is outside loop. Cnt is equal to an array size so it cannot be used in such way because there is no element in the array with such index.
The line:
System.out.println(ya[cnt]);
needs to be in a loop again to print out all the array values after accepting them:
for (cnt = 0;cnt < ya.length;cnt++) {
System.out.println(ya[cnt]);
}
Alternatively, you could do:
System.out.println(Arrays.toString(ya));
cnt condition to leave the loop is to exceed the length therefore you get in indexoutofbounds
This line
System.out.println(ya[cnt]);
is trying to access element at ya.Length index which does not exists.
In your example ya[8] contains elements at position from 0 to 7 (ya[0] ya[1] ... ya[7] and you're trying to access ya[8] bacuase cnt variable is 8 after the for statement ends.
Therefore the compiler throws an indexOutOfBounds exception.

Categories

Resources