Write a function template sort that takes two references to generic objects and switches them if the first argument is larger than the second. It is only assumed that operator<() and a default constructor are defined for the objects considered.
In: Computer Science
Mobile and wireless devices are being increasingly used in the Business Administration and Management Industry. write a three-page paper that discusses three (3) mobile apps that could be used in business management. How do these apps increase the productivity of business managers and their customers? Are there any drawbacks involved in using these apps?
Your paper should include:
1. A three-page discussion of the problem.
2. A conclusion and list of all academic references used.
In: Computer Science
Question 2 : Aggregate Scores: Write a program that opens 2
files, quiz.txt, and hw.txt. The program will
read each file and aggregate these values into the associated class
variables. Using a list of Students, the
program keeps track of each student's scores. The program will then
write out to the scores.txt file, the
students score in homework, quizzes, and their overall score.
Related input files.
Each student is supposed to have 3 quiz scores and 3 homework
scores. If a score is not present in the file,
then it defaults to 0 points.
Files will be formatted as a Name followed by a tab followed by a
score.
Note: Refer to the Pre-Lab for the student class, and how to work
with classes.
How to Calculate Grades:
Homework Percent can thus be calculated as:
Homework_Points/3
Quiz Percent can be calculated in the same way:
Quiz_Points/3
Student’s overall score will be computed using the following
formula
HW_Score_Percent * .5 + Quiz_Score_Percent * .5
These scores work as each assignment is out of 100. Thus the
homework percent is calculated as
hw_percent = student.HW/300 * 100, which equals hw_percent =
student.HW/3
Required Design Schematic:
You must use the Student class. You must use a list of students.
You must not use global variables.
● Write a function find_student(student_list, name)
o Either returns a student or an index to the student in the
list
o Should return None if a student with name is not found
● Write a function get_HW_Scores(file_name, student_list)
o Opens the file
o Reads the file
▪ Divide the line into a name and score
▪ Finds the student
▪ Adds the score to the students homework score
o Closes the file
● Write a function get_Quiz_Scores (file_name, student_list)
o Opens the file
o Reads the file
▪ Divide the line into a name and score
▪ Finds the student
▪ Adds the score to the students quiz score
o Closes the file
● Write a function assign_grade(score)
o Returns a string containing a letter grade matching the percent,
see the week 3 lab for scoring
brackets
o Feel free to copy your lab function for use here
● Write a function output_Scores(student_list)
o Opens the file scores.txt
o Loops over every student in the list
▪ Writes the students name + "\n"
▪ Writes "HW_Percent: " + str(hw_percent) + "% \n"
▪ Writes "Quiz_Percent: " + str(quiz_percent) + "% \n"
▪ Calculate num to be the overall score for the student
▪ Writes "Overall: " + str(num) + "%" "(" + assign_grade(num) + ")"
+ "\n"
o Closes the file
● Write a function main to call the above and other functions as
needed to complete the task
Note: You are allowed to create as many helper functions as you
need.
Sample Input File:
Apple 100
Cube 69
Apple 100
Cube 50
Apple 100
Circle 85
Circle 89
Circle 88
Sample Output File:
Apple
HW_Percent: 100.0%
Quiz_Percent: 83.33333333333333%
Overall: 91.66666666666666%(A-)
Cube
In: Computer Science
Research the internet for companies that have executed data science projects. Pick one company and describe a possible data science life cycle for that project. Make use of both information that you have researched as well as the information provided in the data science life cycle models.
In: Computer Science
Write a Java Program using the following instruction:
Create the following 3 methods that calculate and display the sum or product of the integers from 1 to the number input.
getNum Receives no input. Prompts the user to enter a number, use a loop to validate. Returns the result.
calcSum Receives an integer as input. Calculates the sum of the integers from 1 to this number. Returns the result.
calcProd Receives an integer as input. Calculates the product of the integers from 1 to this number. Returns the result.
Main should: Prompt for a character that determines if you want to calculate the sum (‘S’ or ‘s’) or product (‘P’ or ‘p’). You should use a switch to process the choices. Upper and lower case values should work the same way. Use default to give an error message if anything else is entered. (You can input as String or char)
if a valid option is entered, use getNum to prompt for the number
Note that calcSum and calcProduct RETURN the result to main, and the output is printed in main. For example, if you input 5 as the number, and ‘S’, the program should calculate 1 + 2 + 3 + 4 + 5 and display the sum as 15. If you input 5 and ‘P’ the program should calculate 1 x 2 x 3 x 4 x 5 and display the product as 120. . The process should repeat as long as the user wants to continue. This loop should be in main. DO NOT use System.exit command to end the program. . See sample output below.
Enter S for sum, P for prod:z
Invalid choice Again(y/n)? y
Enter S for sum, P for prod:s
Enter an integer greater than 1: 1
Must be greater than 1, re-enter: -3
Must be greater than 1, re-enter: 3
The sum of the numbers from 1 to 3 is 6 Again(y/n)? y
Enter S for sum, P for prod:p
Enter an integer greater than 1: 4
The product of the numbers from 1 to 4 is 24 Again(y/n)? n
In: Computer Science
Why should a time-based authentication system invalidate the current password on a successful authentication?
In: Computer Science
The files provided contain syntax and/or logic errors. In each case, determine and fix the problem, remove all syntax and coding errors, and run the program to ensure it works properly.
3.
public abstract class DebugBoat
{
String boatType = new String();
int passengers
String power = new String();
public FebugBoat(String bt)
{
boatType = bt;
}
public boolean equals(otherBoat)
{
boolean result;
if((passengers == otherBoat.passengers) && (power.equals(otherBoat.power)))
result = true;
else
result = true;
return result
}
public String toString()
{
return("This " + boatType + "boat carries " + passengers +
" and is powered by + power);
}
public abstract void setPower();
public abstract void setPassengers();
}
// Two boats should be equal
// if they hold the same number of passengers
// and also have the same power source
public class DebugEleven3
{
public static void Main(String args[])
{
DebugRowboat redBoat = new DebugRowboat();
DebugRowboat blueBoat = new DebugRowboat();
System.out.print("The two boats are");
if(redBoat = blueBoat)
System.out.println(" equal");
else
(" not equal");
}
}
public class DebugRowboat extends DebugBoat
{
public DebugRowboat()
{
super("row");
setPower();
}
public void setPassengers()
{
super.passengers = 2;
}
public void setpower()
{
super.power = "oars";
}
}
4.
public abstract class DebugBoat
{
String boatType = new String();
int passengers
String power = new String();
public FebugBoat(String bt)
{
boatType = bt;
}
public boolean equals(otherBoat)
{
boolean result;
if((passengers == otherBoat.passengers) && (power.equals(otherBoat.power)))
result = true;
else
result = true;
return result
}
public String toString()
{
return("This " + boatType + "boat carries " + passengers +
" and is powered by + power);
}
public abstract void setPower();
public abstract void setPassengers();
}
// Creates and displays an array of boats -
// some are rowboats; some are ocean liners
import java.util.*;
public class DebugEleven4
{
static Scanner input = new Scanner(System.in);
static DebugBoat[] boatArray = new DebugBoat[5];
public static void main(String[] args)
{
buildArray;
displayArray;
}
public static void buildArray()
{
char boatType;
for(x = 0; x < boatArray.length; ++x)
{
boatType = getBoat();
if(boatType =='r')
boatArray[x] = DebugRowboat();
else
boatArray[x] = new DebugOceanLiner();
}
}
public static char getBoat()
{
String boatType;
System.out.println("Enter r for rowboat; o for ocean liner ");
boatType = input.next();
return boatType.charAt(0);
}
public static void displayArray()
{
for(int x = 0; x < boatArray.length)
System.out.println("Boat #" + (x + 1) + " " +
boatArray[x].toString());
}
}
public class DebugOceanLiner extends DebugBoat
{
public DebugOceanLiner()
{
super("ocean liner ");
setPassengers();
}
public void setPassengers()
{
super.passengers = 2400;
}
public void setPower()
{
superpower = "four engines";
}
}
public class DebugRowboat extends DebugBoat
{
public DebugRowboat()
{
super("row");
setPower();
}
public void setPassengers()
{
super.passengers = 2;
}
public void setpower()
{
super.power = "oars";
}
}
In: Computer Science
C++, Write an Exception Class for the Student class you created in the initial project you worked on. Create a try catch block that would catch negative numbers for the Student id.
// header file
#pragma once
#include<iostream>
#include<string>
constexpr auto MAX = 100;
using namespace std;
class Roster1
{
private:
string student_name;
int student_id;
int final_grade;
string letter_grade;
public:
//constroctor
Roster1();
//destroctor
~Roster1();
// setters
void setStudents(string newname, int newgade, int
newid);
void validatename(string newname);
void setstudent_name(string newname);
void setstudent_id(int newid);
void setfinal_grade(int newgrade);
void setletter_grade(int newgrade);
void validateGrade(int newgrade);
int validateID(int newid);
//getters
string getstudent_name();
int getfinal_grade();
string getletter_grade();
int getstudent_id();
//int getStudents();
//void getData();
};
// Class definition (implementation)
#include "Roster1.h"
Roster1::Roster1()
{
student_name = "";
student_id = 0;
final_grade = 0;
}
Roster1::~Roster1()
{
}
void Roster1::validateGrade(int newgrade) {
final_grade = newgrade;
if (final_grade >= 0 && final_grade <= 100);
else
cout << "Enter a Valid grade.";
}
//int Roster1::validateID(int newid) {
//}
void Roster1::validatename(string newname) {
student_name = newname;
bool beta = false;
int nameLength = student_name.length();
for (int i = 0;i < nameLength;i++)
{
if (isalpha(student_name[i]))
{
cout <<
student_name[i] << " is a letter.\n";
}
else
{
cout <<
"First instance of a non char is at index "
<<
student_name.find_first_not_of("abcdefghijklmnopqrstuvwxyz", 0)
<< ".\n";
beta =
true;
if (beta ==
true)
{
cout << "Enter a name with characters
only.\n";
cin >> student_name;
}
}
}
}
void Roster1::setStudents(string newname, int newgrade, int
newid)
{
student_name = newname;
student_id = newid;
final_grade = newgrade;
}
void Roster1::setstudent_name(string newname) {
student_name = newname;
}
void Roster1::setstudent_id(int newid) {
student_id = newid;
}
void Roster1::setfinal_grade(int newgrade) {
final_grade = newgrade;
}
void Roster1::setletter_grade(int newgrade) {
if (final_grade >= 93 && final_grade <=
100)
letter_grade = "A";
else if (final_grade >= 90 && final_grade <= 92)
letter_grade = "A-";
else if (final_grade >= 87 && final_grade <= 89)
letter_grade = "B+";
else if (final_grade >= 83 && final_grade <= 86)
letter_grade = "B";
else if (final_grade >= 80 && final_grade <= 82)
letter_grade = "B-";
else if (final_grade >= 77 && final_grade <= 79)
letter_grade = "C+";
else if (final_grade >= 73 && final_grade <= 76)
letter_grade = "C";
else if (final_grade >= 70 && final_grade <= 72)
letter_grade = "C-";
else if (final_grade >= 67 && final_grade <= 69)
letter_grade = "D+";
else if (final_grade >= 60 && final_grade <= 66)
letter_grade = "D";
else
letter_grade = "F";
}
string Roster1::getstudent_name() {
return student_name;
}
int Roster1::getfinal_grade() {
return final_grade;
}
string Roster1::getletter_grade() {
return letter_grade;
}
int Roster1::getstudent_id() {
return student_id;
}
// main
#include<iostream>
#include<string>
#include "roster1.h"
using namespace std;
int menu() {
int c;
while (true)
{
// created a menu outside of the
main, it returns the value that the user input to the main
cout << "This program will
record a student record" << endl;
cout << "1). Add the Student
Record." << endl;
cout << "2). Delete Student Record." << endl;
cout << "3). Display
Student Record." << endl;
cout << "4). Display average
grade" << endl;
cout << "5). Exit" << endl;
cout << "Please enter the choice (1 to 5):";
cin >> c;
if (c >= 1 && c <= 5)
return c;
else
continue;
}
}
int main()
{
Roster1 std[100]; // array
int choice, student_count = 0, flag = 0;
string name;
int id, grade, sum = 0;
double average = 0;
bool con = true;
while (con) // while loop
{
choice = menu(); // brings the
value from int menu and declare it to choice
switch (choice)
{
case 1:
cout << "Enter Student
name:";
cin >> name;
std[student_count].validatename(name);
cout << "Enter Student
ID:";
cin >> id;
cout << "Enter the
Grade:";
cin >> grade;
std[student_count].validateGrade(grade);
std[student_count].setletter_grade(grade);
std[student_count].setStudents(name, grade, id);
student_count++;
cout << "Student " <<
student_count + 0 << " Stored Successfully " << endl;
// display to the user the amount of student so far
break;
case 2:
cout << "Enter the student id you want to delete:";
cin >> id;
for (int i = 0;i < student_count;i++)
{
if (std[i].getstudent_id() == id)
{
//std[i].~student();
flag = 1;
cout << "Student Record deleted;" << endl;
break;
}
}
if (flag == 0)
{
cout << "Student not found!" << endl;
}
break;
case 3:
cout << "Enter the student id you want display record:";
cin >> id;
flag = 0;
for (int i = 0;i < student_count; i++)
{
if (std[i].getstudent_id() == id)
{
cout << "Student name\t:" << std[i].getstudent_name() << endl;
cout << "Student id\t:" << std[i].getstudent_id() << endl;
cout << "Student final grade\t:" << std[i].getfinal_grade() << endl;
cout << "Student Letter Grade\t:" << std[i].getletter_grade() << endl;
flag = 1;
break;
}
}
if (flag == 0)
{
cout << "Student not found!" << endl;
}
break;
case 4:
average =
0;
sum = 0;
for (int i = 0;
i < student_count;i++) {
sum = sum + std[i].getfinal_grade();
}
average =
((double)sum) / student_count;
cout <<
"average grade of the class is: " << average <<
endl;
break;
case 5:
con = false;
// makes con false to finish the program
break;
}
}
return 0;
In: Computer Science
The term “backup” is often used in computing to talk about making copies of data files so that they can be replaced in case of loss. But in the case of businesses, it is not just being able to replace data that should concern managers. Explain how a business backup plan needs to be much more comprehensive.
In: Computer Science
Must be written in c++
Must display comments
Write a program that will read monthly sales into a dynamically allocated array allocated array of double values.
Your program should:
- prompt the user to enter the size of the array ( that is the
number of monthly sales)
- dynamically allocate an array large enough to hold the number of
monthly sales given
by the user
- find and print the yearly sum of all the monthly sales
Note: don’t forget to deallocate memory!
Sample Run:
Enter the number of monthly sales to be input: 4
Enter the monthly sales for month 1: 1290.89
Enter the monthly sales for month 2: 905.95
Enter the monthly sales for month 3: 1567.98
Enter the monthly sales for month 4: 994.83
The total sales for the year is: $4759.65
In: Computer Science
In C++ I just need a MAIN that uses the steps and uses the functions and class given below.
Implement the BinarySearchTree ADT in a file BinarySearchTree.h exactly as shown below.
// BinarySearchTree.h
// after Mark A. Weiss, Chapter 4, Dr. Kerstin Voigt
#ifndef BINARY_SEARCH_TREE_H
#define BINARY_SEARCH_TREE_H
#include
#include
using namespace std;
template
class BinarySearchTree
{
public:
BinarySearchTree( ) : root{ nullptr }
{
}
~BinarySearchTree( )
{
makeEmpty();
}
const C & findMin( ) const
{
assert(!isEmpty());
return findMin( root )->element;
}
const C & findMax( ) const
{
assert(!isEmpty());
return findMax( root )->element;
}
bool contains( const C & x ) const
{
return contains( x, root );
}
bool isEmpty( ) const
{
return root == nullptr;
}
void printTree( ) const
{
if( isEmpty( ) )
cout << "Empty tree" << endl;
else
printTree( root );
}
void makeEmpty( )
{
makeEmpty( root );
}
void insert( const C & x )
{
insert( x, root );
}
void remove( const C & x )
{
remove( x, root );
}
private:
struct BinaryNode
{
C element;
BinaryNode* left;
BinaryNode* right;
BinaryNode( const C & theElement, BinaryNode* lt, BinaryNode* rt )
: element{ theElement }, left{ lt }, right{ rt } { }
};
BinaryNode* root;
// Internal method to insert into a subtree.
// x is the item to insert.
// t is the node that roots the subtree.
// Set the new root of the subtree.
void insert( const C & x, BinaryNode* & t )
{
if( t == nullptr )
t = new BinaryNode{ x, nullptr, nullptr };
else if( x < t->element )
insert( x, t->left );
else if( t->element < x )
insert( x, t->right );
else
; // Duplicate; do nothing
}
// Internal method to remove from a subtree.
// x is the item to remove.
// t is the node that roots the subtree.
// Set the new root of the subtree.
void remove( const C & x, BinaryNode* & t )
{
if( t == nullptr )
return; // Item not found; do nothing
if( x < t->element )
remove( x, t->left );
else if( t->element < x )
remove( x, t->right );
else if( t->left != nullptr && t->right != nullptr ) // Two children
{
t->element = findMin( t->right )->element;
remove( t->element, t->right );
}
else
{
BinaryNode* oldNode = t;
t = ( t->left != nullptr ) ? t->left : t->right;
delete oldNode;
}
}
// Internal method to find the smallest item in a subtree t.
// Return node containing the smallest item.
BinaryNode* findMin( BinaryNode* t ) const
{
if( t == nullptr )
return nullptr;
if( t->left == nullptr )
return t;
return findMin( t->left );
}
// Internal method to find the largest item in a subtree t.
// Return node containing the largest item.
BinaryNode* findMax( BinaryNode* t ) const
{
if( t != nullptr )
while( t->right != nullptr )
t = t->right;
return t;
}
// Internal method to test if an item is in a subtree.
// x is item to search for.
// t is the node that roots the subtree.
bool contains( const C & x, BinaryNode* t ) const
{
if( t == nullptr )
return false;
else if( x < t->element )
return contains( x, t->left );
else if( t->element < x )
return contains( x, t->right );
else
return true; // Match
}
void makeEmpty( BinaryNode* & t )
{
if( t != nullptr )
{
makeEmpty( t->left );
makeEmpty( t->right );
delete t;
}
t = nullptr;
}
void printTree( BinaryNode* t) const
{
if( t != nullptr )
{
printTree( t->left);
cout << t->element << " - ";
printTree( t->right);
}
}
};
#endif
:Program your own file lab07.cpp in which your main() function will test the new data structure.
public:
void printInternal()
{
print_Internal(root,0);
}
private:
void printInternal(BinaryNode* t, int offset)
{
if (t == nullptr)
return;
for(int i = 1; i <= offset; i++)
cout << "...";
cout << t->element << endl;
printInternal(t->left, offset + 1);
printInternal(t->right, offset + 1);
}
The expected result:
insert the values (stop when entering 0): 10 5 20 3 22 6 18 7 9 13 15 4 2 1 19 30 8 0 print the values: 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 - 13 - 15 - 18 - 19 - 20 - 22 - 30 - Print the tree: 10 ...5 ......3 .........2 ............1 .........4 ......6 .........7 ............9 ...............8 ...20 ......18 .........13 ............15 .........19 ......22 .........30 remove the values (stop when entering 0): 1 11 2 12 3 13 0 print the values: 4 - 5 - 6 - 7 - 8 - 9 - 10 - 15 - 18 - 19 - 20 - 22 - 30 - Print the tree: 10 ...5 ......4 ......6 .........7 ............9 ...............8 ...20 ......18 .........15 .........19 ......22 .........30
In: Computer Science
M11 Discussion - Data Security
Data security is a concern every day for information technology professionals. Users, even information technology professionals move data from point to point on a regular basis and often this requires some form of mobility. For this discussion, please address the points listed below. If you use web sources, include the complete URL to the article.
Each student will be responsible for responding to the discussion question by Wednesday with a word count of at least 250 words.
In: Computer Science
Write a JAVA program that prompts the user to enter a character c that represents a binary digit (a bit!). (Recall that c can be only “0” or “1.”) Your program must use the character type for the input. If the user enters a character “x” that is not a bit, you must print out the following error message: “The character x is invalid: x is not a bit.” If the character c is a bit, your main program must print out its value in decimal. Example 1: If the user enters the character “0,” your program must print out the value 0. Example 2: If the user enters the character “1,” your program must print out the value 1. Example 3: If the user enters the character “B,” your program must print out the following error message: “The character B is invalid: B is not a bit.”
In: Computer Science
1.) First Question on Class – the class Circle Given the code below, modify it so that it runs. This will require you to add a class declaration and definition for Circle. For the constructor of Circle that takes no arguments, set the radius of the circle to be 10. You are to design the class Circle around the main method. You may NOT modify the body of the main method in anyway, if you do your code WILL NOT BE ACCEPTED, AND WILL BE GRADED AS ALL WRONG. For this question, YOU MUST capture the output of a run of your program and submit it with your source code as your solution. (TIP: the formula to find the area of a Circle is pi times r squared, or PI * r * r).
#include using namespace std;
const float PI = 3.1416; i
nt main() {
Circle c1, c2, c3; c
1.setRadius(1.0);
c3.setRadius(4.5);
Circle circles[] = {c1, c2, c3};
for (int i = 0; i < 3; i++) {
float rad, diam, area;
Circle c = circles[i];
rad = c.getRadius();
diam = c.getDiameter();
area = c.getArea();
cout << "circle " << (i) << " has a radius of: " << rad << ", a diameter of: " << diam << ", and an area of: " << area << endl;
}
return 0;
The language is C++, thanks in advance
In: Computer Science
DO NOT HARD CODE ANYTHING!
Write a class that maintains the scores for a game application. Implement the addition and removal function to update the database. The gamescore.txt contains player’ name and score data record fields separated by comma. For Removal function, uses the name field to select record to remove the game score record.
Use the List.java, LList.java, Dlink.java, GameEntry.java and gamescore.txt found below
Read gamescore.txt to initialize the Linked list in sorted order by score.
Important****ASK the user to Remove, Add and update function to the sorted linked list.
Display “Name exist” when add an exist name to the list.
Display “Name does not exist” when remove a name not on the list.
List.java File:
/** Source code example for "A Practical Introduction to Data
Structures and Algorithm Analysis, 3rd Edition (Java)"
by Clifford A. Shaffer
Copyright 2008-2011 by Clifford A. Shaffer
*/
/** List ADT */
public interface List<E>
{
/**
* Remove all contents from the list, so it is once again empty. Client is
* responsible for reclaiming storage used by the list elements.
*/
public void clear();
/**
* Insert an element at the current location. The client must ensure that
* the list's capacity is not exceeded.
*
* @param item
* The element to be inserted.
*/
public void insert(E item);
/**
* Append an element at the end of the list. The client must ensure that
* the list's capacity is not exceeded.
*
* @param item
* The element to be appended.
*/
public void append(E item);
/**
* Remove and return the current element.
*
* @return The element that was removed.
*/
public E remove();
/** Set the current position to the start of the list */
public void moveToStart();
/** Set the current position to the end of the list */
public void moveToEnd();
/**
* Move the current position one step left. No change if already at
* beginning.
*/
public void prev();
/**
* Move the current position one step right. No change if already at end.
*/
public void next();
/** @return The number of elements in the list. */
public int length();
/** @return The position of the current element. */
public int currPos();
/**
* Set current position.
*
* @param pos
* The position to make current.
*/
public void moveToPos(int pos);
/** @return The current element. */
public E getValue();
}
LList.java File:
/**
* Source code example for "A Practical Introduction to Data Structures and
* Algorithm Analysis, 3rd Edition (Java)" by Clifford A. Shaffer Copyright
* 2008-2011 by Clifford A. Shaffer
*/
// Doubly linked list implementation
class LList<E> implements List<E>
{
private DLink<E> head; // Pointer to list header
private DLink<E> tail; // Pointer to last element in list
protected DLink<E> curr; // Pointer ahead of current element
int cnt; // Size of list
// Constructors
LList(int size)
{
this();
} // Ignore size
LList()
{
curr = head = new DLink<E>(null, null); // Create header node
tail = new DLink<E>(head, null);
head.setNext(tail);
cnt = 0;
}
public void clear()
{ // Remove all elements from list
head.setNext(null); // Drop access to rest of links
curr = head = new DLink<E>(null, null); // Create header node
tail = new DLink<E>(head, null);
head.setNext(tail);
cnt = 0;
}
public void moveToStart() // Set curr at list start
{
curr = head;
}
public void moveToEnd() // Set curr at list end
{
curr = tail.prev();
}
/** Insert "it" at current position */
public void insert(E it)
{
curr.setNext(new DLink<E>(it, curr, curr.next()));
curr.next().next().setPrev(curr.next());
cnt++;
}
/** Append "it" to list */
public void append(E it)
{
tail.setPrev(new DLink<E>(it, tail.prev(), tail));
tail.prev().prev().setNext(tail.prev());
cnt++;
}
/** Remove and return current element */
public E remove()
{
if (curr.next() == tail)
return null; // Nothing to remove
E it = curr.next().element(); // Remember value
curr.next().next().setPrev(curr);
curr.setNext(curr.next().next()); // Remove from list
cnt--; // Decrement the count
return it; // Return value removed
}
/** Move curr one step left; no change if at front */
public void prev()
{
if (curr != head) // Can't back up from list head
curr = curr.prev();
}
// Move curr one step right; no change if at end
public void next()
{
if (curr != tail.prev())
curr = curr.next();
}
public int length()
{
return cnt;
}
// Return the position of the current element
public int currPos()
{
DLink<E> temp = head;
int i;
for (i = 0; curr != temp; i++)
temp = temp.next();
return i;
}
// Move down list to "pos" position
public void moveToPos(int pos)
{
assert (pos >= 0) && (pos <= cnt) : "Position out of range";
curr = head;
for (int i = 0; i < pos; i++)
curr = curr.next();
}
public E getValue()
{
// Return current element
if (curr.next() == tail)
return null;
return curr.next().element();
}
// reverseList() method that reverses the LList
public void reverseList()
{
LList<E> revList = new LList<E>();
curr = tail.prev();
while (curr != head)
{
revList.append(curr.element());
curr = curr.prev();
}
head.setNext(revList.head.next());
}
// Extra stuff not printed in the book.
/**
* Generate a human-readable representation of this list's contents that
* looks something like this: < 1 2 3 | 4 5 6 >. The vertical bar
* represents the current location of the fence. This method uses
* toString() on the individual elements.
*
* @return The string representation of this list
*/
public String toString()
{
// Save the current position of the list
int oldPos = currPos();
int length = length();
StringBuffer out = new StringBuffer((length() + 1) * 4);
moveToStart();
out.append("< ");
for (int i = 0; i < oldPos; i++)
{
if (getValue() != null)
{
out.append(getValue());
out.append(" ");
}
next();
}
out.append("| ");
for (int i = oldPos; i < length; i++)
{
out.append(getValue());
out.append(" ");
next();
}
out.append(">");
moveToPos(oldPos); // Reset the fence to its original position
return out.toString();
}
}
DLink.java File:
/** Source code example for "A Practical Introduction to Data
Structures and Algorithm Analysis, 3rd Edition (Java)"
by Clifford A. Shaffer
Copyright 2008-2011 by Clifford A. Shaffer
*/
/** Doubly linked list node */
class DLink<E>
{
private E element; // Value for this node
private DLink<E> next; // Pointer to next node in list
private DLink<E> prev; // Pointer to previous node
/** Constructors */
DLink(E it, DLink<E> p, DLink<E> n)
{
element = it;
prev = p;
next = n;
}
DLink(DLink<E> p, DLink<E> n)
{
prev = p;
next = n;
}
/** Get and set methods for the data members */
DLink<E> next()
{
return next;
}
DLink<E> setNext(DLink<E> nextval)
{
return next = nextval;
}
DLink<E> prev()
{
return prev;
}
DLink<E> setPrev(DLink<E> prevval)
{
return prev = prevval;
}
E element()
{
return element;
}
E setElement(E it)
{
return element = it;
}
}
GameEntry.java File:
public class GameEntry {
protected String name;
protected int score;
public GameEntry(String n, int s) {
name = n;
score = s;
}
public String getName() {return name;}
public int getScore() {return score;}
public String toString() {
return "("+name+","+score+")";
}
}
gamescore.txt File:
Mike,1105
Rob,750
Paul,720
Anna,660
Rose,590
Jack,510
In: Computer Science