Questions
Java program Prime Numbers A prime number is a natural number which has exactly two distinct...

Java program

Prime Numbers

A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself. For example, the first four prime numbers are: 2, 3, 5 and 7.

Write a java program which reads a list of N integers and prints the number of prime numbers in the list.

Input: The first line contains an integer N, the number of elements in the list.

N numbers are given in the following lines.

Output: Print the number of prime numbers in the given list.

Constraints:

1 ≤ N ≤ 10000

2 ≤ an element of the list ≤ 108

Sample Input 1

5
2
3
4
5
6

Sample Output 1

3

Sample Input 2

11
7
8
9
10
11
12
13
14
15
16
17

Sample Output 2

4

In: Computer Science

Create a Python program that: Allows the user to enter a phrase or sentence. The program...

Create a Python program that:

  • Allows the user to enter a phrase or sentence.
    • The program should then take the phrase or sentence entered
      • Separate out the individual words entered
      • Each individual word should then be added to a list
  • After all of the words have been place in a list
    • Sort the contents of the list
    • Display the contents of the sorted list with each individual word displayed on a separate line
  • Display a message to the user indicating when all of the items in the list have been displayed

The program should:

  • Use variables with meaningful names
  • Display easily understood prompts when collecting user input
  • Have appropriate comments indicating what each part of the program is doing
  • Have a comment area at the beginning of the program identifying the author of the program and the class it was created for

Save the program as a Python module, and submit the program through this assignment.

In: Computer Science

For a LinkedList in Java how do I - Add a method named replace() that takes...

For a LinkedList in Java how do I

- Add a method named replace() that takes in two parameters (the data object to replaced, followed by the one to be inserted) that will remove the first occurrence of the item to be replaced and add the second parameter to the list. The method returns a boolean - true if the item to be replaced was found, false if not

- Add an instance method named showList() (no parameters or return value) that will extract all of the values from the list and display them in order, one per line, followed by another line displaying how many values are currently in the list. If the list is empty, display the message “The list is currently empty” instead

- Overload showList() with an integer parameter which represents how many items to display on each line. The method needs to newline after the last item no matter how many items were displayed (i.e. don’t leave the cursor hanging.)

In: Computer Science

Consider the following database schema: LIKE(person, sport), PRACTICE(person, sport), where person and sport are keys in...

Consider the following database schema:

LIKE(person, sport),

PRACTICE(person, sport),

where person and sport are keys in both tables. The table LIKE gives the sports a person likes, the table PRACTICE gives the sports a person practices. We assume that a person likes at least one sport and practices at least one sport. We assume also that a person does not like a sport if the sport is not listed among the sports that person likes

  1. List the people who practice at least one sport they do not like
  2. List pairs of people who practice at least one common sport
  3. List the people who like all the sports they practice
  4. List the people who practice all the sports they like
  5. List the people who practice all the sports John likes
  6. Who practices the largest number of sport (SQL only)?

In: Computer Science

note: Input-output screen-shot if needed #No-copy paste codes, please. Q) Create a python functions that rotates...

note: Input-output screen-shot if needed #No-copy paste codes, please.

Q) Create a python functions that rotates the elements of a list by one position. Consider a function rotate(a_list, direction) that takes as arguments the list to rotate, and the direction (left or right) of rotation. Rotate the list in place.

Q) Choice of appropriate data structure is an important step in designing algorithms. Suppose a text file contains student records on each line and each record is of the format: Name of Student, Student ID, GPA. Now consider reading that le to create a list of lists, a list of tuples or a tuple of tuples.
(a) If you want to create a report using the data, what data structure would you use?

(b) If you want to modify the name, id or GPA, what data structure would you use?

In: Computer Science

A Wilkinson case study Introduction Businesses must respond to change in order to remain competitive. Developing...

A Wilkinson case study

Introduction

Businesses must respond to change in order to remain competitive. Developing appropriate strategies which allow them to move forward is essential. Wilkinson is a prime example of a business that has responded to changing customer needs throughout its history. It is one of the UK”s long-established retailers of a wide range of food, home, garden, office, health and beauty products.

Growing the business

James Kemsey (JK) Wilkinson opened his first Wilkinson Store in Charnwood Street, Leicester in 1930. After the Second World War, the 1950s saw a rise in the use of labor-saving devices and DIY. Wilkinson responded by making this type of product the focus of its sales.

