Tuesday, April 29, 2014

Fibonacci Series with Reading the Number from a file placed in your Local System

One of this question i encountered while giving interview of Oracle, although qualified well, but at times people gets confused with various Stream Classes defined in java.io package. So to make it more easy to understand and to cope up with Question too, i have come up with a technique where people will read the number upto which we want to print the fibonacci series to from a file and then printing the fibonacci series using recursion.





Our approach to this solution will be
1) Read the number from a file using various Stream Classes with java.io.* package.
2) Call fibonacci method and calculate the next number in the series using recursion.



import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class FibonacciSeriesFromFile {


public static void main(String[] args) throws IOException {

System.out.println("This Program Reads Data from a file which is a number till where u want to print the Fibonacci Series: ");
FileInputStream in = null;
DataInputStream din=null;
BufferedReader br = null;
try {
in = new FileInputStream("C:\\input.txt");
din = new DataInputStream(in);
br= new BufferedReader(new InputStreamReader(din));
String strLine;
while ((strLine = br.readLine()) != null) {
String str=strLine;
int c= Integer.parseInt(str);
System.out.println("The number upto which we want the fibonacci sequence is: "+c);
for (int i = 1; i <= c; i++) {

System.out.println(fibonacci(i));
}
}
} catch (IOException e) {
System.out.println("Exception caught" + e);
} finally {
if (in != null) {
in.close();
}
if (din != null) {
din.close();
}
if (br != null) {
br.close();
}
}

}


public static int fibonacci(int number) {


if (number == 1) {

return 0;
}
if (number == 2) {
return 1;
}
return (fibonacci(number - 1) + fibonacci(number - 2));
}

}


With Respect to the above code what i have come up with the significance of all the java.io classes which are used in this program. You can find in more detail in my next blog.

For any queries, please post comemnts below.

No comments:

Post a Comment