Question

Fibtester: package fibtester; // Imported to open files import java.io.File; // Imported to use the exception...

Fibtester:

package fibtester;

// Imported to open files
import java.io.File;
// Imported to use the exception when files are not found
import java.io.FileNotFoundException;
// Imported to write to a file
import java.io.PrintWriter;
// Imported to use the functionality of Array List
import java.util.ArrayList;
// Imported to use the exceptions for integer values
import java.util.NoSuchElementException;
// Imported to use when the array is out of bounds
import java.lang.NullPointerException;
// Imported to take input from the user
import java.util.Scanner;

public class FibTester
{
/**
* @param args will contain the name of the input and output file
*/
public static void main(String[] args)
{
int fibNumber = 0;

double initialTime = 0.0;
double finalTime = 0.0;
double iterativeTime = 0.0;
double recursiveTime = 0.0;

/*
Our table will have a fixed sized of 5 columns but the number of rows
will vary.
*/
final int COLUMNS = 5;
/*
The time will be stored in nanoseconds but the output will be displayed
in milliseconds. To convert, we need the following constant.
*/
final int MILLISECOND = 1000000;
ArrayList<Long> saveFibNumber = new ArrayList<Long>();
  
try
{
File inputFile = new File (args[0]);
/*
The delimeter will be used to ignore everything that is not a number
*/
Scanner inputStream = new Scanner(inputFile).useDelimiter("[^0-9]+" + "^\\.*");
PrintWriter outputFile = new PrintWriter(args[1]);   

try
{
fibNumber = inputStream.nextInt();

if (fibNumber >= 0)
{
LoopFib iterativeTest = new LoopFib();
RecursiveFib recursiveTest = new RecursiveFib();

//Start the Timer for Iterative Fib
initialTime = System.nanoTime();
for (int start = 0; start < fibNumber; start++)
{
saveFibNumber.add(iterativeTest.fib(start));
}
// Stop Timer
finalTime = System.nanoTime();
iterativeTime = (finalTime - initialTime) / MILLISECOND;

// Print to outputFile
outputFile.println("Expected Values. Time of execution: " + iterativeTime
+ " milliseconds\n");
displayTable(COLUMNS, saveFibNumber, outputFile);
outputFile.println("\n");

// Start the Timer for Recursive Fib
initialTime = System.nanoTime();
for (int start = 0; start < fibNumber; start++)
{
saveFibNumber.set(start, recursiveTest.fib(start));
}
// Stop the Timer
finalTime = System.nanoTime();
recursiveTime = (finalTime - initialTime) / MILLISECOND;

outputFile.println("‘Fast’ recursively-computed Fibonacci numbers. "
+ "\nTime of execution: " + recursiveTime + " milliseconds\n");
displayTable(COLUMNS, saveFibNumber, outputFile);
}
else
{
System.out.println("The input file contains a negative number.\n"
+ "Change format to a positive integer.");   
}
}
catch (NoSuchElementException exceptionInteger)
{
System.out.println("Make sure the file ONLY contains an Integer");
}
finally
{
outputFile.close();
inputStream.close();
}
}
catch (FileNotFoundException exceptionFile)
{
System.out.println("File not found. Please try again.");
}
catch (NullPointerException exceptionCommandLine)
{
System.out.println("Provide both input and output file names. Please "
+ "try again");
}
}

/**
* This method will display the Fibonacci number to the output file in a
* formated table
* @param COLUMNS How many columns the table will have
* @param saveFibNumber The array containing the Fibonacci number that will
* be printed
* @param out The output file that will be used to print the Fibonacci numbers
*/
public static void displayTable(int COLUMNS, ArrayList<Long> saveFibNumber, PrintWriter out)
{
for (int currentElement = 0; currentElement < saveFibNumber.size(); currentElement++)
{
out.printf("%9d" + " |", saveFibNumber.get(currentElement));
if ((currentElement + 1) % COLUMNS == 0)
{
out.printf("\n");
}
}
}

}

package fibtester;

// Imported to open files
import java.io.File;
// Imported to use the exception when files are not found
import java.io.FileNotFoundException;
// Imported to write to a file
import java.io.PrintWriter;
// Imported to use the functionality of Array List
import java.util.ArrayList;
// Imported to use the exceptions for integer values
import java.util.NoSuchElementException;
// Imported to use when the array is out of bounds
import java.lang.NullPointerException;
// Imported to take input from the user
import java.util.Scanner;