In the 1960s customers wanted more convenience shopping. Wilkinson started selling groceries and supermarket goods and created the Wilko brand. In the 1980s Wilkinson extended its range of low-cost products to include quality clothing, toys, toiletries and perfumes.

In 1995 it opened a central distribution center in Workshop, serving stores in the north of England and in 2004, a new distribution center opened in Wales. In 2005 Wilkinson launched its Internet shopping service, offering over 800,000 product lines for sale online.

Wilkinson currently has over 300 stores, which carry an average of 25,000 product lines. 40% of these are Wilko 'own-brand' products. The company's target is to see this element grow and to have over 500 stores by 2012.

Competition

Wilkinson's growth places it in the top 30 retailers in the UK. Recently it has faced increasing challenges from competitors, such as the supermarket sector. Wilkinson needed to combat this and identify new areas for growth.

Over two years it conducted extensive market research. This has helped it create a marketing strategy designed to continue growing by targeting a new market segment -the student population.

This case study focuses on how Wilkinson created and implemented this strategy, using the findings of its market research to drive the strategy forward

Marketing strategy

To grow, a business needs to give consumers what they want, at a price they are satisfied with, when they want it and make a profit for the company. Wilkinson commissioned market research which identified key potential for growth in the student sector. It had to develop a strategy for growth that not only covered the specific requirements of this target group, but also linked closely with the company's overall aims and objectives.

The key elements that need to be in place for business planning are:

aims -describe the overall goals of a business

objectives -are steps which managers decide need to be taken in order to achieve the overall aims

strategy -is a plan which outlines all the medium and long-term steps that need to be taken in order to achieve a given target

tactics -are what the business does in the short-term -these respond to opportunities and threats identified when preparing the original strategy

Strategies may be to combat competition, to improve the position of the company in the market or to grow the business.

The type of strategy required will depend upon several factors but the main influences include:

number and power of competitors

company strengths

size of business

financial position

government influences

Marketing strategy aims to communicate to customers the added-value of products and services. This considers the right mix of design, function, image or service to improve customer awareness of the business' products and ultimately to encourage them to buy.

An important tool for helping develop an appropriate marketing strategy is Ansoff's Matrix. This model looks at the options for developing a marketing strategy and helps to assess the levels of risk involved with each option.

Marketing strategies may focus on the development of products or markets. Doing more of what a business already does carries least risk; developing a completely new product for a new audience carries the highest risk both in terms of time and costs.

Based on its research, Wilkinson committed to a market development strategy to sell its products to a new audience of students. This is a medium risk strategy as it requires the business to find and develop new customers. It also carries costs of the marketing campaigns to reach this new group.

The main focus of the strategy was to increase awareness of the brand among students and encourage them to shop regularly at Wilkinson stores.

Market research

Market research is vital for collecting data on which to base the strategy. Market research takes one of two main forms primary research and secondary research.

Primary research (also called field research) involves collecting data first hand. This can take many forms, the main ones being interview, questionnaires, panels and observation

.Secondary research (also called desk research) involves collecting data which already exists. This includes using information from reports, publications, Internet research and company files.

Advantages and disadvantages

Both methods have advantages and disadvantages. The advantages of primary research are that it is recent, relevant and designed specifically for the company's intended strategy. The main disadvantage is that it is more expensive than secondary research and can be biased if not planned well.

Secondary research is relatively cheap, can be undertaken quickly and so enables decision-making sooner. However, secondary research can go out of date and may not be entirely relevant to the business' needs.

Wilkinson undertook primary market research using questionnaires from students across the UK and secondary research using government and university admissions data. The statistics revealed that there were three million potential student customers.They had a combined annual spend of around £9 billion per year.

This research confirmed that the choice of focusing on the student market as a means of growth was valid.

Wilkinson undertook further research to identify how to reach students and persuade them to start shopping at Wilkinson stores. This information was used to formulate a focus strategy. This was aimed specifically at the needs of the student market segment.

Marketing to students

Wilkinson involved 60 universities in research, using questionnaires distributed to students initially in Years 2 and 3 of a range of universities and then to 'freshers' (new students) through the University and Colleges Admission Service. This ensured the widest range of students was included to eliminate bias. It also gave a wide range of responses.

From this initial group, students were asked a second set of questions. Participants were rewarded with Amazon vouchers to encourage a good take-up. The research focused on two areas:

