My thrown exception running into StackOverflowError - java

I have the following simple recursive Fibonacci code:
public class FibPrac5202016
{
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter index number: ");
int integer = input.nextInt();
FibPrac5202016 object = new FibPrac5202016();
System.out.println(object.operation(integer));
}
public static long operation(long n) {
if(n==0)
return 0;
if(n==1)
return 1;
try {
if( n < 0)
throw new Exception("Positive Number Required");
}
catch(Exception exc)
{
System.out.println("Error: " + exc.getMessage());
}
return operation((n-1))+operation((n-2));
}
}
As I recently learned about exceptions, I'm trying to use that here when the user inputs negative integer.However, my program runs into StackOverflowError.

Well yes, because you recurse after you catch an Exception. You could trivially fix it by returning -1 in the catch.
catch(Exception exc)
{
System.out.println("Error: " + exc.getMessage());
return -1;
}
or not throwing an Exception in the first place like
public static long operation(long n) {
if (n < 0) {
return -1;
} else if (n == 0) {
return 0;
} else if (n == 1 || n == 2) {
return 1;
}
return operation((n-1))+operation((n-2));
}
or you could implement the Negafibonaccis. And, you could extend it to support BigInteger (and optimize with memoization) like
private static Map<Long, BigInteger> memo = new HashMap<>();
static {
memo.put(0L, BigInteger.ZERO);
memo.put(1L, BigInteger.ONE);
memo.put(2L, BigInteger.ONE);
}
public static BigInteger operation(long n) {
if (memo.containsKey(n)) {
return memo.get(n);
}
final long m = Math.abs(n);
BigInteger ret = n < 0 //
? BigInteger.valueOf(m % 2 == 0 ? -1 : 1).multiply(operation(m))
: operation((n - 2)).add(operation((n - 1)));
memo.put(n, ret);
return ret;
}

the problem is that these throws a execcion within a try block and this creates a cycle in which is testing the code and as always will be a smaller number than 0 always threw the exception infinitely until the exception is given
Exception in thread "main" java.lang.StackOverflowError
I think the solution is to make the program a stop when you find a number less than 0
as follows
public class FibPrac5202016 {
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter index number: ");
int integer = input.nextInt();
FibPrac5202016 object = new FibPrac5202016();
System.out.println(object.operation(integer));
}
public static long operation(long n) {
if(n==0)
return 0;
if(n==1)
return 1;
try
{
if( n < 0)
throw new Exception("Positive Number Required");
}
catch(Exception exc)
{
System.out.println("Error: " + exc.getMessage());
//return -1;
}
return operation((n-1))+operation((n-2));
}
}

Related

Binary search algorithm isn't returning variable

