Question

Please code this in java: The purpose of this assignment is to: Read double data in...

Please code this in java:

The purpose of this assignment is to:

  • Read double data in to a TreeSet where each datum inserted is Math.abs(datum) (i.e., no negative values are inserted).
    • NOTE: This will (i) sort the data placed into the TreeSet, and, (ii) remove duplicate values since no duplicates are allowed (i.e., duplicates will not be inserted).
  • Create a list iterator.
  • Iterate backwards through the TreeSet (i.e., from the largest value to the smallest) outputting all elements * -1.0.
  • Iterator forwards through the TreeSet (i.e., from the smallest value to the largest) outputting all element.

This assignment must be a public class called A5 in the package called comp2120. You will only need this class with a main() method to do this assignment. To help you do the assignment, the code in main() must be as follows:

  • Remember to declare this class in the comp2120 package at the top of the file.
    • This will require you to place this class in a comp2120 subdirectory.
  • Scanner, TreeSet, etc. are all in java.util. You can save yourself some typing by having import java.util.*;
  • Declare a TreeSet variable called sorted_set. Initialize it to an empty TreeSet.
  • Declare a Scanner variable that processes System.in (i.e., standard input).
  • Using a (for or while) loop, add the absolute value of all double values found in the System.in stream:
    • TIP: You want sorted_set.add(Math.abs(in.nextDouble());
  • Declare an ArrayList variable called sorted_seq. Initialize it to an ArrayList passing in sorted_set to its constructor.
    • NOTE 1: One cannot get a list iterator from a TreeSet as it is not an AbstractList. This is why an ArrrayList is being made --it provides a list iterator.
    • NOTE 2: Notice that all of the containers have a constructor that accepts any other container object. These constructors create an iterator from the object passed in and automatically insert each element into the container being constructed.
  • Declare a ListIterator variable called li and set its value to be sorted_seq.listIterator(sorted_seq.size());
    • NOTE 3: To get an iterator at the "starting position" of a container one calls the iterator() method of that container. Such iterators can only go "forwards" by calling the "next()" method, however. In this example, you want to start a the end --not the beginning-- which means you want to be able to go backwards too. List iterators permit such.
    • NOTE 4: To get a list iterator at the "starting position" of a container one calls the listIterator() method of that container. If one passes an "index" (i.e., position) to the listIterator() method then one gets an iterator pointing to that position. In the above code, by passing sorted_seq.size() the iterator returned is positioned at the "end" of the container. This implies that hasNext() will return false. This is okay since you'll be using hasPrevious() and previous() instead of hasNext() and next() below.
  • Create a while loop as follows:
    • while loop test: li.hasPrevious()
    • while loop body: Call System.out.println() with the result of li.previous * -1.0.
    • i.e., you are moving "backwards" through the container from the largest to the smallest value.
  • Create another while loop as follows:
    • NOTE: Do NOT create another iterator! You already have one at the position you need! :-)
    • while loop test: lt.hasNext()
    • while loop body: Call System..out.println() with the result of li.next().
    • i.e., you are moving "forwards" through the container from the smallest to the largest value

Sample Completed Program Output

Given the following input data:

$ cat testdata.txt
1.1 2.2 -1.5 3.3 2.2 1.1 4.4
$

Then the completed program would output:

$ java comp2120.A5 <testdata.in
-4.4
-3.3
-2.2
-1.5
-1.1
1.1
1.5
2.2
3.3
4.4
$ 

NOTE: Your code must handle all input without exceptions occurring. This includes when no double values are provided. Use java.util.Scanner's hasNextDouble() method to do this!

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

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

// A5.java

import java.util.ArrayList;

import java.util.ListIterator;

import java.util.Scanner;

import java.util.TreeSet;

public class A5 {

      public static void main(String[] args) {

            // creating a TreeSet of doubles

            TreeSet<Double> sorted_set = new TreeSet<Double>();

            // creating a Scanner

            Scanner scanner = new Scanner(System.in);

            // looping and adding all double values until there is no more

            // if you are using manual input, enter ctrl+Z or ctrl+D to trigger eof

            while (scanner.hasNextDouble()) {

                  // note: adding the absolute value (no sign)

                  sorted_set.add(Math.abs(scanner.nextDouble()));

            }

            // creating an array list from sorted_set

            ArrayList<Double> sorted_seq = new ArrayList<Double>(sorted_set);

            // creating a list iterator from the rear position

            ListIterator<Double> iterator = sorted_seq.listIterator(sorted_seq

                        .size());

            // looping and printing each element multiplied by -1.0 from rear to

            // front

            while (iterator.hasPrevious()) {

                  System.out.println(iterator.previous() * -1.0);

            }

            // looping and printing each element from front to rear

            while (iterator.hasNext()) {

                  System.out.println(iterator.next());

            }

      }

}

/*OUTPUT*/

1.1 2.2 -1.5 3.3 2.2 1.1 4.4

<eof triggered by ctrl+Z>

-4.4

-3.3

-2.2

-1.5

-1.1

1.1

1.5

2.2

3.3

4.4