1.student awareness of the Wilkinson brand

2.reasons why students were currently not using the stores regularly

The market research enabled Wilkinson to put together its marketing strategy. The aim was to ensure the student population began shopping at Wilkinson stores early in their student experience. This would help to maintain their customer loyalty to Wilkinson throughout their student years and also to develop them as future customers after university. Repeat business is key to sustained growth.

Promotional tactics

Wilkinson wanted to create satisfied customers with their needs met by the Wilkinson range of products. A marketing campaign was launched which focused on a range of promotional tactics, specifically designed to appeal to university students:

Wilkinson attending freshers' fairs and giving free goody bags with sample products directly to students

direct mail flyers to homes and student halls, prior to students arriving

advertisements with fun theme, for example, showing frying pans as tennis racquets

web banners

offering discounts of 15% with first purchase using the online store

gift vouchers

free wallplanners.

The challenge was to get students into Wilkinson stores. The opportunity was to capture a new customer group at an early stage and provide essential items all year round. This would lead to a committed customer group and secure repeat business.

Outcomes/evaluation

Wilkinson wanted to know what would inspire students to shop at Wilkinson more and what factors would help to attract non-customers. The research provided significant primary information to analyse the effects of the campaign.

Evaluation

Wilkinson used questionnaires collected from the first year undergraduates to gather qualitative data. In addition, Wilkinson obtained quantitative data from various other sources, including:

redemption rates how many people used the discount vouchers when buying

sales analysis how much extra business did the stores handle

footfall in stores analysis how many extra people went into stores

This information helped Wilkinson to develop its plans for future marketing campaigns.

It identified motivation factors for the student audience which would help to encourage future purchase. Key factors included products being cheaper than competitors and easy access to stores. The layout of the store was another major problem affecting repeat visits. 23% of students questioned gave 'distance from university' as a reason for not regularly visiting the store.

These findings have been taken on board by Wilkinson in its future planning of store locations and layouts.

Outcomes

Researching students' opinions after the campaign showed that:

Awareness of Wilkinson brand had significantly risen from 77% to 95% of those interviewed. This brought it in line with Morrison supermarkets, a key competitor.

17% of students who received a goody bag at freshers” fairs used the 15% discount voucher. A further 58% intended to use the voucher. The campaign had either got students to enter the Wilkinson stores or increase their intention to visit the store.

Of particular importance to Wilkinson was that the campaign had made the company more appealing to 67% of students interviewed. This fulfilled one of the main objectives of the campaign and was reinforced by figures from existing students. Prior to the campaign 13% shopped at Wilkinson at least once a month. After the campaign this had risen to 33%.

The results of interviews with fresher students two months after the campaign shows which of the various marketing tactics Wilkinson used with the students had the greatest impact on their awareness.

Conclusion

Wilkinson marketing strategy began with its corporate aim to grow and increase stores across the UK. It was facing increased competition from supermarkets and needed to identify an area to focus on. To pursue a growth strategy, Wilkinson used market research to identify new target customers. This enabled it to prepare marketing strategies to fit the audience.

Primary and secondary research was used to find out customer views regarding its brand.Data indicated the student market segment was a significant area to focus on to achieve market development.

A marketing campaign using data from a follow-up survey was put in place.The campaign showed significant increase in students' levels of awareness about Wilkinson and its products.

It encouraged them either to shop more or to try Wilkinson for the first time. The campaign helped to achieve many of the business' aims, creating increased brand awareness and repeat visits. It also helped to inform the company's future strategies for growth.

Market research gathered will help to formulate future plans for new stores. These will be in line with Wilkinson commitment to providing communities with affordable products across the country.

  1. What is your overall reaction to case and how would you describe the emotional life of the Wilkinson family?
  2. Where did the greatest emotional issues arise, in the family system or in the business system?
  3. How did gender and emotion intersect in the Wilkinson family?

In: Economics

Python Programming- 9.11 S80 MT Practice1 #This is a template for practicing mutability and conversion #Create...

Python Programming- 9.11 S80 MT Practice1