I'm very new to binary search and I attempted a code that would read values from a document and then the user can input a number to search for from the document, and through binary search, the number would be found. I'm having trouble now because the "low" variable that I initialize in the binary search section of my code is not being returned to my main code and there's an error that says "low can not be resolved to a variable".
Here is the code for my binary search:
static public int search (int[]numbers,int target, int count)
{
int high = numbers.length;
int low = -1;
int middle = (high+low)/2;
while(high-low>1)
{
count++;
middle = (high+low)/2;
if(numbers[middle]>target)
{
high = middle;
}
else if(numbers[middle]<target)
{
low = middle;
}
else
{
break;
}
System.out.println(numbers[middle]);
System.out.println(middle);
}
if(low == -1 || numbers[low]!=target)
{
low=-1;
return low;
}
else
{
return low;
}
}
And here is the code from my main code. The part with the if statements is where the error is showing up:
public static void main(String[] args) throws IOException {
DataInputStream input = new DataInputStream(System.in);
int [] numbers = new int [50000];
int target;
int count=0;
try
{
BufferedReader br = new BufferedReader(new FileReader("randNums.txt"));
for(int i=0;i<50000;i++)
{
numbers[i]=Integer.parseInt(br.readLine());
}
br.close();
Arrays.sort(numbers);
System.out.print("Choose a number between 1-100000000 to search for: ");
target = Integer.parseInt(input.readLine());
search(numbers, target,count);
if(low==-1)
{
System.out.println("The number was not on the list.");
}
else
{
System.out.println("The number is at position " + low);
System.out.println("It took " + count + " comparisons to find the number.");
}
}
You have to initialize low in main:
int low=search(numbers, target,count);
I have Already resolved this algorithm.
Try my code :
public static int guessNumber(int number) {
int first = 0;
int last = 1_000_000;
if (verify(first) == 0) {
count++;
return first;
}
if (verify(last) == 0) {
count++;
return last;
}
while (last > first && count <= 50) {
count += 1;
// get the middle of the range
int middle = (first + last) / 2;
if (verify(middle) == 0) {
return middle;
}
if (verify(middle) == 1) {
first = middle + 1;
if (verify(first) == 0) {
return first;
}
}else {
last = middle - 1;
if (verify(last) == 0)
return last;
}
}
return 0;
}
//Function verify(integer) => integer
public static int verify(int guess){
if (numberTobeGuessed > guess ) {
return 1;
}else if (numberTobeGuessed < guess) {
return -1;
}
return 0;
}
I recently found a solution for lazy peoples like me use below code
int position = Arrays.binarySearch(numbers , target);
here no need to sort, and array variable number integer variable target.

Multiply objects in an array witrh another object recursively in Java

Hello there I am learning Java and after doing some tasks to learn recursion I was giving my self some exercises to learn it a bit more but now I am struggeling with some..
So the main Problem is that I dont know how I can multiply every element in an Array recursively when the elements in that array are object (Maybe there is at the end no difference if objects are in there or not). So the exercise I gave myself was: check if 1 / 3 is in the given Array. If Yes then multiply everything in that array with 2 / 1.
This is Fraction:
private int numerator; // Zaehler
private int denominator; // Nenner
public Fraction ( int num, int denom )
{
if ( denom != 0 )
{
if ( denom < 0 )
{
numerator = -num;
denominator = -denom;
}
else
{
numerator = num;
denominator = denom;
}
reduce();
}
else
{
// error: division by zero
throw new IllegalArgumentException();
}
}
public Fraction()
{
numerator = 0;
denominator = 1;
}
public Fraction( int num )
{
numerator = num;
denominator = 1;
}
So I got it done by doing it with an for loop:
public static Fraction[] mulWithFor(Fraction[] arr)
{
for (int i = 0; i<arr.length; i++)
{
arr[i] = arr[i].multiply(new Fraction(2,1));
}
return arr;
}
But thats not my Main goal I want to do it recursively so that was my approach:
public static Fraction[] mulAus(Fraction[] arr, int i)
{
if (i>= 0 && i<arr.length)
{
rekurMul(arr,i);
//return mulAus(rekurMul(arr,i-1));
}
return arr;
}
public static Fraction rekurMul(Fraction[] arr, int i)
{
if (i>= 0 && i<arr.length)
{
return arr[i].multiply(new Fraction(2,1));
return arr[i].multiply(new Fraction(2, 1)); // Does Not Work!!!
}
throw new IndexOutOfBoundsException();
}
Maybe there is someone who can Help me! Thank you for your attention.
OK Thanks to #Chaï Sarfati and also to the others trying to help me out. I now know how to multiply recursive things in an Array! I used the Methods from #Chaï Sarfati but wrote an alternative method for his "oneThirdIsPresent" which is also a recursive method : So now my working code looks like this
public static Fraction[] mulAus(Fraction[] arr)
{
if(contains(arr,arr.length-1,new Fraction(1,3)))
{
rekurMul(arr,0);
return arr;
}
throw new IllegalArgumentException("1/3 does not exist in the Input-Array");
}
public static void rekurMul(Fraction[] arr, int i)
{
if(i == arr.length)
{
return ;
}
arr[i] = arr[i].multiply(new Fraction(2,1));
rekurMul(arr,i+1);
}
The Method to check if 1 / 3 exists in the given Array.
public static boolean contains(Fraction[] arr, int i, Fraction x)
{
if (i>= 0 && i < arr.length)
{
if (arr[i].equals(x))
{ return true;}
else
{ return contains(arr, i-1,x); }
}
return false;
}
I hope other People can learn from the code.. Maybe there are better solutions but I am just starting Programming so I dont know them for now.
Bye
Assuming you have a multiplyBy(Fraction f) method that works properly in you Fraction class.
Moreover, it will be better (more readable, more time & space complexity saving) to do it iteratively.
For the sake of the example, I would do like this:
First define:
private static boolean oneThirdIsPresent(Fraction[] arr){
for (int i = 0; i < arr.length; i++) {
if(arr[i].numerator == 1 && arr[i].denominator == 3) {
return true;
}
}
return false;
}
private static void recursivelyMultBy2(Fraction[] arr, int index){
if(index == arr.length){
return;
}
arr[index] = arr[index].multiplyBy(new Fraction(2));
recursivelyMultBy2(arr, index+1);
}
In order to solve finally:
public static void multBy2IfOneThirdIsPresent(Fraction[] arr){
if(oneThirdIsPresent(arr)){
recursivelyMultBy2(arr, 0);
}else{
return;
}
}
Here's a quick example of just the recursive multiplication part:
public static void main(String[] args)
{
Fraction[] fractions = new Fraction[] {new Fraction(1,2), new Fraction(2,3), new Fraction(3,1)};
System.out.println("Fractions:");
for(Fraction f: fractions)
{
System.out.println(f);
}
System.out.println("Multiplying array by 2...");
Fraction.mulAus(fractions, new Fraction(2, 1));
for(Fraction f: fractions)
{
System.out.println(f);
}
}
Modified Fraction Class (multiplication code at the bottom):
public class Fraction
{
private int numerator; // Zaehler
private int denominator; // Nenner
public Fraction(int num, int denom)
{
if (denom != 0)
{
if (denom < 0)
{
numerator = -num;
denominator = -denom;
}
else
{
numerator = num;
denominator = denom;
}
reduce();
}
else
{
// error: division by zero
//throw new IllegalArgumentException();
}
}
private void reduce()
{
// ...
}
public Fraction()
{
numerator = 0;
denominator = 1;
}
public Fraction(int num)
{
numerator = num;
denominator = 1;
}
public String toString()
{
return numerator + " / " + denominator;
}
public void MultiplyBy(Fraction F)
{
if (F != null)
{
numerator = numerator * F.numerator;
denominator = denominator * F.denominator;
reduce();
}
}
public static void mulAus(Fraction[] arr, Fraction F)
{
if(arr != null && F != null)
{
rekurMul(arr, 0, F);
}
}
private static void rekurMul(Fraction[] arr, int i, Fraction F)
{
arr[i].MultiplyBy(F);
if (i < (arr.length - 1))
{
rekurMul(arr, ++i, F);
}
}
}
Output:

FIbonacci series using recursion error?

public class Fibonacci2 {
static int fib(int n) {
if(n==1 || n==2) {
return(1);
}
return fib((n-1)+fib(n-2));
}
// Stackoverflow error //
public static void main(String[] args) {
int i, n = 7;
for(i=1; i<=n; i++)
System.out.println("FIbonaci series" + fib(i));
}
}
This program suffer from runtime exception (stackoverflow) please tell how to deal with it.
You step through the code in your debugger and you will see that
return fib((n-1)+fib(n-2));
should be
return fib(n-1) + fib(n-2);
as what you have is like
return fib(fib(n-2));
which quickly creates very high levels of recursion.
replace fib((n-1)+fib(n-2)) with fib(n-1)+fib(n-2).
May be it will help you
public static void fib(int initial, int current, int n) {
int sum = 0;
sum = initial + current;
if (initial == 0) {
System.out.print(current + " ");
}
System.out.print(sum + " ");
initial = current;
current = sum;
if (n > 2) {
fib(initial, current, n - 1);
}
}

Retrieving the two smallest inputs from an array in java

I'm taking an Intro to CS and one of the assignments asks for the 2 smallest numbers based off of user input. I've tried for about 3 days and just can't figure out why my code isn't working, and the more I work at it the more frustrated I get.
public class TwoSmallest {
public static void main(String[] args){
System.out.print("How many numbers will you be inputing? ");
int howManyNums = IO.readInt();
int[] arrayScores = new int[howManyNums];
for(int j = 0;j < howManyNums;j++){
System.out.print("Inuput number "+(j+1)+": ");
arrayScores[j]=IO.readInt();
int tinyNum1 = arrayScores[0];
int tinyNum2 = arrayScores[1];
for(int m = 0;tinyNum1 < arrayScores[m];m++){
//if (tinyNum1 < m) {
tinyNum1 = arrayScores[m];
}
for (int n = 1;tinyNum2 < arrayScores[n];n++){
//if (tinyNum2 < n) {
tinyNum2 = arrayScores[n];
}
if (tinyNum2 < tinyNum1){
int swapTinyNum1 = tinyNum1;
tinyNum2 = swapTinyNum1;
}
System.out.println("Smallest number: "+tinyNum1);
System.out.println("Followed by: "+tinyNum2);
}
We use the IO.readInt() for user input which I use to define the size of the array. I use it again at arrayScores[j]=IO.readInt(); to load the array. It kind of works when the user inputs the lower numbers first, but not when the higher numbers are input first. I think I'm having problems with retrieving the value at the designated index. It's probably a mess, but if anyone can help me out, it would definitely be appreciated. And here is the IO module we use, if this helps. I'm going to continue my endless battle at making this thing work..
import java.io.*;
public class IO
{
private static BufferedReader kb =
new BufferedReader(new InputStreamReader(System.in));
private static BufferedReader fio = null;
public static boolean openFile(String filename){
try{
fio = new BufferedReader(new FileReader(filename));
return true;
}catch (IOException e){ return false;}
}
public static String readLine(){
if (fio == null)
return null;
try{
return fio.readLine();
}catch(IOException e){ return null;}
}
public static String readString()
{
while (true) {
try {
return kb.readLine();
} catch (IOException e) {
// should never happen
}
}
}
public static int readInt()
{
while (true) {
try {
String s = kb.readLine();
return Integer.parseInt(s);
} catch (NumberFormatException e) {
System.out.print("That is not an integer. Enter again: ");
} catch (IOException e) {
// should never happen
}
}
}
public static double readDouble()
{
while (true) {
try {
String s = kb.readLine();
return Double.parseDouble(s);
} catch (NumberFormatException e) {
System.out.print("That is not a number. Enter again: ");
} catch (IOException e) {
// should never happen
}
}
}
public static char readChar()
{
String s = null;
try {
s = kb.readLine();
} catch (IOException e) {
// should never happen
}
while (s.length() != 1) {
System.out.print("That is not a single character. Enter again: ");
try {
s = kb.readLine();
} catch (IOException e) {
// should never happen
}
}
return s.charAt(0);
}
public static boolean readBoolean()
{
String s = null;
while (true) {
try {
s = kb.readLine();
} catch (IOException e) {
// should never happen
}
if (s.equalsIgnoreCase("yes") ||
s.equalsIgnoreCase("y") ||
s.equalsIgnoreCase("true") ||
s.equalsIgnoreCase("t")) {
return true;
} else if (s.equalsIgnoreCase("no") ||
s.equalsIgnoreCase("n") ||
s.equalsIgnoreCase("false") ||
s.equalsIgnoreCase("f")) {
return false;
} else {
System.out.print("Enter \"yes\" or \"no\": ");
}
}
}
public static void outputStringAnswer(String s)
{
if (s != null) {
System.out.println("RESULT: \"" + s + "\"");
} else {
System.out.println("RESULT: null");
}
}
public static void outputIntAnswer(int i)
{
System.out.println("RESULT: " + i);
}
public static void outputDoubleAnswer(double d)
{
System.out.println("RESULT: " + d);
}
public static void outputCharAnswer(char c)
{
System.out.println("RESULT: '" + c + "'");
}
public static void outputBooleanAnswer(boolean b)
{
System.out.println("RESULT: " + b);
}
public static void reportBadInput()
{
System.out.println("User entered bad input.");
}
}
To find the two smallest number:
int[] numbers = {}; // whatever.
int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] < min1) {
min2 = min1;
min1 = numbers[i];
} else if (numbers[i] < min2) {
min2 = numbers[i];
}
}