public class FibTester
{
/**
* @param args will contain the name of the input and output file
*/
public static void main(String[] args)
{
int fibNumber = 0;

double initialTime = 0.0;
double finalTime = 0.0;
double iterativeTime = 0.0;
double recursiveTime = 0.0;

/*
Our table will have a fixed sized of 5 columns but the number of rows
will vary.
*/
final int COLUMNS = 5;
/*
The time will be stored in nanoseconds but the output will be displayed
in milliseconds. To convert, we need the following constant.
*/
final int MILLISECOND = 1000000;
ArrayList<Long> saveFibNumber = new ArrayList<Long>();
  
try
{
File inputFile = new File (args[0]);
/*
The delimeter will be used to ignore everything that is not a number
*/
Scanner inputStream = new Scanner(inputFile).useDelimiter("[^0-9]+" + "^\\.*");
PrintWriter outputFile = new PrintWriter(args[1]);   

try
{
fibNumber = inputStream.nextInt();

if (fibNumber >= 0)
{
LoopFib iterativeTest = new LoopFib();
RecursiveFib recursiveTest = new RecursiveFib();

//Start the Timer for Iterative Fib
initialTime = System.nanoTime();
for (int start = 0; start < fibNumber; start++)
{
saveFibNumber.add(iterativeTest.fib(start));
}
// Stop Timer
finalTime = System.nanoTime();
iterativeTime = (finalTime - initialTime) / MILLISECOND;

// Print to outputFile
outputFile.println("Expected Values. Time of execution: " + iterativeTime
+ " milliseconds\n");
displayTable(COLUMNS, saveFibNumber, outputFile);
outputFile.println("\n");

// Start the Timer for Recursive Fib
initialTime = System.nanoTime();
for (int start = 0; start < fibNumber; start++)
{
saveFibNumber.set(start, recursiveTest.fib(start));
}
// Stop the Timer
finalTime = System.nanoTime();
recursiveTime = (finalTime - initialTime) / MILLISECOND;

outputFile.println("‘Fast’ recursively-computed Fibonacci numbers. "
+ "\nTime of execution: " + recursiveTime + " milliseconds\n");
displayTable(COLUMNS, saveFibNumber, outputFile);
}
else
{
System.out.println("The input file contains a negative number.\n"
+ "Change format to a positive integer.");   
}
}
catch (NoSuchElementException exceptionInteger)
{
System.out.println("Make sure the file ONLY contains an Integer");
}
finally
{
outputFile.close();
inputStream.close();
}
}
catch (FileNotFoundException exceptionFile)
{
System.out.println("File not found. Please try again.");
}
catch (NullPointerException exceptionCommandLine)
{
System.out.println("Provide both input and output file names. Please "
+ "try again");
}
}

/**
* This method will display the Fibonacci number to the output file in a
* formated table
* @param COLUMNS How many columns the table will have
* @param saveFibNumber The array containing the Fibonacci number that will
* be printed
* @param out The output file that will be used to print the Fibonacci numbers
*/
public static void displayTable(int COLUMNS, ArrayList<Long> saveFibNumber, PrintWriter out)
{
for (int currentElement = 0; currentElement < saveFibNumber.size(); currentElement++)
{
out.printf("%9d" + " |", saveFibNumber.get(currentElement));
if ((currentElement + 1) % COLUMNS == 0)
{
out.printf("\n");
}
}
}

}

Sequence:

package fibtester;

/**
*
* @author Sal
*/
public interface Sequence {
int next();
}

Recursivefib:

package fibtester;

import java.util.ArrayList;

/**
*
* @author Sal
*/
public class RecursiveFib
{
private ArrayList<Long> storingFibNumber = new ArrayList<Long>();
/*
To calculate the fibonacci number, you need the previous 2 fibonacci numbers
*/
private final int SECONDFIB = 2;

/**
* Method that will calculate the Fibonacci number
* @param fibNumber Which Fibonacci number we want to calculate
* @return the current Fibonacci number
*/
public long fib(int fibNumber)
{
if(storingFibNumber.size() < SECONDFIB)
{
storingFibNumber.add((long)1);
return 1;
}
if (storingFibNumber.size() < fibNumber)
{
return (fib(fibNumber - 1) + fib(fibNumber - SECONDFIB));
}
if (storingFibNumber.size() == fibNumber)
{
storingFibNumber.add(storingFibNumber.get(fibNumber - 1) + storingFibNumber.get(fibNumber - SECONDFIB));
return storingFibNumber.get(fibNumber - 1) + storingFibNumber.get(fibNumber - SECONDFIB);
}
else
{   
return storingFibNumber.get(fibNumber - 1) + storingFibNumber.get(fibNumber - SECONDFIB);
}
}
}

