Question

Class River describes river’s name and its length in miles. It provides accessor methods (getters) for...

Class River describes river’s name and its length in miles. It provides accessor methods (getters) for both variables and toString() method that returns String representation of the river.

Class CTRivers describes collection of CT rivers. It has no data, and it provides the following service methods. None of the methods prints anything, except method printListRec, which prints all rivers.

// Prints all rivers recursively. Print them is same order as they were in the list . List can be empy or not.

  • void printListRec(River[] list, int n)

// Returns index for the river object with given name. Returns -1 for unsuccessful search. List can

// be empy or not.

  • int linearSearch(River[] list, int n, String name)

// Returns ArrayList of rivers with length between min and max inclusive. Returns an empty

// Arraylist<River> if no such river was found. List can be empy or not.

  • ArrayList <River> searchRange(River[] list, int n, int min, int max)

// Sorts list of rivers by selection sort recursively (Compare river by their names.) List can be empy or not.

  • void sortByNameRec(River[] list, int n)

// PRECONDITION: Method assumes that input list is sorted by names. First and last are indices of the first

// and last character of the current substring. Returns index of River object with given name or returns -1

// if none of the rivers has that name. List can be empy or not.

  • int binarySearchRec(River[] list, int first, int last, String name)

Three methods marked in yellow must be implemented recursively.

File “input.txt”

Naugatuck   40

Pawcatuck   34

Quinebaug   69

Shepaug   26

Connecticut   407

Still   25

Quinnipiac   46

Housatoic 139

Class Driver has main method in it. Read data from an input file "input.txt" into an array of River objects, named riverList, and keep track of number of rivers stored in variable counter. Array riverList has capacity 100. Input file should be as shown.

  • Print all rivers.
  • Apply one successful and one unsuccessful linear search.
  • Print all rivers with length between min and max (min and max are provided by user). Must use for each loop in the main method to print resulting ArrayList<River> returned by method searchRange .
  • Sort myList by river names, and print sorted list.
  • Apply one successful and one unsuccessful binary search on sorted list.

Must print appropriate explanation in English of all steps performed in outcome.

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

Code

River.java
public class River
{
private String name;
private int length;

public River(String name, int length) {
this.name = name;
this.length = length;
}

public String getName() {
return name;
}

public int getLength() {
return length;
}

@Override
public String toString()
{
String str = String.format("%-12s %10d",name,length);
return str;
}
  
  
}

CTRiver.java
import java.util.ArrayList;