Recursive method to add odd numbers

I have the below snippet of code to use a recursive method to add the sum of odd numbers.
I have already coded the iterative method successfully that adds the sum of all odd numbers between n and m which are entered by the user. I'd like to reach that goal but am started slow to make sure I understand what is happening.
I know that it makes more sense to do it iteratively, however I am experimenting with the two types to see which is more efficient. I am stuck on the below as it is not doing what i want it to and i can't understand why.
import java.util.*;
public class SumofOdd
{
public static void main (String [] args)
{
int n = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter an odd number");
n = sc.nextInt();
int x = add(n);
}
public static int add(int x)
{
if (x == 0)
{
return 0;
}
else
{
return (x + add(x-1));
}
}
}
I have changed the above to the below. It compiles however stops after I enter the number.
import java.util.*;
public class SumofOdd
{
public static void main (String [] args)
{
int n = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter an odd number");
n = sc.nextInt();
if (n%2 == 0)
{
System.out.println("The number entered is even");
}
else
{
int x = add(n);
}
}
public static int add(int x)
{
if (x <= 0)
{
return 0;
}
else
{
return (x + add(x-2));
}
}
}
import java.util.*;
public class OddR{
public static void main (String Args [])
{
Scanner s = new Scanner(System.in);
System.out.println("Enter an odd number");
int max = s.nextInt();
if((max% 2) == 0) {
System.out.println(max + " is Even number and therefore is invalid");
}
else{
System.out.println("Enter a greater odd number");
int m = s.nextInt();
if (m <max){
System.out.println("Invalid data");
}
else{
if((m % 2) == 0) {
System.out.println(m + " is Even number and therefore is invalid");
}
else{
int data = (addodd(m)- addodd(max))+max;
System.out.print("sum:"+data);
}
}
}
}
public static int addodd(int m)
{
if(m<=0)
{
return 0;
}
if(m%2 != 0)
{
return (m+addodd(m-1));
}
else
{
return addodd(m-1);
}
}
}
This is the answer recursively of the sum of odd numbers from n to m
public int addOdds(int n) {
if (n <= 0) {
return 0;
}
if (n % 2 == 0) {
return addOdds(n - 1);
}
return x + addOdds(n - 1);
}
Take care, I never tested the code.
class Oddsum {
public int addodd(int n)
{
if(n<=0)
{
return 0;
}
if(n%2 != 0)
{
return (n+addodd(n-1));
}
else
{
return addodd(n-1);
}
}
}
public class Xyz {
public static void main (String[] v)
{
int n = 9;
Oddsum o = new Oddsum();
int data = o.addodd(n);
System.out.print("sum:"+data);
}
}
This is working fine
public static void main (String[] args){
public static int oddSum(int s){
if (s <= 0)
return 0;
else
return s + oddSum(s -2);
}
}

Categories

Resources