#This is a template for practicing mutability and conversion
#Create and assign the following list of numbers to a list data type and variable name: 88.5, 90, 75, 70, 85.6
#convert the list to a tuple and assign the tuple a different variable name
#Ask the user for a grade and convert it to a float type (no prompt) and assign it to a new variable name
#append the user entered grade to the list
#update the tuple to reflect the user entered grade (Tip, replace the entire tuple with the list converted to a tuple)
#compute the current average grade using the tuple
#Display the average that you calculated in the previous line using the following format:
#Your average score is [calculated average]. (Tip: use the + concatenator and convert the average to a string)
#Ask the user for another grade (no prompt), convert it to an integer and assign it to a new variable name
#replace the third grade in the list with the most recently entered grade (Tip, you'll need to use the index)
#remove the second grade from the list (Tip, you'll need to use the index and the pop method)
#update the tuple to reflect these recent changes to the list (Tip: replace the entire tuple with the converted list)
#compute the current average grade using the tuple (Tip: divide the tuple sum by the tuple length)
#Display the latest average that you calculated in the previous line using the following format:
#Your updated score is: [calculated average]. (Tip: use the + concatenator and convert the average to a string)
#Display the following statement using the + concatenator using the latest values for sum, length and average:
#(Tip: make sure all the three variables have been converted to strings)
#With a total of [sum of tuple] for [length of tuple] assignments your average score is [tuple average]!

In: Computer Science

1) Modify all methods that have used count, especially rewrite length method by traversing the list...

1) Modify all methods that have used count, especially rewrite length method by traversing the list and counting no. of elements.

import java.util.*;
import java.io.*;

public class Qup3 implements xxxxxlist {// implements interface
   // xxxxxlnk class variables
   // head is a pointer to beginning of rlinked list
   private node head;
   // no. of elements in the list
   // private int count;

// xxxxxlnk class constructor
   Qup3() {
       head = null;
       count = 0;
   } // end Dersop3 class constructor

   PrintStream prt = System.out;

   // class node
   private class node {
       // class node variables
       int data;
       node rlink;

       // class node constructor
       node(int x) {
           data = x;
           rlink = null;
       } // class node constructor
   } // end class node

   // isEmpty() returns true if list is empty, false otherwise.
   public boolean isEmpty() {
       return (count == 0);
   } // end isEmpty

   // length() returns number of list elements.
   public int length() {
       return count;
   } // end length

   // insert x at position p, for successful insertion:
   // list should not be full and 1 <= p <= count+1
   public int insert(int x, int p) {
       int i;
       prt.printf("\n Insert %4d at position %2d:", x, p);
      
       if (p < 1 || p > ( count + 1) ) {
           return 0;
       }
       node tmp = new node(x);
       // p == 1 Inserts x to front of list,
       // is a special case where head changes
       if (p == 1) {
           tmp.rlink = head;
           head = tmp;
       } else {// traverse the list till element before p
           node current = head;
           // Find node before p
           for (i = 2; i < p; i++, current = current.rlink)
               ; // end for
           // insert node after cur node
           tmp.rlink = current.rlink;
           current.rlink = tmp;
       }
       count++;
       return 1; // successful insertion
   } // end insert

   // delete x at position p, for successful deletion:
   // list should not be empty and 1 <= p <= count
   public int delete(int p) {
       prt.printf("\n Delete element at position %2d:", p);
       if (isEmpty() || p < 1 || p > length())
           return 0; // invalid deletion
       int count = length();
       node tmp = head;
       // p == 1 deletes front of list.
       // This is a special case where head changes
       if (p == 1) { // Delete Front of List
           head = head.rlink;
           tmp.rlink = null;
           } else { // Find node before p
           node current = head;
           for (int i = 2; i < p; i++, current = current.rlink; ) ;// end for
           // Delete node after current node
           tmp = current.rlink;
           current.rlink = tmp.rlink;
           tmp.rlink = null; // delete tmp;
           }
       count--;
       return 1; // successful deletion
   } // end delete

   // sequential serach for x in the list
   // if successful return position of x in the
   // list otherwise return 0;
   public int searchx(int x) {
       prt.printf("\n search for %4d:", x);
       // complete the rest
       //.........
       return 0;
   } // end searchx

   // print list elements formatted
   public void printlist() {
       prt.print("\n List contents: ");
       for (node current = head; current != null; current = current.rlink)
           prt.printf("%4d, ", current.data);
      
       // end for
   } // end printlist