Add a comment
Know the answer?
Add Answer to:
Please code this in java: The purpose of this assignment is to: Read double data in...
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
  • Create a nested inner class inside a file called LinkedList.java called the ListIterator. ListIterator: This public...

    Create a nested inner class inside a file called LinkedList.java called the ListIterator. ListIterator: This public class is nested within an LinkedList data structure and allows us to traverse the elements in any collection, access any data element and remove any data elements of the collection. It also adds the functionality to move forward and backward, which is new functionality. We are going to build this data structure from scratch. Instance variables (fields) are: mPrevious (Node) – the previous node...

  • Java implement the method in IteratorExercise.java using only list iterator methods: bubbleSort: sort the provided list...

    Java implement the method in IteratorExercise.java using only list iterator methods: bubbleSort: sort the provided list using bubble sort Do not modify the test code in each function. You can look at that code for some ideas for implementing the methods. import java.lang.Comparable; import java.util.*; public class IteratorExercise {       public static <E extends Comparable<? super E>> void bubbleSort(List<E> c) throws Exception {        // first line to start you off        ListIterator<E> iit = c.listIterator(), jit;...

  • Complete P16.1 and P16.4 (Class Name: NewMethodDemo) Once complete, upload all .java files. For primary test...

    Complete P16.1 and P16.4 (Class Name: NewMethodDemo) Once complete, upload all .java files. For primary test class: Remember your header with name, date, and assignment. Also include class names that will be tested. Psuedocode (level 0 or mixture of level 0 and algorithm [do not number steps]) is required if main() contains more than simple statements (for example, your program includes constructs for decisions (if/else), loops, and methods. For Secondary class(es): Include a JavaDoc comment that describes the purpose of...

  • Array with Iterator. Java style Implement an array data structure as a class JstyArray<E> to support...

    Array with Iterator. Java style Implement an array data structure as a class JstyArray<E> to support the Iterable interface such that the following code works: JstyArray<Integer> data; data = new JstyArray<Integer>(10); for (int i = 0; i < 10; ++i) { data.set(i, new Integer(i) ); } int sum = 0; for ( int v : data ) { if (v == null) continue; // empty cell sum += v; } The iterator provided by this class follows the behaviour of...

  • What is the code for this in Java? Assignment Inheritance Learning Objectives Declare a subclass that...

    What is the code for this in Java? Assignment Inheritance Learning Objectives Declare a subclass that derives from a superclas:s ■ Demon "Declare a variable of the superclass type and assign it an instance of the subclass type strate polymorphic behavior Access the public members of the superclass type Notice how the overridden versions of the subclass type are called Notice how the subclass specific members are inaccessible "Create an array of superclass type and use a foreach loop to...

  • Code a complete Java program for the following payroll application: First, hard code the following data...

    Code a complete Java program for the following payroll application: First, hard code the following data for the object ‘Employee’ into 4 separate arrays: SSN: 478936762, 120981098, 344219081, 390846789, 345618902, 344090917 First name      : Robert, Thomas, Tim, Lee, Young, Ropal Last name       : Donal, Cook, Safrin, Matlo, Wang, Kishal Hourly rate     : 12.75, 29.12, 34.25, 9.45,   20.95, 45.10 Hours worked: 45,        40,        39,       20,      44,        10 These 4 arrays must be declared inside the class and not within any method....

  • Please use my Lab 3.2 code for this assignment Lab 4.2 instruction Using the code from...

    Please use my Lab 3.2 code for this assignment Lab 4.2 instruction Using the code from lab 4.1, add the ability to read from a file. Modify the input function:       * Move the input function out of the Cargo class to just below the end of the Cargo class       * At the bottom of the input function, declare a Cargo object named         temp using the constructor that takes the six parameters.       * Use the Cargo output...

  • ASSIGNMENT DUE DATE GOT PUSHED BACK TO LATE THIS WEEK. PLEASE READ COMMENTS AND CODE BEFORE...

    ASSIGNMENT DUE DATE GOT PUSHED BACK TO LATE THIS WEEK. PLEASE READ COMMENTS AND CODE BEFORE ANSWERING CODING SECTIONS HW07 #Q1-Q5 HW08 #Q1-Q2 // READ BEFORE YOU START: // Please read the given Word document for the project description with an illustrartive diagram. // You are given a partially completed program that creates a list of students for a school. // Each student has the corresponding information: name, standard, and a linked list of absents. // Please read the instructions...

  • JAVA - Circular Doubly Linked List Does anybody could help me with this method below(previous)? public...

    JAVA - Circular Doubly Linked List Does anybody could help me with this method below(previous)? public E previous() { // Returns the previous Element return null; } Explanation: We have this class with these two implemented inferfaces: The interfaces are: package edu.ics211.h04; /** * Interface for a List211. * * @author Cam Moore * @param the generic type of the Lists. */ public interface IList211 { /** * Gets the item at the given index. * @param index the index....

  • For this week's lab, you will use two of the classes in the Java Collection Framework:...

    For this week's lab, you will use two of the classes in the Java Collection Framework: HashSet and TreeSet. You will use these classes to implement a spell checker. Set Methods For this lab, you will need to use some of the methods that are defined in the Set interface. Recall that if set is a Set, then the following methods are defined: set.size() -- Returns the number of items in the set. set.add(item) -- Adds the item to the...

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