public class CTRivers
{
public void printListRec(River[] list, int n)
{
for(int i=0;i<n;i++)
System.out.println(list[i]);
}
public int linearSearch(River[] list, int n, String name)
{
for(int i=0;i<n;i++)
{
if(list[i].getName().equalsIgnoreCase(name))
return i;
}
return -1;
}
public ArrayList <River> searchRange(River[] list, int n, int min, int max)
{
ArrayList <River> riverList=new ArrayList<>();
for(int i=0;i<n;i++)
{
if(list[i].getLength()>=min && list[i].getLength()<=max)
riverList.add(list[i]);
}
return riverList;
}
public void sortByNameRec(River[] list, int n)
{
selectionSort(list,0,n);
}
//these are the helper function
private static void swap(River[] arr, int i, int j)
{
River temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// Recursive function to perform selection sort on sub-array arr[i..n-1]
private static void selectionSort(River[] arr, int i, int n)
{
// find the minimum element in the unsorted sub-array[i..n-1]
// and swap it with arr[i]
int min = i;
for (int j = i + 1; j < n; j++)
{
// if arr[j] element is less, then it is the new minimum
if (arr[j].getName().compareTo( arr[min].getName() ) < 0)
{
min = j; // update index of min element
}
}
// swap the minimum element in sub-array[i..n-1] with arr[i]
swap(arr, min, i);
if (i + 1 < n)
{
selectionSort(arr, i + 1, n);
}
}
River binarySearchRec(River[] list, int n, String name)
{
int index=binarySearch(list, 0, n-1, name);
if(index!=-1)
return list[index];
return null;
}
private static int binarySearch(River arr[], int l, int r, String x)
{
if (r >= l) {
int mid = l + (r - l) / 2;
  
// If the element is present at the middle itself
if (arr[mid].getName().equals(x))
return mid;
  
// If element is smaller than mid, then it can only
// be present in left subarray
if ((arr[mid].getName().compareTo(x))<0)
return binarySearch(arr, l, mid - 1, x);
  
// Else the element can only be present in right
// subarray
return binarySearch(arr, mid + 1, r, x);
}
  
// We reach here when element is not present in array
return -1;
}
public void insertInOrder(River[] list, int n, River river)
{
int i=0;
for(i=0;i<n;i++)
{
if(list[i].getName().compareTo(river.getName())>0)
break;
}
for(int j=n; j > i; j--)
{
list[j] = list[j-1];
}
list[i] = river;
}
}

Driver.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;


public class Driver {

/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
BufferedReader reader;
River []MyList=new River[100];
CTRivers ctObject=new CTRivers();
int count=0;
try
{
reader = new BufferedReader(new FileReader("input.txt"));
String line = reader.readLine();
while (line != null)
{
String[] splited = line.split(" ");
MyList[count]=new River(splited[0],Integer.parseInt(splited[1]));
line = reader.readLine();
count++;
}
reader.close();
} catch (IOException e)
{
e.printStackTrace();
}
System.out.printf("%-7s %15s\n","River Name","Length");
ctObject.printListRec(MyList, count);
int index=ctObject.linearSearch(MyList, count, "Quinnipiac");
  
System.out.println("\n\nUsing linear search\n");
if(index>=0)
System.out.println("Quinnipiac is in the array at location :"+index);
  
index=ctObject.linearSearch(MyList, count, "Ganga");
if(index>=0)
System.out.println("Ganga is in the array at location :"+index);
else
System.out.println("Ganga is not in the array");
  
ctObject.sortByNameRec(MyList, count);
System.out.println("\n\nAfter sorting\n");
System.out.printf("%-7s %15s\n","River Name","Length");
ctObject.printListRec(MyList, count);
  
System.out.println("\n\nUsing binary search\n");
  
River r=ctObject.binarySearchRec(MyList, count, "Pawcatuck");
  
if(r==null)
System.out.println("Pawcatuck is not available in the list");
else
System.out.println("Pawcatuck is available in the list");
  
r=ctObject.binarySearchRec(MyList, count, "Jamuna");
  
if(r==null)
System.out.println("Jamuna is not available in the list");
else
System.out.println("Jamuna is available in the list");
  
ctObject.insertInOrder(MyList, count, new River("Farmington",47));
count++;
ctObject.insertInOrder(MyList, count, new River("Ganga",187));
count++;
  
System.out.println("\n\nAfter adding 2 new river the list is :");
ctObject.printListRec(MyList, count);
  
}
  
}

outputs

Hope this may help you

Thank you ??