   public static void main(String args[]) throws Exception {
       int j, m, k, p, x, s;
       try {
           // open input file
           Scanner inf = new Scanner(System.in);
           // Create a List of type Integer of size n
           Qup3 lst = new Qup3();

           // read no. of elements to insert
           m = inf.nextInt();
           System.out.printf("\n\tInsert %2d elements in the list.", m);
           for (j = 1; j <= m; j++) {
               x = inf.nextInt(); // read x
               p = inf.nextInt(); // read position

               s = lst.insert(x, p); // insert x at position p
               if (s == 1)
                   System.out.printf(" Successful insertion.");
               else
                   System.out.printf(" %2d is invalid position for insertion.", p);
           } // end for
           lst.printlist(); // print linked list elements
           // read no. of elements to search in the list
           m = inf.nextInt();
           System.out.printf("\n\tSearch for %d elements in the list.", m);
           for (j = 1; j <= m; j++) {
               x = inf.nextInt(); // read x
               p = lst.searchx(x); // search for x
               if (p > 0)
                   System.out.printf(" found at position %d.", p);
               else
                   System.out.printf(" is not found.");
           } // end for
               // read no. of positions to delete from list
           m = inf.nextInt();
           System.out.printf("\n\tDelete %d elements from list.", m);
           for (j = 1; j <= m; j++) {
               p = inf.nextInt(); // read position
               s = lst.delete(p); // delete position p
               if (s == 1)
                   System.out.printf(" Successful deletion.");
               else
                   System.out.printf(" %2d is invalid position for deletion.", p);
           } // end for
           lst.printlist(); // print array elements
           inf.close(); // close input file
      
       } catch (Exception e) {
           System.out.print("\nException " + e + "\n");
       }
   } // end main
} // end class xxxxxlnk

In: Computer Science

(C++) All programs will be included! This lab gives you a little practice with linked lists...

(C++) All programs will be included!

This lab gives you a little practice with linked lists

·Debug insertSorted() and implement sorted() in numberlist.cpp

·Hint: insertSorted() is just missing a few parts. What is in the function can work fine once you add the right code, though you are free to rewrite it

·You need to have main.cpp, numberlist.h and numberlist.cpp in this project, and if you are using Code::Blocks, remember to set the Build Options to indicate you want to use C++11 or later. The expected output for the final program is:

Test driver to check insertSorted() and sorted() methods of NumberList class

Is empty list in ascending order? true

Displaying list first time:

3.9

5.2

Displaying list second time:

3.9

4.6

5.2

8.4

Is list in ascending order? true

3.9

4.6

5.2

8.4

7.1

Is list in ascending order? False

MAIN.CPP

#include <iostream>
#include "numberlist.h"

using namespace std;

int main()
{
    NumberList list;
    cout << "Test driver to check insertSorted() and sorted() methods of NumberList class"
         << endl << endl;

    cout << "Is empty list in ascending order? "
         << boolalpha << list.sorted() << endl;

    list.insertSorted(5.2);
    list.insertSorted(3.9);
    cout << "Displaying list first time: " << endl;
    list.displayList();
    list.insertSorted(8.4);
    list.insertSorted(4.6);
    cout << "Displaying list second time: " << endl;
    list.displayList();
    cout << "Is list in ascending order? "
         << list.sorted() << endl;
    list.appendNode(7.1);
    list.displayList();
    cout << "Is list in ascending order? "
         << list.sorted() << endl;

    return 0;
}

NUMBERLIST.CPP

#include "numberlist.h"
#include <iostream>

using namespace std;

const double NumberList::EPSILON = 0.000001;


// insert so values are in ascending order
void NumberList::insertSorted(double num) {
    ListNode * newNode = new ListNode;
    newNode->value = num;
    newNode->next = nullptr;

    if (num < head->value) {
        newNode->next = head;
        head = newNode;
    }
    // declare outside for loop so we can use iter after the loop
    ListNode * iter = head;
    for (; nullptr != iter->next; iter = iter->next) {
        if (num < iter->next->value) {
            // insert between iter and iter->next
            iter->next = newNode;
            return;
        }
    }
}


/** destructor to free memory for all elements in list */
NumberList::~NumberList()
{
    ListNode * nodePtr, * nextNode;

    nodePtr = head;
    while (nodePtr != NULL) {
        nextNode = nodePtr->next;
        delete nodePtr;
        nodePtr = nextNode;
    }
}

/** display list to console
    rewritten to show similarity to working with arrays */
void NumberList::displayList() const {
    for (ListNode *nodePtr = head;
         nodePtr != NULL;
         nodePtr = nodePtr->next)
        cout << nodePtr->value << endl;
}

