Questions
Programming language to be used: Java Exercises Part 1) The Dog Class In the first part...

Programming language to be used: Java

Exercises

Part 1) The Dog Class

In the first part of the lab, we are writing a class to represent a Dog. It should not have a main method.

  1. Dog needs fields for price (to purchase the dog), breed, name, and age. Use appropriate data types
  2. The class should have the following two kinds of Constructors:
    1. Constructor 1: Write a constructor that accepts a value for each of the fields
    2. Constructor 2: Write a constructor that accepts no arguments and sets default values of your choice
  3. The Dog class requires:
    1. Setters and getters for all fields
    2. A toString() method, which
      1. Returns String
      2. Returns a String describing the dog, such as

Sebastian the Husky is 5 years old.
$45.56 adoption fee

  1. Please note that the dollars must be formatted that way

Part 2) The Sales Class

In the second part of the lab, we are writing a class to represent the buying of a Dog or multiple Dogs. Let’s not consider the logistics of buying Dogs in bulk.

  1. The Sales class has the following fields – a PrintWriter for a file being used (as well as any other fields you decide you want to help with that) and a double holding the total price of dogs purchased
  2. A Sales class has one constructor – it should take a file name to save the output to
  3. The Sales class needs the following functions
    1. An addDog method, which saves a new dog to the file (using the toString to get the String representation) and adds the price to the total double
    2. A finalizeReport method, which closes the file after adding a bottom line (“----“) and printing the total price below that line, properly formatted

Part 3) The DogMarket Class

This class should get a file name from the user. It should use the file to create a Sales class object. Then, it should prompt the user for details of the dogs they want to buy. Use a while loop, which uses the word “quit” to not buy a dog and the word “buy” to buy a dog – other words should be ignored, but should not quit the program. If the user says “buy”, ask them for all of the dog’s info, then make a new Dog object and save it to the file using the Sales object. Once the user is done buying dogs, the program should exit, being sure to use finalizeReport() on the sales object

In: Computer Science

C# Structures usage tips, with examples ?

C# Structures usage tips, with examples ?

In: Computer Science

Define a structure Point. A point has an x- and a y-coordinate. Write a function double...

Define a structure Point. A point has an x- and a y-coordinate. Write a function double distance(Point a, Point b) that computes the distance from a to b. Write a program that reads the coordinates of the points, calls your function, and displays the result. IN C++

if possible please give //comments

In: Computer Science

Fibonacci Sequence in JAVA f(0) = 0, f(1) = 1, f(n) = f(n-1) + f(n-2) Part...

Fibonacci Sequence in JAVA

f(0) = 0, f(1) = 1, f(n) = f(n-1) + f(n-2)

Part of a code
public class FS {
public static void main(String[] args){
IntSequence seq = new FibonacciSequence();
for(int i=0; i<20; i++) {
if(seq.hasNext() == false) break;
System.out.print(seq.next()+" ");
}
System.out.println(" ");
}
}
///Fill in the rest of the code!
Output
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181

You should define IntSequence as the interface.

You can't use for, while loop.

Thanks!!

In: Computer Science

Write a public Java method called WriteToFile that opens a file called words.dat which is empty....

Write a public Java method called WriteToFile that opens a file called words.dat which is empty. Your program should read a String array called words and write each word onto a new line in the file. Your method should include an appropriate throws clause and should be defined within a class called TextFileEditor.

The string should contain the following words:
{“the”, “quick”, “brown”, “fox”}

In: Computer Science