Loop fib:

package fibtester;

/**
*
* @author Sal
*/
public class LoopFib
{   
public long fib (int fibNumber)
{
if (fibNumber < 2)
{
return 1;
}
else
{
long olderValue = 1;
long oldValue = 1;
long newValue = 1;

for (int fibIteration = 2; fibIteration <= fibNumber; fibIteration++)
{
newValue = oldValue + olderValue;
olderValue = oldValue;
oldValue = newValue;
}
return newValue;
}
}
}

I NEED A URLEXCEPTION CLASS AND FASTFIBSEQUENCE CLASS. IDK HOW TO DO IT. JAVA

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Program is workin fine, there is no url exception class, But there is a main class (FibTester.java) which has main method in it , And it takes few file arguments , Actually two arguments

In case you are using command prompt ::

  • Use command " javac" to compile all files
  • but you have to run only one file with "java" command that is "FibTester.java"
  • like this : " java FibTester test1.txt test2.txt " (Note: first create these two files where all your java files are and write a single integer inside test1.txt.)

If you are using eclipse (This ones Easy)::

  • Goto run configurations of FibTester.java put two arguments in it with space separating them( test1.txt test2.txt) (if u dont know, it is explained in next step)
  • {Run-->Run Configurations-->(select class on left panel FibTester in this case) -->(then select Arguments tab on right after selecting your class -->(in first text area which says Program argument, type your arguments there)}.
  • then create two files with same name inside your workspace where all your java files are(test1.txt and test2.txt ).
  • write a single integer in test1.txt     eg: 3 (remember no space nothing else only number).
  • thats it you are done.

And Classes in project are :

  1. FibTester.java. (main class)
  2. RecursiveFib.java. (Logic)
  3. LoopFib.java. (Same as RecursiveFib)
  4. Sequence.java. (interface)

Its First and the second you are looking for ..

Hope this helps ..I am copying these classes below :

/////////////////////////////////////////////////////////////////FibTester.java/////////////////////////////////////////////////////////////////////////////


//Imported to open files
import java.io.File;
//Imported to use the exception when files are not found
import java.io.FileNotFoundException;
//Imported to write to a file
import java.io.PrintWriter;
//Imported to use the functionality of Array List
import java.util.ArrayList;
//Imported to use the exceptions for integer values
import java.util.NoSuchElementException;
//Imported to use when the array is out of bounds
import java.lang.NullPointerException;
//Imported to take input from the user
import java.util.Scanner;

public class FibTester
{

public static void main(String[] args)
{
   int fibNumber = 0;

   double initialTime = 0.0;
   double finalTime = 0.0;
   double iterativeTime = 0.0;
   double recursiveTime = 0.0;



   /*
   Our table will have a fixed sized of 5 columns but the number of rows
   will vary.
   */
   final int COLUMNS = 5;
   /*
   The time will be stored in nanoseconds but the output will be displayed
   in milliseconds. To convert, we need the following constant.
   */

   final int MILLISECOND = 1000000;
   ArrayList<Long> saveFibNumber = new ArrayList<Long>();

   try
   {
      File inputFile = new File (args[0]);
      /*
         The delimeter will be used to ignore everything that is not a number
      */
      Scanner inputStream = new Scanner(inputFile).useDelimiter("[^0-9]+" + "^\\.*");
      PrintWriter outputFile = new PrintWriter(args[1]);       
    
      try
      {
         fibNumber = inputStream.nextInt();

         if (fibNumber >= 0)
         {
            LoopFib iterativeTest = new LoopFib();
            RecursiveFib recursiveTest = new RecursiveFib();

            //Start the Timer for Iterative Fib
            initialTime = System.nanoTime();
            for (int start = 0; start < fibNumber; start++)
            {
               saveFibNumber.add(iterativeTest.fib(start));
            }
            // Stop Timer
            finalTime = System.nanoTime();
            iterativeTime = (finalTime - initialTime) / MILLISECOND;

            // Print to outputFile
            outputFile.println("Expected Values. Time of execution: " + iterativeTime
               + " milliseconds\n");
            displayTable(COLUMNS, saveFibNumber, outputFile);
            outputFile.println("\n");

            // Start the Timer for Recursive Fib
            initialTime = System.nanoTime();
            for (int start = 0; start < fibNumber; start++)
            {
              saveFibNumber.set(start, recursiveTest.fib(start));
            }
            // Stop the Timer
            finalTime = System.nanoTime();
            recursiveTime = (finalTime - initialTime) / MILLISECOND;        

            outputFile.println("‘Fast’ recursively-computed Fibonacci numbers. "
               + "\nTime of execution: " + recursiveTime + " milliseconds\n");
            displayTable(COLUMNS, saveFibNumber, outputFile);
         }
         else
         {
            System.out.println("The input file contains a negative number.\n"
               + "Change format to a positive integer.");             
         }
      }
      catch (NoSuchElementException exceptionInteger)
      {
         System.out.println("Make sure the file ONLY contains an Integer");
      }
      finally
      {
         outputFile.close();
         inputStream.close();
      }
   }
   catch (FileNotFoundException exceptionFile)
   {
      System.out.println("File not found. Please try again.");
   }
   catch (NullPointerException exceptionCommandLine)
   {
      System.out.println("Provide both input and output file names. Please "
         + "try again");
   }    
}

/**
* This method will display the Fibonacci number to the output file in a
* formated table
* @param COLUMNS How many columns the table will have
* @param saveFibNumber The array containing the Fibonacci number that will
*                      be printed
* @param out The output file that will be used to print the Fibonacci numbers
*/
public static void displayTable(int COLUMNS, ArrayList<Long> saveFibNumber, PrintWriter out)
{
   for (int currentElement = 0; currentElement < saveFibNumber.size(); currentElement++)
   {
      out.printf("%9d" + " |", saveFibNumber.get(currentElement));
      if ((currentElement + 1) % COLUMNS == 0)
      {
         out.printf("\n");
      }
   }
}

}

////////////////////////////////////////////////////////////////////////////////////////RecursiveFib.java/////////////////////////////////////////////////////////////////


import java.util.ArrayList;

/**
*
* @author Sal
*/
public class RecursiveFib
{
   private ArrayList<Long> storingFibNumber = new ArrayList<Long>();
   /*
   To calculate the fibonacci number, you need the previous 2 fibonacci numbers
   */
   private final int SECONDFIB = 2;

   /**
    * Method that will calculate the Fibonacci number
    * @param fibNumber Which Fibonacci number we want to calculate
    * @return the current Fibonacci number
    */
   public long fib(int fibNumber)
   {
      if(storingFibNumber.size() < SECONDFIB)
      {
         storingFibNumber.add((long)1);
         return 1;
      }
      if (storingFibNumber.size() < fibNumber)
      {
         return (fib(fibNumber - 1) + fib(fibNumber - SECONDFIB));
      }
      if (storingFibNumber.size() == fibNumber)
      {
         storingFibNumber.add(storingFibNumber.get(fibNumber - 1) + storingFibNumber.get(fibNumber - SECONDFIB));
         return storingFibNumber.get(fibNumber - 1) + storingFibNumber.get(fibNumber - SECONDFIB);
      }
      else
      {       
         return storingFibNumber.get(fibNumber - 1) + storingFibNumber.get(fibNumber - SECONDFIB);
      }
   }
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Add a comment
Know the answer?
Add Answer to:
Fibtester: package fibtester; // Imported to open files import java.io.File; // Imported to use the exception...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Java only. Thanks These questions involve choosing the right abstraction (Collection, Set, List, Queue, Deque, SortedSet,...

    Java only. Thanks These questions involve choosing the right abstraction (Collection, Set, List, Queue, Deque, SortedSet, Map, or SortedMap) to EFFICIENTLY accomplish the task at hand. The best way to do these is to read the question and then think about what type of Collection is best to use to solve it. There are only a few lines of code you need to write to solve each of them. Unless specified otherwise, sorted order refers to the natural sorted order...

  • How to solve this problem by using reverse String and Binary search? Read the input one...

    How to solve this problem by using reverse String and Binary search? Read the input one line at a time and output the current line if and only if it is not a suffix of some previous line. For example, if the some line is "0xdeadbeef" and some subsequent line is "beef", then the subsequent line should not be output. import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.TreeSet;...

  • Please complete the give code (where it says "insert code here") in Java, efficiently. Read the...

    Please complete the give code (where it says "insert code here") in Java, efficiently. Read the entire input one line at a time and then output a subsequence of the lines that appear in the same order they do in the file and that are also in non-decreasing or non-increasing sorted order. If the file contains n lines, then the length of this subsequence should be at least sqrt(n). For example, if the input contains 9 lines with the numbers...

  • Please answer question correctly and show the result of the working code. The actual and demo...

    Please answer question correctly and show the result of the working code. The actual and demo code is provided .must take command line arguments of text files for ex : input.txt output.txt from a filetext(any kind of input for the text file should work as it is for testing the question) This assignment is about using the Java Collections Framework to accomplish some basic text-processing tasks. These questions involve choosing the right abstraction (Collection, Set, List, Queue, Deque, SortedSet, Map,...

  • Please answer the question correctly and USE THE MOST EFFICIENT TECHNIQUE OF JAVA COLLECTION FRAME WORK...

    Please answer the question correctly and USE THE MOST EFFICIENT TECHNIQUE OF JAVA COLLECTION FRAME WORK to answer it. It is very essential that you do. Please make sure it is very efficient and doesnt run out of memory. A demo code required for the question is given below. These questions involve choosing the right abstraction (Collection, Set, List, Queue, Deque, SortedSet, Map, or SortedMap) to efficiently accomplish the task at hand. The best way to do these is to...

  • /** * */ package groceries; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ShoppingList {   ...

    /** * */ package groceries; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ShoppingList {    /**    * @param args    */    public static void main(String[] args) {        List groceryList = new ArrayList<>();        groceryList.add("rice");        groceryList.add("chicken");        groceryList.add("cumin");        groceryList.add("tomato");        groceryList.add("cilantro");        groceryList.add("lime juice");        groceryList.add("peppers");               groceryList.remove("cilantro");               for (int i = 0; i            if (groceryList.get(i).equals("peppers")) {...

  • package cards; import java.util.ArrayList; import java.util.Scanner; public class GamePlay { static int counter = 0; private...

    package cards; import java.util.ArrayList; import java.util.Scanner; public class GamePlay { static int counter = 0; private static int cardNumber[] = {1,2,3,4,5,6,7,8,9,10,11,12,13}; private static char suitName[] = { 'c', 'd', 'h', 's' }; public static void main(String[] args) throws CardException, DeckException, HandException { Scanner kb = new Scanner(System.in); System.out.println("How many Players? "); int numHands = kb.nextInt(); int cards = 0; if (numHands > 0) { cards = 52 / numHands; System.out.println("Each player gets " + cards + " cards\n"); } else...

  • PLEASE COMPLETE THE CODES. package javaprogram; import java.io.PrintStream; import java.util.ArrayList; import java.util.Scanner; /** * Movie class...

    PLEASE COMPLETE THE CODES. package javaprogram; import java.io.PrintStream; import java.util.ArrayList; import java.util.Scanner; /** * Movie class definition. * * @author David Brown * @version 2019-01-22 */ public class Movie implements Comparable { // Constants public static final int FIRST_YEAR = 1888; public static final String[] GENRES = { "science fiction", "fantasy", "drama", "romance", "comedy", "zombie", "action", "historical", "horror", "war" }; public static final int MAX_RATING = 10; public static final int MIN_RATING = 0; /** * Converts a string of...

  • Hi All, Can someone please help me correct the selection sort method in my program. the...

    Hi All, Can someone please help me correct the selection sort method in my program. the output for the first and last sorted integers are wrong compared with the bubble and merge sort. and for the radix i have no idea. See program below import java.io.*; import java.util.ArrayList; import java.util.Scanner; public class Sort { static ArrayList<Integer> Data1 = new ArrayList<Integer>(); static ArrayList<Integer> Data2 = new ArrayList<Integer>(); static ArrayList<Integer> Data3 = new ArrayList<Integer>(); static ArrayList<Integer> Data4 = new ArrayList<Integer>(); static int...

  • Can someone help me with my Java code error! Domain package challenge5race; import java.util.Random; public class...

    Can someone help me with my Java code error! Domain package challenge5race; import java.util.Random; public class Car {    private int year; private String model; private String make; int speed; public Car(int year, String model, String make, int speed) { this.year = year; this.model = model; this.make = make; this.speed = speed; } public Car() { } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public String getModel() { return model; }...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
Active Questions
ADVERTISEMENT