void NumberList::insertNode(double num) {
    ListNode * node = new ListNode;
    node->next = head;
    node->value = num;
    head = node;
}

/** add to end of list */
void NumberList::appendNode(double num) {
    // cannot put num into list directly
    // must construct a node
    ListNode *newNode;

    // use this to go through list
    // serves same purpose as loop counter
    // for array processing
    ListNode *nodePtr;

    newNode = new ListNode;
    newNode->value = num;
    // always have to initialize the pointer
    newNode->next = NULL;

    // usually best to handle special cases
    // first
    if (!head) // like (NULL == head)
        head = newNode;
    else {
        nodePtr = head;
        /** should make sure you understand why the condition
            checks nodePtr->next instead of nodePtr */
        while (nodePtr->next)   // same as (nodePtr->head != NULL)
            nodePtr = nodePtr->next;

        // the actual appending
        nodePtr->next = newNode;
    }
}

// delete a value from the list
void NumberList::deleteNode(double num) {
    ListNode * nodePtr;
    ListNode * previousNode;

    // handle special case first
    if (head->value == num) {
        // save pointer to 2nd element
        nodePtr = head->next;
        // free first element's memory
        delete head;
        head = nodePtr;
    }
    else {
        nodePtr = head;

        while (nodePtr != NULL && nodePtr->value != num) {
            previousNode = nodePtr;
            nodePtr = nodePtr->next;
        }

        /** if nodePtr is not at the end of the list,
           (What would that mean?)
           link the previous node to the node after nodePtr,
           then delete nodePtr
           */
        if (nodePtr) {
            previousNode->next = nodePtr->next;
            delete nodePtr;
        }
    }
}

numberlist.h

// a basic linked list class from Gaddis, ch. 17.2
#ifndef NUMBERLIST_H
#define NUMBERLIST_H
// replacing NULL by nullptr -- if you are using Code::Blocks,
// remember to set the build option that you are using C++11 or later

class NumberList
{
    private:
        // adding this for double comparison
        static const double EPSILON;

        struct ListNode {
            double value;
            ListNode *next;
        };
        ListNode * head; //!< points to start of list

    public:
        /** Default constructor */
        NumberList() {
            head = nullptr;
        }
        /** Default destructor */
        ~NumberList();

        // standard list operations
        // add to end of list
        void appendNode(double);
        // inserts in order
        void insertNode(double);
        void deleteNode(double);
        // insert so values are in ascending order
        // NOTE: if we really wanted this, we should remove
        // insertNode() and appendNode()
        // deleteNode() could stay
        void insertSorted(double);
        // returns true if sorted, false if not
        bool sorted() const;

        void displayList() const;
};

#endif // NUMBERLIST_H

In: Computer Science