Add a comment
Know the answer?
Add Answer to:
Class River describes river’s name and its length in miles. It provides accessor methods (getters) for...
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
  • All those points need to be in the code Project 3 Iterative Linear Search, Recursive Binary...

    All those points need to be in the code Project 3 Iterative Linear Search, Recursive Binary Search, and Recursive Selection Sort Class River describes river's name and its length in miles. It provides accessor methods (getters) for both variables, toString() method that returns String representation of the river, and method isLong() that returns true if river is above 30 miles long and returns false otherwise. Class CTRivers describes collection of CT rivers. It has no data, and it provides the...

  • Hi, So I have a finished class for the most part aside of the toFile method...

    Hi, So I have a finished class for the most part aside of the toFile method that takes a file absolute path +file name and writes to that file. I'd like to write everything that is in my run method also the toFile method. (They are the last two methods in the class). When I write to the file this is what I get. Instead of the desired That I get to my counsel. I am having trouble writing my...

  • *** FOR A BEGINNER LEVEL JAVA CLASS, PLEASE KEEP CODE SIMPLE, AND WE USE BLUE J...

    *** FOR A BEGINNER LEVEL JAVA CLASS, PLEASE KEEP CODE SIMPLE, AND WE USE BLUE J IN CLASS (IF IT DOESNT MATTER PLEASE COMMENT TELLING WHICH PROGRAM YOU USED TO WRITE THE CODE, PREFERRED IS BLUE J!!)*** ArrayList of Objects and Input File Use BlueJ to write a program that reads a sequence of data for several car objects from an input file. It stores the data in an ArrayList<Car> list . Program should work for input file containing info...

  • In Java programming language Please write code for the 6 methods below: Assume that Student class...

    In Java programming language Please write code for the 6 methods below: Assume that Student class has name, age, gpa, and major, constructor to initialize all data, method toString() to return string reresentation of student objects, getter methods to get age, major, and gpa, setter method to set age to given input, and method isHonors that returns boolean value true for honors students and false otherwise. 1) Write a method that accepts an array of student objects, and n, the...

  • what is the solution for this Java problem? Generics Suppose you need to process the following...

    what is the solution for this Java problem? Generics Suppose you need to process the following information regarding Students and Courses: A Student has a name, age, ID, and courseList. The class should have a constructor with inputs for setting name, ID and age. The class should have setters and getters for attributes name, ID and age, and a method addCourse, removeCourse, printSchedule. courseList: use the generic class ArrayList<E> as the type of this attribute addCourse: this method takes as...

  • Array lists are objects that, like arrays, provide you the ability to store items sequentially and...

    Array lists are objects that, like arrays, provide you the ability to store items sequentially and recall items by index. Working with array lists involves invoking ArrayList methods, so we will need to develop some basic skills. Let's start with the code below: The main method imports java.utii.ArrayList and creates an ArrayList that can hold strings by using the new command along with the ArrayList default constructor. It also prints out the ArrayList and, when it does, we see that...

  • In Java, Implement a class MyArray as defined below, to store an array of integers (int)....

    In Java, Implement a class MyArray as defined below, to store an array of integers (int). Many of its methods will be implemented using the principle of recursion. Users can create an object by default, in which case, the array should contain enough space to store 10 integer values. Obviously, the user can specify the size of the array s/he requires. Users may choose the third way of creating an object of type MyArray by making a copy of another...

  • Please help. I need a very simple code. For a CS 1 class. Write a program...

    Please help. I need a very simple code. For a CS 1 class. Write a program in Java and run it in BlueJ according to the following specifications: The program reads a text file with student records (first name, last name and grade). Then it prompts the user to enter a command, executes the command and loops. The commands are the following: "printall" - prints all student records (first name, last name, grade). "firstname name" - prints all students with...

  • Use BlueJ to write a program that reads a sequence of data for several car objects...

    Use BlueJ to write a program that reads a sequence of data for several car objects from an input file. It stores the data in an ArrayList<Car> list . Program should work for input file containing info for any number of cars. (You should not assume that it will always be seven lines in the input file). Use notepad to create input file "inData.txt". File should be stored in the same folder where all files from BlueJ for this program...

  • *Java* Hi. I need some help with creating generic methods in Java. Write a program GenMethods...

    *Java* Hi. I need some help with creating generic methods in Java. Write a program GenMethods that has the following generic methods: (1) Write the following method that returns a new ArrayList. The new list contains the nonduplicate (i.e., distinct) elements from the original list. public static ArrayList removeDuplicates(ArrayList list) (2) Write the following method that shuffles an ArrayList. It should do this specifically by swapping two indexes determined by the use of the random class (use Random rand =...

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
ADVERTISEMENT