Create a grade report. The grades will be stored as a list of tuples: [ (grade_percentile_1...

Create a grade report.

The grades will be stored as a list of tuples:

[ (grade_percentile_1 , grade_letter_1) , (grade_percentile_2 , grade_letter_2) , .... ]

Create each grade percentile using a random generator to uniformly choose a percent between 50% and

100%. Assign the letter grade based on the chosen percentile using the table below.

Numeric Average Letter Grade Numeric Average Letter Grade
93 - 100 A 90 - 92.99 A-
87 - 89.99 B+ 83 - 86.99 B
80 - 82.99 B- 77 - 79.99 C+
73 - 76.99 C 70 - 72.99 C-
67 - 69.99 D+ 63 - 66.99 D
60 - 62.99 D- Below 60 F

Create 35 random grades and store them as a list of 35 tuples. You decide on the class name. Then print all 35 grades to the screen, along with summary information (total number of grades, minimum grade, maximum grade, and average grade). Show all grades and the average with exactly 2 decimal places.

Submit your program script called grades.py. Use functions as appropriate for optimal abstraction and encapsulation.

Here is an example of how the grade report could appear:

Grades for Applied Neural Networks    Letter Grade

    Numeric Grade (%)

86.75 B+

76.62 C+

85.50 B

74.00 C

92.35 A-

97.72 A

55.35   F

72.67 C

65.87 D

94.87 A

97.53    A

63.42 D

82.57 B

72.43 C-

87.65 B+

68.56 D+

59.34   F

62.87   D

92.62 A

Total Grades: 19

Minimum Grade: 55.35

Maximum Grade: 97.72

Average Grade: 78.35

In: Computer Science

The C++ problem: Student marks are kept in a text file as a single column. Each...

The C++ problem:

Student marks are kept in a text file as a single column. Each student may have a different number of assessments and therefore scores. The data recorded in the file for each student start with the number of scores for the student. This is followed by the student id and then several marks student scored in various assessments, one score per line. A small segment of the file might look like the following: (file name is marks.txt)

2

S1234567

55

70

4

S2222222

96

67

88

88

So, according data presented in this file segment, the first student has 2 scores, student id is S1234567, and the assessment scores are 55 and 70. The second students has 4 scores, student id is S2222222, and the assessment scores are 96, 67, 88 and 88.

It is anticipated (assumed) that the total number of scores in the marks.txt file will not exceed 100.

The program functionality:

Your program will utilise a number of user-defined functions to display data from the file, update data by adding marks for new students, as well as performing a number of other tasks including calculating the mean and median score of all marks and finding the minimum and maximum scores in the collection as well as calculating and displaying the average mark for a given student.

Your program should be modular and menu-driven as described below:

  • The main() function handles all interactions with the user and other functions:
    • It displays an appropriate welcoming message introducing the program
    • Calls a function named readFile() which opens the text file marks.txt for

reading and stores all of the student marks from the file to an array (NOT A VECTOR!) namedmarksArray. The readFile()function has two parameters: one for receiving the file variable and one for the array, both receiving arguments passed by reference.

later

  • It (the main function) then repeatedly calls the menu() function to display user

options, get the user selection returned by the menu() function, use a switch statement or a multi-alternative if statement to process user request by calling appropriate function

  • It displays the result with an appropriate message after processing user request
  • It displays a goodbye message when the user selects the Quit option (option 8) from the menu and terminates the program.

  • The menu() function has no parameters. When called, it displays a menu of 8 options allowing the user to select one and returns this option to the calling main() function. The options displayed should be:

(1) Display marks
(2) Calculate mean
(3) Calculate median
(4) Find minimum
(5) Find maximum
(6) Find average for student

(7) Add new student data

(8) Quit program

  • Option (1) will use a function called displayMarks() called from the main()to display the contents of the marks array on the screen in an appropriate format. The displayMarks() function has two parameters: the array and the number of values in the array.
  • Option (2) will use a function called calculateMean() which is designed to calculate the mean value of all scores in marksArray and return the result to the main()

function which will then display it with an appropriate message. This function also has two parameters: the array and the number of values in the array.

  • Option (3) will use a function called calculateMedian() which is designed to calculate the median value of all scores in marksArray and return the result to the main() function which will then display it with an appropriate message. The median value is calculated by finding the middle value when the values are sorted in ascending (or descending) order. When there are two middle values (as is the case when the number of values is even), then the average of the two middle values is the median value. Parameters for this function are the same as the previous function.
  • Option (4) will use a function called findMinimum()which is designed to find the smallest value of all scores in marksArray and return the result to the main() function which will then display it with an appropriate message. Again, the parameters for this function are the same as the previous function.
  • Option (5) will use a function called findMaximum()which is designed to find the largest value of all scores in marksArray and return the result to the main() function

which will then display it with an appropriate message. Again, the parameters for this function are the same as the previous function.

  • Option (6) will use a function called findAverageForStudent()which is designed to get a student id as an argument as well as a reference to the marks data file from the main() function, open the marks.txt file, find the marks in the file for that particular student, calculate the average value and return it to the main function which will then display it with an appropriate message. The main function should be responsible for prompting the user for the student id.
  • Option (7) will first use a function called updateFile() which will open the file in append mode, prompt the user for new student’s id followed by a varying number of marks received from the user, and then write the new data at the end of the file using the same format as the original file.
  • Option (8) will terminate the program after displaying an appropriate goodbye message.

In: Computer Science

I'm trying to get my occupancy rate to output as 2 decimal places with a %...

I'm trying to get my occupancy rate to output as 2 decimal places with a % sign. I know this is a string but I need it to print as 2 decimal places like 59.23% or 25.36%

I have system.out.printf("Occupancy rate: %2s", occupancy + "%"); but I'm still not getting 2 decimal places or the % sign. How can I fix this? I'm in beginning java so I can't use anything advanced.

public class ResortAccomidations {
public static void main(String[] args) {
int totalNumberOfOccupiedRooms = 0; // Total number of floors
int totalNumberOfRooms = 0; // Total number of rooms

Scanner in = new Scanner(System.in); // Scanner object for user input

System.out.print("How many floors does the resort have?: "); // Get number of floors in resort
int floor = in .nextInt(); // To store number of floors

while (floor < 1) // Validate input
{
System.out.print("INVALID. How many floors does the resort have?: "); // Correct floors
floor = in .nextInt(); // To store correct number of floors
}
for (int i = 0; i < floor; i++) // Initialize floor at 0, test that floor is <0, increase floor per user input
{
System.out.println("\nFloor " + (i + 1)); // Displays floor
System.out.print("How many rooms does floor " + (i + 1) + " have?: "); // Get how many rooms
int rooms = in .nextInt(); // Store number of rooms
while (rooms < 10) // While rooms greater than 10
{
System.out.print("INVALID. Enter 10 or more: "); // Validate input < 10
rooms = in .nextInt(); // Store correct number of rooms
}
totalNumberOfRooms = rooms + totalNumberOfRooms; // Add rooms to total number of rooms

System.out.print("How many occupied rooms does floor " + (i + 1) + " have?: "); // Get number of rooms occupied
int occupied = in .nextInt(); // Store number of rooms occupied
while (occupied > rooms) // While occupied do not exceed rooms
{
System.out.print("INVALID. How many rooms occupied?: "); //Validate occupied do not exceed rooms
occupied = in .nextInt(); // Store correct number of rooms occupied
}
totalNumberOfOccupiedRooms = totalNumberOfOccupiedRooms + occupied; // Add occupied to total number of occupied rooms   
}
int vacancies = totalNumberOfRooms - totalNumberOfOccupiedRooms; // Vacancies
double occupancy = ((double) totalNumberOfOccupiedRooms / (double) totalNumberOfRooms) * 100; // Occupancy rate


System.out.printf("\nNumber of rooms: %d\n", +totalNumberOfRooms);
System.out.printf("Occupied rooms: %d\n", +totalNumberOfOccupiedRooms);
System.out.printf("Vacant rooms: %d\n", +vacancies);
System.out.printf("Occupancy rate: %.2s", occupancy + "%");

}
}

This is my output

How many floors does the resort have?: 2

Floor 1
How many rooms does floor 1 have?: 16
How many occupied rooms does floor 1 have?: 5

Floor 2
How many rooms does floor 2 have?: 16
How many occupied rooms does floor 2 have?: 15

Number of rooms: 32
Occupied rooms: 20
Vacant rooms: 12
Occupancy rate: 62

I need 2 decimal places and the % sign but no luck. Could someone please tell me how to get the correct output?

In: Computer Science

Create a Java class named Trivia that contains three instance variables, question of type String that...

Create a Java class named Trivia that contains three instance variables, question of type String that stores the question of the trivia, answer of type String that stores the answer to the question, and points of type integer that stores the points’ value between 1 and 3 based on the difficulty of the question.

Also create the following methods:

  1. getQuestion( ) – it will return the question.
  2. getAnswer( ) – it will return the answer.
  3. getPoints( ) – it will return the point
  4. setQuestion( String ) – sets the value of the question variable
  5. setAnswer( String ) – sets the value of the answer variable
  6. setPoints( int ) – sets the value of the points variable
  7. Constructor to initialize the instance variables.
  8. Overload Constructor to set the instance variables.
  9. Add any other methods you need such as equal( ), toString( ), display( ), calcPoints( )...

Create Java application that contains a main method that plays a simple Trivia game. The game should have 5 questions. Each question has a corresponding answer and point value between 1 and 3. Implement the game using an array of 5 Trivia objects.

Next, open a binary file and store those 5 Trivia objects into a binary file then close the file. Open the file again to read each question one at a time and store them into an array of objects.

Randomly, display a question and allow the player to enter an answer.

If the player’s answer matches the actual answer, the player wins the number of points for that question. If the player’s answer is incorrect, the player wins no points for the question. Make sure the answer is not case sensitive and it is only one word or two words at most. The program should show the correct answer if the player is incorrect. After the player has answered all five questions, the game is over and your program should display the player’s total score.

In: Computer Science

The nutrition.py program (attached) creates a dictionary of food items (a mix of fruit and meat...

The nutrition.py program (attached) creates a dictionary of food items (a mix of fruit and meat items) and displays their corresponding information. The dictionary has the food item code, and Food object as key and value respectively. Write the missing code, in the designated locations, in order for the program execution to yield the following output when the input number of food items is 5:

Enter number of food items:
5

Type: Fruit
Category: Apples & Pears
Code: 1012030
Name: Fruit_0
Sugar: 10g

Type: Meat
Category: Chicken
Code: 1012031
Name: Meat_1
Protein: 21%

Type: Fruit
Category: Berries
Code: 1012032
Name: Fruit_2
Sugar: 12g

Type: Meat
Category: Beef
Code: 1012033
Name: Meat_3
Protein: 23%

Type: Fruit
Category: Citrus
Code: 1012034
Name: Fruit_4
Sugar: 14g

nutrition.py file

import random

class Food:
    FRUIT_CATEGORIES =["Apples & Pears","Citrus","Berries"]
    MEAT_CATEGORIES  = ["Beef","Chicken","Fish"]

    def __init__(self,code,name,category):
        self.code = code
        self.name = name
        self.category = category

    def info(self):
        print('\nType:',type(self).__name__)
        #TODO

class Fruit(Food):
    # Add code for the __init__ function

    def info(self):
        super(Fruit,self).info()
        print('Sugar:',str(self.sugar)+"g")  # Sugar content

class Meat(Food):
    # Add code for the __init__ function

    def info(self):
        super(Meat, self).info()
        print('Protein:',str(self.protein)+"%")  # Protein content

# Enter the number of food items
s = input("Enter number of food items:\n")
n = int(s)

foods = dict()
for i in range(0,n):
    code = "101203"+str(i)
    rd = i % 3
    if i % 2 == 0:
        food = Fruit(10+i%10,code,"Fruit_"+str(i),Fruit.FRUIT_CATEGORIES[rd])
    else:
        food = Meat(20+i%10,code,"Meat_"+str(i),Fruit.MEAT_CATEGORIES[rd])

    foods[code] = food

keys = list(foods.keys())
keys.sort()

for key in keys:
    foods[key].info()

In: Computer Science

c++ ///////////////////////////////////////////////////////////////////////// need to be named Subsequences.h and pass test cpp file SubsequenceTester.cpp at the end...

c++

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

need to be named Subsequences.h and pass test cpp file SubsequenceTester.cpp at the end of this question.

This assignment will help you solve a problem using recursion

Description

A subsequence is when all the letters of a word appear in the relative order of another word.

  • Pin is a subsequence of Programming
  • ace is a subsequence of abcde
  • bad is NOT a subsequence abcde as the letters are not in order

This assignment you will create a Subsequence class to do the following:

  • Add a constructor that takes only a single word argument
  • Add a bool isSubsequence(string sub); a method that will return true if sub is a subsequence of the original word.
  • Overload the operator<< using a friend function, such that information is given about the class. This will be used for your own debugging

Hints

Think about the following questions to help you set up the recursion...

  • What strings are subsequences of the empty string
  • What happens if the first character of the subsequence matches the first character of the text?
  • What happens if it doesn't

Submission

To get you thinking of data good test cases, only the example test cases have been provided for you in the SubsequenceTester.cpp. It is your responsibility to come up with several other test cases. Think of good ones

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

SubsequenceTester.cpp

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

using namespace std;

void checkCase(string, string, string, bool);

int main()
{
    /**
        Add several more test cases to thoroughly test your data
        checkCase takes the following parameters (name, word, possible subsequence, true/false it would be a subsequence)
    **/

    checkCase("Case 1: First Letter", "pin", "programming", true);
    checkCase("Case 2: Skipping Letters", "ace", "abcde", true);
    checkCase("Case 3: Out of order", "bad", "abcde", false);

    return 0;
}


void checkCase(string testCaseName, string sub, string sentence, bool correctResponse){
    Subsequences s(sentence);
    if(s.isSubsequence(sub) == correctResponse){
        cout << "Passed " << testCaseName << endl;
    }
    else{
        cout << "Failed " << testCaseName << ": " << sub << " is " << (correctResponse? "": "not ") << "a subsequence of " << sentence << endl;
    }
}

In: Computer Science

Activity 1 - Network Design Proposal In this section, you are required to write a Network...

Activity 1 - Network Design Proposal

In this section, you are required to write a Network Design Proposal. You will need to: 1. Describe the network design scenario that needs to be addressed. 2. Provide a network design solution. 3. Write a complete network design proposal. 4. Develop (implement) a high‐level solution showing important components of the solution using a virtualization tool.

In: Computer Science

What is the output of the following piece of Java code? int id = 4; double...

What is the output of the following piece of Java code?

int id = 4; 
double grossPay = 81.475;
String jobType = "Intern";
System.out.printf("Id: %d, Type: %s, Amount:%.2f", id,grossPay,jobType);

Select one:

Error

Id: 4, Type: Intern, Amount: $81.475

Id: 4, Type: $81.475, Amount: Intern

Id: 4, Type: $81.48, Amount:Intern

Id: 4, Type: Intern, Amount: $81.48

In: Computer Science

Post a two- paragraph summary in your own words, of Walden's policy on academic integrity. Identify...

Post a two- paragraph summary in your own words, of Walden's policy on academic integrity. Identify three types of academic integrity violations, and explain what stidents can do to avoid them.

In: Computer Science

Code in Python. You can only use while loops NOT for loops. Program 1: cost_living In...

Code in Python. You can only use while loops NOT for loops.

Program 1: cost_living

In 2020 the average cost of living/month (excluding housing) for a family of 4 in Pittsburgh was $3850 per month. Write a program to print the first year in which the cost of living/month is over $4450 given that it will rise at a rate of 2.1% per year. (Note:  this program requires no input).

Program 2: discount

A discount store is having a sale where everything is 15% off. Write a program to display a table showing the original price and the discounted price. This program requires no input and your table should include headings and the original prices should go from 99 cents to $9.99 in increments of 50 cents.

Program 3: numbers

Write a program to input a sequence of 8 integers, count all the odd numbers and sum all the negative integers. One integer is input and processed each time around the loop.

In: Computer Science