/** * This class maintains an arbitrary length list of integers. * * In this version:...

/**
* This class maintains an arbitrary length list of integers.
*
* In this version:
* 1. The size of the list is *VARIABLE* after the object is created.
* 2. The code assumes there is at least one element in the list.
*
* This class introduces the use of structural recursion.
*
* @author Raymond Lister
* @version May 2016
*
*/
public class ListOfNVersion03PartB
{   
private int thisNumber; // the number stored in this node
private ListOfNVersion03PartB next; // forms a linked list of objects
  
private final int nodeID; // a unique ID for each object in the list
  
private static int nodeCount = 0; // the number of list objects that have been created

/**
* This constructor initializes the list to the same values
* as in the parameter.
*
* @param element the initial elements for the list
*/
public ListOfNVersion03PartB(int num)
{
thisNumber = num;
next = null;
  
++nodeCount;
nodeID = nodeCount;

} // constructor(int num)

/**
* @param num the multiple values to be stored in the list, in that order
*/
public ListOfNVersion03PartB(int [] num)
{
this(num[0]); // in this context, "this" invokes the other constructor

for (int i=1 ; i<num.length ; ++i)
insertLast(num[i]);

} // constructor(int [] num)

/**
* @return the first element in the list
*/
public int getFirst()
{
return thisNumber;
  
} // method getFirst
  
/**
* prints this object
*/
public void printNode()
{
System.out.print("[" + nodeID + "," + thisNumber + "]->");

} // method printListNode

/**
* stringifies this object
*/
public String toStringNode()
{
return "[" + nodeID + "," + thisNumber + "]->";

} // method toStringNode


/**
* form a string from the tail of a list
*/
private String toStringTail()
{
String s = toStringNode();

if ( next != null )
s = s + next.toStringTail();

return s;

} // method toStringTail

/**
* @return A summary of the contents of the whole list.
*/
public String toString()
{
String s = toStringNode();

if ( next != null )
s = s + next.toStringTail();

return s;

} // method toString

/**
* @return the sum of the elements of the array
*/
public int sum()
{
if( next == null )
return thisNumber;
else
return thisNumber + next.sum();

} // method sum

/**
* @return the number of times the replacement was made (i.e. 0 or 1)
*
* @param replaceThis the element to be replaced
* @param withThis the replacement
*/
public int replaceOnce(int replaceThis, int withThis)
{

return 999;

} // method replaceOnce

/**
* @return the value of the smallest element in the list
*/
public int minVal()
{
return 999;

} // method minVal

/**
* Inserts an element in the first position. The elements already in the
* list are pushed up one place.
*
* @param newElement the element to be inserted
*/
public void insertFirst(int newElement)
{
ListOfNVersion03PartB temp = new ListOfNVersion03PartB(thisNumber);
temp.next = next;
next = temp;
thisNumber = newElement;

} // method insertFirst

/**
* Inserts an element in the last position. The pre-existing elements in the
* list are unaffected.
*
* @param newElement the element to be inserted
*/
public void insertLast(int newElement)
{
// add and/or modify code to complete the method

if ( next == null )
next = new ListOfNVersion03PartB(newElement);
else
next.insertLast(newElement);

} // method insertLast

/**
* No change if there is only one element in the list. Otherwise, it moves up one place all
* elements in the list, by overwriting each "thisNumber" with "next.thisNumber", thus
* removing the first value in the list. The last node in the list is removed.
*/
public void shuffleUp()
{
System.out.println("This method is NOT part of the lab test");
System.out.println("It will probably be part of the assignment");
  
} // method shuffleUp

/*
* @return the number of deletions made (i.e. 0 or 1)
*
* @param element the element to be deleted
* @param predecessor a reference to the previous node in the linked list
* i.e. the node where "next" points to this node
*/
private int delete2(int element, ListOfNVersion03PartB predecessor)
{
System.out.println("This method is NOT part of the lab test");
System.out.println("It will probbaly be part of the assignment");
return 99; // delete this line and complete the method for the assignment

} // method delete2

/**
* @return the number of deletions made (i.e. 0 or 1)
*
* @param element the element to be deleted
*/
public int delete(int element)
{
if ( (thisNumber == element) && (next == null) )
{
System.out.println("Error when attempting to delete '" + element + "'. The list must contain at least one element");
return 0;
}

if ( thisNumber == element )
{
// if thisNumber == element is true then the first "if" statement implies that next != null
thisNumber = next.thisNumber;
next = next.next;
return 1;
}

if ( next == null )
{
// if next == null is true then the first "if" statement implies that thisNumber != element
return 0;
}

return next.delete2(element, this);

} // method delete
public static void main(String[] args)
{
int [] a = {3,7,1,7};
ListOfNVersion03PartB list = new ListOfNVersion03PartB(a);
System.out.println(list.toString());
int n = list.getFirst();
System.out.println("First element is: " + n);
System.out.println(list.toString());
int m = list.sum();
System.out.println("The sum of the values is: " + m);
int ro1 = list.replaceOnce(2,3);
System.out.println("Number of replacements of value 2 with 1 is: " + ro1);
System.out.println(list.toString());
int ro2 = list.replaceOnce(3,4);
System.out.println("Number of replacements of value 3 with 4 is: " + ro2);
System.out.println(list.toString());
int ro3 = list.replaceOnce(7,8);
System.out.println("Number of replacements of value 7 with 8 is: " + ro3);
System.out.println(list.toString());
int mv = list.minVal();
System.out.println("Minimum value is: " + mv);
int ro4 = list.replaceOnce(1,7);
System.out.println("Number of replacements of value 3 with 4 is: " + ro4);
System.out.println(list.toString());
int ro5 = list.replaceOnce(8,1);
System.out.println("Number of replacements of value 3 with 4 is: " + ro5);
System.out.println(list.toString());
list.insertFirst(2);
System.out.println(list.toString());
}

} // class ListOfNVersion03PartA

In: Computer Science