Questions
(b) Postcard from Giza (actually: a Pyramid) It is quite possible that programming to generate rectangles...

(b) Postcard from Giza (actually: a Pyramid)

It is quite possible that programming to generate rectangles using loops is a piece of cake for you. Here is another programming challenge to see how well you can use the for loop, so now we want you to draw a "Postcard from Giza (Links to an external site.)" i.e. create a view of a famous location: a single side of a hollow pyramid.

You are to write an interactive program that asks the user about a single pyramid's width, a positive integer representing the size of its base and then creates a picture like the one below. Use repetition control structures better known as "loops" to output a hollow pyramid shape based on the width specified by the integer. If the input is an even number, it should be increased to the next odd number.


Don't cheat! Don't use the setw manipulator or output hard-coded strings containing a rigid number of asterisks and spaces – all elements must be created dynamically using loops!

 
    Enter a value to represent the base of a hollow pyramid (not to exceed 80): 11    
     *
    * *
   *   *
  *     *
 *       *
***********

Notice the specific character * (an asterisk) used to generate the hollow pyramid.

When thinking of how to generate a somewhat complex pattern such as the one above using loops we can begin by looking at the pyramid displayed and asking a few questions. Here are a few you might think about.

How is the integer value input of 11 used in this pyramid display? Answer: Used in a loop to generate a line of asterisks for the base of the pyramid.
Can the integer value of 11 be used to determine the number of rows needed to be generated? Answer: A possible formula here might be 11/2+1= 6 rows
How can the integer value of 11 be used to determine the number of outer whitespaces to be generated for each row? Answer: 11/2=5 outer whitespaces for the first row. Determine how to come up with outer whitespaces for the remaining rows as this will be helpful in generating the left slope of the pyramid.
How can the integer value of 11 be used to determine the inner whitespaces to be generated for each row? Answer: Inner whitespace for second row - 11-8 (outer whitespace*2) - 2 (left and right * characters) = 1 whitespace. This sort of study of the pattern progressing through each row will help in generating the right slope of the pyramid.

Remember, there may be multiple ways to complete a programming challenge, and the algorithm here may not necessarily be the only, or even the best, way. Implement the algorithm that you understand and works best for.

Your task is to achieve the following goals:

  • ask the user to enter a positive integer value greater than 4 (n) to represent the width or base of the pyramid; This integer value should not be used to represent the rows needed to generate the pyramid, make sure you get this correct. If the input is an even number, it should be increased to the next odd number. The odd number width is needed to ensure that the pyramid has a single tip.

  • check the entered value and if it isn't legal, output a message stating the reason;

  • draw a hollow pyramid using the character * (an asterisk) with a base of n (see sample output above)

  • check to make sure the number of inner whitespaces in each row starting with the second row is an odd number. So for the above sample pyramid with a base of 11, the number of inner whitespaces should be Row2=1, Row3=3, Row4=5 and Row5=7.

  • find a reasonable upper limit for the width or base (depending on your screen's dimensions or an acceptable range) and embed it into your input validation code.

  • The algorithm should provide the user an opportunity to try the shape generator program again or quit.

Input Validation: Ensure that the user inputs a positive integer value greater than 4 and does not exceed an acceptable range determined by you. Do not accept negative or non-numeric values.

Use meaningful variable names, nested loop statements with proper indentation, appropriate comments, and good prompting messages.

Here us a sample test run of the Postcard from Giza program with some user input validation routines.

Enter a value to represent the base of a hollow pyramid (not to exceed 20): four
OOPS! Looks like you typed some bad data here!
The acceptable base for the pyramid should range from 5 to 20...
Enter a value to represent the base of a hollow pyramid (not to exceed 20): 4
OOPS! Looks like you typed some bad data here!
The acceptable base for the pyramid should range from 5 to 20...
Enter a value to represent the base of a hollow pyramid (not to exceed 20): 11

************** A POSTCARD **************
*********
*********
*********
                   *
                  * *
                 *   *
                *     *
               *       *
              ***********

********** A PYRAMID FROM GIZA ********

Process returned 0 (0x0) execution time : 12.188 s
Press any key to continue.

In: Computer Science

Operating Budgeting(9) Scenario Don Flowers, CEO of Burbage Manufacturing looked around the conference room as his...

Operating Budgeting(9)
Scenario

Don Flowers, CEO of Burbage Manufacturing looked around the conference room as his management team chatted and settled in for the monthly meeting.
“Let’s get started,” Don said, “we have a lot to cover today, and frankly it’s not all good news.” The room fell quiet. Don continued, “As you know we recently experienced a cash shortage despite last quarter’s record sales. We can’t keep going back to the bank to borrow money to support operations. I am counting on each of you to figure out a way to keep this from happening in the future.”
Brian Mitchell, the newest member of the team raised his hand somewhat sheepishly. “Sir, perhaps if we looked at the Master Budget for last month we could begin to identify areas for improvement.”
Don looked to Alex, his CFO. “Well, Alex that’s your area of expertise and Brian’s suggestion makes sense. Let’s have a look at that Master Budget.”
Alex looked down at the desk and began shuffling through his paperwork. “Well Don, we don’t exactly have a Master Budget per se. I mean we have budgets for different areas within the company, but I really rely on the managers to know what they need to do in their areas.”
Terri, the production manager spoke up, “Hey, wait a minute Alex. You’re the CFO. I’m doing everything I can just to keep up with demand down there on the floor. I don’t have time to worry about that kind of thing. We had a press go down last week and I had an entire shift of down time. Besides, that’s your job, Alex.”
“You know she has a point there Alex. You are the CFO. I need Terri to put all of her time towards keeping the production line running smoothly,” Don said.
“Look, Don, Alex replied, “In January I asked everyone to send me their budgets for the year and the only thing I got was a sales budget from Peter with a note attached that asked for a pay increase for his account managers.”
Brian raised his hand to speak. “Well, I know I’m new here, but at my last company we had budgets for sales, finished goods, cash – pretty much everything was budgeted. It seemed to work pretty well, and everyone had a good grasp of where we were financially.”
Alex, the CFO gave Brian an icy stare.
Don turned to Alex. “Alex, I think this young man has a point. Is there some reason why we aren’t budgeting like he described?”
“Well”, Alex began, “It’s really complicated, Don. Marjorie in materials is short two people and she’s paying overtime to her remaining people just to meet supply requisitions from the shop floor. And then there’s the problem with the corporate office. Every time I turn around I am getting an invoice from them for some piece of office equipment or another. Last week I got a bill from some company that Jessica hired to water the plants. How am I supposed to keep track of all of this? And then ….”
Don raised his hand to cut Alex off. “Look, I know we are a complex organization – but the fact of the matter is that I can’t keep going to the bank every month, borrowing money to pay the suppliers. For heaven’s sake – we are a multi-million-dollar company.” By this time Don was red in the face and everyone around the table was showing an intense interest in the conference table. He continued, “What am I going to tell the shareholders at the annual meeting when we don’t have enough cash to pay a dividend – that Jessica spent their money on potted plants?”
“This is going to end, today. Brian, you seem like a smart young man. You are going to work with Alex and anyone else in this company to get us on board with establishing and using budgets to correct this situation,” Don explained. “Further, as for the rest of you -when Brian comes and asks you for information treat him as if it was me making the request. Understood?”
Everyone nodded their heads in agreement.
“Meeting adjourned,” Don declared.
Questions

1. Identify the problems that appear to exist in Burbage’s budgetary control system and explain how these problems are contributing to the company’s poor cash position.
2. Identify the budgets that Brian and Alex will need to create to resolve these issues, including the information that is needed to construct each budget.
3. Once you have identified the problems and necessary budgets, prepare a report for Don and the rest of the management team outlining your plan for establishing a budgetary control system, making certain to include how each component of the system will benefit the overall financial health of the company.

In: Accounting

Read the case study below, based on the experiences of Larry Zeenny in the Lebanon. It...

Read the case study below, based on the experiences of Larry Zeenny in the Lebanon. It concerns a football agent’s attempt to make a deal for his client. When you have read it, answer the questions that follow.



An own goal


The taxi arrived at the impressive mansion in Faqra and I made my way through the blistering sun towards  the entrance. I was met by two servants and directed to Mr Haider’s room. He had faxed me a contract, the terms of which were ridiculously low, and I was determined to get a better deal for my client.

A peek at my watch revealed it was 11.30. I’d arrived just in time, despite the flight delays at Frankfurt and the queues at Beirut airport. In front of Haider’s door I cleared my throat, tightened my tie, gathered all my courage and entered the room. ‘Mr Haider, I am delighted to meet you’, I said, rather too exuberantly. ‘AhlanWilhelm, welcome my friend’, said Haider. ‘I just have to say goodbye to my important visitors. Please make yourself at home while you’re waiting.’

A servant led me to a large room where there were two men and, in the far corner, a beautiful oriental

woman. I sat down in a chair and waited for Mr Haider. An elaborate clock chimed twelve, but there was still no sign of him. By now the other three were thoroughly enjoying their lunch, which I had refused out of politeness. To keep my nerves steady I had only accepted a glass of arak. By 12.15 my patience had started to desert me. I was going to be too late for my next meeting. How could I trust Mr Haider if he had already broken his promise beforehand?

Eventually, at 12.30, Mr Haider entered the room. He looked extremely relaxed in his traditional dress and I jumped up to greet him. Before approaching me he first kissed both men and had a brief conversation with the woman. I had prepared myself well for this moment. I gave him a firm handshake and seated myself.

‘Ahlan Wilhelm, welcome to Lebanon’, he said. Looking at the table, he added: ‘I hope you enjoyed your delicious lunch with my beloved sons, Alain and Elie, and of course with my habibi, Charlotte.’

‘Mr Haider’, I replied, ‘Thank you for your warm reception, but I ate on the plane. My client is extremely pleased about your interest and he is looking forward to playing for such an illustrious club as Al Ansar. Shall we come to terms as quickly as possible so we can finalise this matter in the best interest of both parties?’ ‘Shouf Wilhelm’, he retorted. ‘Please call me Hashem. But why the rush? We have the time for business until the sun walks out on us! When will your client arrive?’

I told him that my client, a goalkeeper who had played for German,Italian and British teams, as well as for his home country, Denmark, would be unable to attend the negotiations. ‘The thing is . . .’ (I hesitated: how could I call him by his first name and show my total respect?) ‘It’s usual for a player to leave such dealings to his agent.’

Mr Haider seemed disgruntled, but agreed to talk. He called his two sons over while his wife quietly

headed for the door. As she passed by I respectfully looked her in the eye and wished her a pleasant day.

The bargaining process began and, quite disconcertingly, Mr Haider’s sons joined in. Was he hoping to get the upper hand through force of numbers? Could I trust his sons to honour the confidentiality spect of the negotiation? I was concerned details would leak out to the predators from the international press. After anhour we had reached an impasse, but I couldn't really understand why. Mr Haider refused to provide me with a bank guarantee with respect to my client's salary and signing-on fee. In fact, Mr Haider persistently refused to go into financial matters. These could be discussed the next day, he insisted, since they would not be aproblem as far as he was concerned.

But for me they were the problem. And that was why we had reached a stalemate.

Questions (each answer should be 250 words long)

Q1. Explain the title of the case study "An own goal".

Q2. What is the main problem faced by Larry in this case study?

Q3. Using the cultural values model (Time focus, space, structure......) explain the main reasons why Larry feels that he reached an impasse with Mr Haider and compare their respective cultures.

Q4. Did Larry used the best approach to deal with Mr. Haider? Explain how you would behave in his situation? Propose a solution to overcome this impasse.

In: Operations Management

Note: This is a single file C++ project - No documentation is required on this assignment....

Note: This is a single file C++ project - No documentation is required on this assignment.

Write a Fraction class whose objects will represent Fractions.

Note: You should not simplify (reduce) fractions, you should not use "const," and all of your code should be in a single file. In this single file, the class declaration will come first, followed by the definitions of the class member functions, followed by the client program.

You must provide the following member functions:

  1. A set() operation that takes two integer arguments, a numerator and a denominator, and sets the calling object accordingly.
  2. Arithmetic operations that add, subtract, multiply, and divide Fractions. These should be implemented as value returning functions that return a Fraction object. They should be named addedTo, subtract, multipliedBy, and dividedBy. In these functions you will need to declare a local "Fraction" variable, assign to it the result of the mathematical operation, and then return it.
  3. A boolean operation named isEqualTo that compares two Fraction objects for equality. Since you aren't reducing your Fractions, you'll need to do this by cross-multiplying. A little review: if numerator1 * denominator2 equals denominator1 * numerator2, then the Fractions are equal.
  4. An output operation named print that displays the value of a Fraction object on the screen in the form numerator/denominator.

Your class should have exactly two data members, one to represent the numerator of the Fraction being represented, and one to represent the denominator of the Fraction being represented.

Here's a hint for how you will set up your arithmetic operation functions: You need two Fractions. One is the parameter, one is the calling object. The function multiplies the calling object times the parameter and returns the result. In some ways it is similar to the comesBefore() function from the lesson. That function also needs two Fractions, and one is the calling object and one is the parameter.

When adding or subtracting Fractions, remember that you must first find the common denominator. The easy way to do this is to multiply the denominators together and use that product as the common denominator.

I am providing a client program for you below. You should copy and paste this and use it as your client program. The output that should be produced when the provided client program is run with your class is also given below, so that you can check your results.

I strongly suggest that you design your class incrementally. For example, you should first implement only the set function and the output function, and then test what you have so far. Once this code has been thoroughly debugged, you should add additional member functions, testing each one thoroughly as it is added. You might do this by creating your own client program to test the code at each stage; however, it would probably be better to use the provided client program and comment out code that relates to member functions that you have not yet implemented.

As you can see from the sample output given below, you are not required to reduce Fractions or change improper Fractions into mixed numbers for printing. Just print it as an improper Fraction. You are also not required to deal with negative numbers, either in the numerator or the denominator.

Here is the client program.

#include <iostream>
using namespace std;

int main()
{
    Fraction f1;
    Fraction f2;
    Fraction result;

    f1.set(9, 8);
    f2.set(2, 3);
    
    cout<<"\nArithmetic operations with fraction objects stored in the results class object\n"; 
    cout<<"------------------------------------------------------------------------------\n\n";

    cout << "The product of ";
    f1.print();
    cout << " and ";
    f2.print();
    cout << " is ";
    result = f1.multipliedBy(f2);
    result.print();
    cout << endl;

    cout << "The quotient of ";
    f1.print();
    cout << " and ";
    f2.print();
    cout << " is ";
    result = f1.dividedBy(f2);
    result.print();
    cout << endl;

    cout << "The sum of ";
    f1.print();
    cout << " and ";
    f2.print();
    cout << " is ";
    result = f1.addedTo(f2);
    result.print();
    cout << endl;

    cout << "The difference of ";
    f1.print();
    cout << " and ";
    f2.print();
    cout << " is ";
    result = f1.subtract(f2);
    result.print();
    cout << endl;

    if (f1.isEqualTo(f2)){
        cout << "The two Fractions are equal." << endl;
    } else {
        cout << "The two Fractions are not equal." << endl;
    }
    
    cout<<"\n---------------------------------------------------------\n"; 
    cout<<"\nFraction class implementation test now successfully concluded\n"; 
    // system ("PAUSE"); 
    return 0;
}

This client should produce the output shown here:

C++ CLASS SINGLE-FILE PROJECT Client.cpp - testing a Fraction class implementation 
----------------------------------------------------

Arithmetic operations with Fraction objects stored in the result class object 
------------------------------------------------------------------------------ 
The product of 9/8 and 2/3 is 18/24 
The quotient of 9/8 and 2/3 is 27/16 
The sum of 9/8 and 2/3 is 43/24 
The difference of 9/8 and 2/3 is 11/24 
The two Fractions are not equal. 
--------------------------------------------------------- 
Fraction class implementation test now successfully concluded 

Process returned 0 (0x0) execution time : 10.546 s Press any key to continue.

You may not change the client program in any way. Changing the client program will result in a grade of 0 on the project.

In: Computer Science

Assignment: Operating Budgeting Scenario Don Flowers, CEO of Burbage Manufacturing looked around the conference room as...

Assignment: Operating Budgeting

Scenario

Don Flowers, CEO of Burbage Manufacturing looked around the conference room as his management team chatted and settled in for the monthly meeting.

“Let’s get started,” Don said, “we have a lot to cover today, and frankly it’s not all good news.” The room fell quiet. Don continued, “As you know we recently experienced a cash shortage despite last quarter’s record sales. We can’t keep going back to the bank to borrow money to support operations. I am counting on each of you to figure out a way to keep this from happening in the future.”

Brian Mitchell, the newest member of the team raised his hand somewhat sheepishly. “Sir, perhaps if we looked at the Master Budget for last month we could begin to identify areas for improvement.”

Don looked to Alex, his CFO. “Well, Alex that’s your area of expertise and Brian’s suggestion makes sense. Let’s have a look at that Master Budget.”

Alex looked down at the desk and began shuffling through his paperwork. “Well Don, we don’t exactly have a Master Budget per se. I mean we have budgets for different areas within the company, but I really rely on the managers to know what they need to do in their areas.”

Terri, the production manager spoke up, “Hey, wait a minute Alex. You’re the CFO. I’m doing everything I can just to keep up with demand down there on the floor. I don’t have time to worry about that kind of thing. We had a press go down last week and I had an entire shift of down time. Besides, that’s your job, Alex.”

“You know she has a point there Alex. You are the CFO. I need Terri to put all of her time towards keeping the production line running smoothly,” Don said.

“Look, Don, Alex replied, “In January I asked everyone to send me their budgets for the year and the only thing I got was a sales budget from Peter with a note attached that asked for a pay increase for his account managers.”

Brian raised his hand to speak. “Well, I know I’m new here, but at my last company we had budgets for sales, finished goods, cash – pretty much everything was budgeted. It seemed to work pretty well, and everyone had a good grasp of where we were financially.”

Alex, the CFO gave Brian an icy stare.

Don turned to Alex. “Alex, I think this young man has a point. Is there some reason why we aren’t budgeting like he described?”

“Well”, Alex began, “It’s really complicated, Don. Marjorie in materials is short two people and she’s paying overtime to her remaining people just to meet supply requisitions from the shop floor. And then there’s the problem with the corporate office. Every time I turn around I am getting an invoice from them for some piece of office equipment or another. Last week I got a bill from some company that Jessica hired to water the plants. How am I supposed to keep track of all of this? And then ….”

Don raised his hand to cut Alex off. “Look, I know we are a complex organization – but the fact of the matter is that I can’t keep going to the bank every month, borrowing money to pay the suppliers. For heaven’s sake – we are a multi-million-dollar company.” By this time Don was red in the face and everyone around the table was showing an intense interest in the conference table. He continued, “What am I going to tell the shareholders at the annual meeting when we don’t have enough cash to pay a dividend – that Jessica spent their money on potted plants?”

“This is going to end, today. Brian, you seem like a smart young man. You are going to work with Alex and anyone else in this company to get us on board with establishing and using budgets to correct this situation,” Don explained. “Further, as for the rest of you -when Brian comes and asks you for information treat him as if it was me making the request. Understood?”

Everyone nodded their heads in agreement.

“Meeting adjourned,” Don declared.

Questions

1. Identify the problems that appear to exist in Burbage’s budgetary control system and explain how these problems are contributing to the company’s poor cash position.
2. Identify the budgets that Brian and Alex will need to create to resolve these issues, including the information that is needed to construct each budget.
3. Once you have identified the problems and necessary budgets, prepare a report for Don and the rest of the management team outlining your plan for establishing a budgetary control system, making certain to include how each component of the system will benefit the overall financial health of the company.

In: Operations Management

Important notes: Use Console I/O (Scanner and System.out) for all user I/O in this lab. Do...

Important notes: Use Console I/O (Scanner and System.out) for all user I/O in this lab.

Do not hard code data file paths or filenames; always ask the user for them.

Complete the Monster Attack project by doing the following: In place of the driver used in homework 2, add a menu with a loop and switch (this is already done, ignore this).

The user must be able to add attacks, get a report on existing attacks, save a file, retrieve a file, and clear the list as many times as she wants in any order she wants.

Replace the array of MonsterAttacks with an ArrayList of MonsterAttacks. This will require changes in several methods. You will need to be able to handle any number of MonsterAttacks the user chooses to input.

Add a method to AttackMonitor that saves the list of attacks to a comma separated values file. Iterate through the list, and for each attack, get each field using the getters from MonsterAttack. Write each value to the file, following each one except the last with a comma. Save the date as a single String in the format MM/DD/YYYY. After you have written out all the data for one attack, write out a newline. Add an item to the main menu that calls this method.

Add a method that clears the list of monster attacks, then uses a Scanner to read data from a .csv file, uses it to instantiate MonsterAttack objects, and adds the attacks to the list. This method must be able to read the files you write out in the method described above. You will need to use String's split() method here. Add an item to the main menu that calls this method. Make sure you can input attack data, save to a file, quit the program, start the program again, read your output file, and show the data from the file.

Below is the original code that needs to be modified to meet the requirements stated above.

MonsterAttack

//side note- the date is incorrect here.. user is supposed to enter the date.. but that shouldn't matter.. still works

import java.util.Date;
class MonsterAttack {
private String monsterName;
private String attackLocation;
private double damagesInMillions;
private Date date;

public MonsterAttack(){
}

public MonsterAttack(String monsterName, String attackLocation, double damagesInMillions, Date date){
this.monsterName = monsterName;
this.attackLocation = attackLocation;
this.damagesInMillions = damagesInMillions;
this.date = date;
}

public String getMonsterName(){
return monsterName;
}
public String getAttackLocation(){
return attackLocation;
}
public double getDamagesInMillions(){
return damagesInMillions;
}
public Date getDate(){
return date;
}
public void setMonsterName(String monsterName){
this.monsterName = monsterName;
}
public void setAttackLocation(String attackLocation){
this.attackLocation = attackLocation;
}
public void setDamagesInMillions(double damagesInMillions){
this.damagesInMillions = damagesInMillions;
}
public void setDate(Date date){
this.date = date;
}
public String toString(){
return " Monster named " + monsterName + " attacked in " + attackLocation + " causing damages of " + damagesInMillions + " dollars in " + date;
}
}

AttackMonitor

import java.util.Scanner;
import java.util.Arrays;
import java.util.Date;


public class AttackMonitor {
Scanner in = new Scanner (System.in);
MonsterAttack[] monsterArray = new MonsterAttack[5];

double[] damagesArray = new double[5];
static double damages = 0;

private void reportAttack(){
for (int i = 0; i < 5; i++){
// if (i == 0)
// System.out.println("press enter");
in.nextLine();
System.out.println("name");
String name = in.nextLine();
System.out.println("location");
String location = in.nextLine();
System.out.println("damage ");
double millions = in.nextDouble();
System.out.println("date");
damagesArray[i] = millions;
Date date = new Date();
damages = damages + millions;
MonsterAttack a = new MonsterAttack(name, location, millions, date);
monsterArray[i] = a;
}
}

private void printAttacks(){
for (int x = 0; x < monsterArray.length; x++){
System.out.println(monsterArray[x]);
}
}

private void showDamages(){
for (int i = 0; i < damagesArray.length; i++){
System.out.println("damage for attack " + (i+1) + ": " + damagesArray[i]);
}
System.out.println("total damages: " + damages);
System.out.println("average damage: " + damages/5);
}

private void findEarliestAttack () {
Date early = monsterArray[0].getDate();
for (int i = 0; i < monsterArray.length; i++){
if (early.compareTo(monsterArray[0].getDate()) > 0){
early = monsterArray[i].getDate();
}
}
System.out.println(early);
}

public void menu(){
String[] choices = { "Quit", "report attacks", "show attacks", "show damages", "find earliest attack"};
int choice;
do {
System.out.println("Enter\n 0 to quit,\n 1 to report attacks, \n 2 to show attacks, \n 3 to show damages, \n 4 to find earliest attack");;
choice = in.nextInt();
switch(choice){
case 0:
break;
case 1:
reportAttack();
break;
case 2:
printAttacks();
break;
case 3:
showDamages();
break;
case 4:
findEarliestAttack();
break;
}
} while (choice !=0);
}
}

MonitorDriver

import java.util.Scanner;
import java.util.Arrays;
import java.util.Date;
public class MonitorDriver{
public static void main (String[] args){
AttackMonitor test = new AttackMonitor();
test.menu();

}
}

In: Computer Science

This is my current code for a question that asks: "Implement the stack methods push(x) and...

This is my current code for a question that asks: "Implement the stack methods push(x) and pop() using two queues". It works well, other than I want it to work for data of type T, not just Int's. (EXCUSE THE INDENTING... CHEGG POSTING DOESNT ALLOW PROPER CODE TO BE UPLOADED... JUST COPY PASTE IT INTO ECLIPSE IDE, HIGHLIGHT ALL CODE, PRESS COMMAND+SHIFT+F AND SHOULD AUTO-FORMAT)

MY QUESTION: How could one modify this code in order to take data of type T, rather than only Int's?

PS: the code must continue to use the data structure provided.... must use the Queue class built... (can't use built-in ArrayList from Java).

HERE IS MY CODE CURRENTLY

//author: Nicolas Wills

package ass1Q1B;

public class StackUsingTwoQueues {

public Queue queue1 = new Queue();

public Queue queue2 = new Queue();

// public int s = queue1.size()+queue2.size(); //dont really use this

// variable... ignore it

public boolean inQueue1 = false; // inQueue1 is true when elements are in queue1. set to false to start means

// first add(x) will add to queue1 first

public void push(int x) { // queue1 holds data when there's an odd number of elements, queue2 holds data

// when even number of elements

if (!inQueue1) { // elements not in queue1, therefore will push to queue1, then transfer queue2

// elements to queue1

queue1.add(x); // add pushed element to previously empty queue1

int queue2StartSize = queue2.size(); // use this variable for "for-loop"... cant put "for(int i=0;

// i

// changes the return value of queue2.size().

for (int i = 0; i < queue2StartSize; i++) {

try {

queue1.add(queue2.remove()); // remove beginning element of queue1, add it to queue2

} catch (NoSuchElementException e) {

}

;

} // end for loop

inQueue1 = true;

} // end else if

else if (inQueue1) { // previous push() added to queue1, therefore add "x" to queue2.

queue2.add(x); // add pushed element to previously empty queue2

int queue1StartSize = queue1.size(); // use this variable for "for-loop"... cant put "for(int i=0;

// i

// change the return value of queue1.size().

for (int i = 0; i < queue1StartSize; i++) {

try {

queue2.add(queue1.remove()); // remove beginning element of queue1, add it to queue2

} catch (NoSuchElementException e) {

}

;

} // end for loop

inQueue1 = false;

} // end else if

}// end push method

// the running time of push O(n+1) time. n for the loop, 1 for the resize()

// operation

public Integer pop() {

Integer x = null; // very sketchy way to get around error

try {

if (inQueue1) {

x = queue1.remove(); // if the elements are currently in queue1, remove first element from queue1

} else {

x = queue2.remove(); // if the elements are currently in queue2, remove first element from queue2

}

} catch (NoSuchElementException e) {

}

;

return x;

}// end pop() method

// the running time of the pop() method is O(1)

public String printArray() {

if (inQueue1) {

return (queue1.stringedArray()); // if the elements are currently in queue1, printArray() will return a

// string version of the contents of queue1

} else

return (queue2.stringedArray()); // if the elements are currently in queue2, printArray() will return a

// string version of the contents of queue2

}

public static void main(String[] args) {

StackUsingTwoQueues myStack = new StackUsingTwoQueues();

// push elements

myStack.push(1);

System.out.println(myStack.printArray());

myStack.push(2);

System.out.println(myStack.printArray());

myStack.push(3);

System.out.println(myStack.printArray());

myStack.push(4);

System.out.println(myStack.printArray());

myStack.push(5);

System.out.println(myStack.printArray());

myStack.push(6);

System.out.println(myStack.printArray());

myStack.push(7);

System.out.println(myStack.printArray());

myStack.push(8);

System.out.println(myStack.printArray());

myStack.push(9);

System.out.println(myStack.printArray());

myStack.push(10);

System.out.println(myStack.printArray());

// pop elements

myStack.pop();

System.out.println(myStack.printArray());

myStack.pop();

System.out.println(myStack.printArray());

myStack.pop();

System.out.println(myStack.printArray());

myStack.pop();

System.out.println(myStack.printArray());

myStack.pop();

System.out.println(myStack.printArray());

myStack.pop();

System.out.println(myStack.printArray());

myStack.pop();

System.out.println(myStack.printArray());

}

}

package ass1Q1B;

//import ass1Q1.illegalOperation;

//import ass1Q1.priorityQ;

public class Queue {

int[] arr = new int[10];

int j=0; // keeps track of index of front of array

int n = 0; //number of elements in array

public int size() {

return n;

}

public boolean add(int x) { // why cant i just return void

if ((n + 1) > arr.length)

resize();

arr[(j + n) % arr.length] = x;

n++;

return true;

}

private void resize() { // only function in queue class that can be private right?

int[] b = new int[(Math.max(1, n * 2))];

for (int k = 0; k < n; k++)

b[k] = arr[(j + k) % arr.length];

arr = b;

j = 0;

}

public int remove() throws NoSuchElementException {

if (n == 0)

throw new NoSuchElementException("cant remove if theres no elements to remove");

int x = arr[j];

j = (j + 1) % arr.length;

n--;

if (arr.length >= 3 * n)

resize();

return x;

}

public String stringedArray() {

String returnString = "";

for(int i=0; i

returnString+= arr[(i+j)%(arr.length)];

}

return returnString;

}

}

In: Computer Science

Please convert this java program to a program with methods please. import java.io.*; import java.util.*; public...

Please convert this java program to a program with methods please.

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

public class Number{

public static void main(String[] args) {
  
Scanner scan = new Scanner(System.in);

System.out.println("Enter 20 integers ranging from -999 to 999 : "); //print statement

int[] array = new int[20]; //array of size 20

for(int i=0;i<20;i++){

array[i] = scan.nextInt(); //user input

if(array[i]<-999 || array[i]>999){ //check if value is inside the range

System.out.println("Please enter a number between -999 to 999");
i--;
}
}

// Now we have to create 4 array for odd,even,positive,negative number

int odd = 0; //initializing as zero
int even = 0;
int positive = 0;
int negative = 0;

for(int i=0;i<20;i++){

if(array[i]%2 == 0){ //check if even

even++; //increment
}
if(array[i]%2 != 0){ //check if odd

odd++; //increment
}
if(array[i]>0){ //check if positive

positive++; //increment
}   
if(array[i]<0){ //check if negative

negative++; //increment
}
}

//Now initializing array for all

int[] oddA = new int[odd]; //arrays of required size
int[] evenA = new int[even];
int[] positiveA = new int[positive];
int[] negativeA = new int[negative];

int countOdd = 0; //initializing as zero
int countEven = 0; //for array indexing
int countPositive = 0;
int countNegative = 0;

for(int i=0;i<20;i++){

if(array[i]%2 == 0){ //check if even

evenA[countEven] = array[i]; //Putting value
countEven++;
}
if(array[i]%2 != 0){ //check if odd

oddA[countOdd] = array[i]; //Putting value
countOdd++;
}
if(array[i]>0){ //check if positive

positiveA[countPositive] = array[i]; //Putting value
countPositive++;   
}   
if(array[i]<0){ //check if negative

negativeA[countNegative] = array[i]; //Putting value
countNegative++;   
}
}

//Difference between highest and lowest positive number

int highest = -1000; //Initialize
int lowest = 1000;

for(int i=0;i<20;i++){

if(array[i]>0 && array[i]>highest){ //condition for highest positive number

highest = array[i];
}
if(array[i]>0 && array[i]<lowest){ //condition for lowest positve number

lowest = array[i];
}
}

int diff = highest - lowest; //difference

//Sum of all negative numbers

int sumNegative = 0;

for(int i=0;i<negative;i++){

sumNegative = sumNegative + negativeA[i]; //sum of negative number
}

int input = 0;

do{

System.out.println("Enter your choice : ");

System.out.println("1. The orginal array");
System.out.println("2. The array of all odd numbers");
System.out.println("3. The array of all even numbers");
System.out.println("4. The array of all positive numbers");
System.out.println("5. The array of all negative numbers");
System.out.println("6. The highest and lowest postive value and difference between them");
System.out.println("7. The sum of all negative numbers");
System.out.println("8. Display all positive appearing in positive array whose value is less than 50");
System.out.println("9. Display all even numbers in reverse order");
System.out.println("10. Display all multiples of 5 (positive or negative)");

int choice = scan.nextInt(); //user choice

switch(choice){

case 1 :

for(int i=0;i<20;i++){

System.out.print(array[i]+" ");
}
System.out.println("");
break;

case 2 :

for(int i=0;i<odd;i++){

System.out.print(oddA[i]+" ");
}
System.out.println("");
break;

case 3 :

for(int i=0;i<even;i++){

System.out.print(evenA[i]+" ");
}
System.out.println("");
break;

case 4 :

for(int i=0;i<positive;i++){

System.out.print(positiveA[i]+" ");
}
System.out.println("");
break;

case 5 :

for(int i=0;i<negative;i++){

System.out.print(negativeA[i]+" ");
}
System.out.println("");
break;

case 6 :

System.out.println("The highest positive value is : " + highest);
System.out.println("The lowest positive value is : " + lowest);
System.out.println("The difference between the highest and lowest positve value is : " + diff);
break;

case 7 :

System.out.println("The sum of all negative number is : " + sumNegative);
break;

case 8 :

for(int i=0;i<positive;i++){

if(positiveA[i]<50){

System.out.print(positiveA[i]+" ");
}
}
System.out.println("");
break;

case 9 :

for(int i=even-1;i>=0;i--){

System.out.print(evenA[i]+" ");
}
System.out.println("");
break;

case 10 :

for(int i=0;i<20;i++){

if(array[i]%5 == 0){

System.out.print(array[i]+" ");
}
}
System.out.println("");
break;
}

System.out.println("Do you wish to continue : (1 or 0) : Press 1 to continue : ");

input = scan.nextInt();

}while(input == 1);
}
}

In: Computer Science

Skills needed to complete this assignment: linked lists, stacks. Postfix notation, is a mathematical notation in...

Skills needed to complete this assignment: linked lists, stacks.

Postfix notation, is a mathematical notation in which operators follow their operands; for instance, to add 3 and 4, one would write 3 4 + rather than 3 + 4 (infix notation). If there are multiple operations, operators are given immediately after their second operands; so, the expression written 3 − 4 + 5 in conventional notation would be written 3 4 − 5 + in postfix notation: 4 is first subtracted from 3, then 5 is added to it. An advantage of postfix notation is that it removes the need for parentheses that are required by infix notation. While 3 − 4 × 5 can also be written 3 − (4 × 5), which is different from (3 − 4) × 5. In postfix notation, the former could be written 3 4 5 × −, while the latter could be written 3 4 − 5 × or 5 3 4 − ×.

Stacks can be used to evaluate expressions in postfix notations by following these steps: • If a number is typed, push it on the stack. • If an operation is typed, depending on the operation, pop off two numbers from the stack, perform the operation, and push the result back on the stack. You should complete the Stack class and other functions in the template file (found on Carmen) so that when the user enters an expression in postfix notation, the program calculates and shows the result. In this assignment the user enters one-digit positive numbers only, but the result can be any integer. Only basic operations (i.e. +, -, /, *) are entered by the user and integer division is used in calculations. User input ends with a semicolon.

Class Stack uses a linked list to implement a stack, and it has five public member functions:

• Default constructor: initializes the stack to an empty stack • isEmpty: returns true if the stack is empty and false otherwise

• push: pushes a new number to the top of stack

• pop: removes the top of stack

• top: returns the value at the top of stack, does not remove it from stack

You must use the template file and only add you code were you see /*your code here*/. Do not modify other parts of the code. Do not use C/C++ libraries other than iostream and cstdlib.

template code

#include <iostream>
#include <cstdlib>

using namespace std;

const char SENTINEL = ';';

struct Node {
int data;
Node *link;
};

// precondition: c is initialized
// postcondition: returns true if c is '+', '-', '*' or '/'
bool isOperator(char c);

// precondition: o1 and o2 are initialized and op is an operator
// postcondition: returns op(o1, o2), e.g. if op is '-' then returns o1-o2
int calculate(int o1, int o2, char op);

// precondition: c is a digit
// postcondition: returns the integer value of c
int charToInt(char c);

class Stack {

public:
// default constructor
// initializes the stack to an empty stack
Stack();

// this is a const function, meaning it cannot change any of the member variables
// returns true if the stack is empty, false otherwise
bool isEmpty() const;

// this is a const function, meaning it cannot change any of the member variables
// returns the value at the top of stack, does not modify the stack, does not check if the stack is empty or not
int top() const;

// adds data to the top of stack
void push(int data);

// removes the top value of stack, does not return it, does nothing if the stack is empty
void pop();

private:
Node *listHead; // pointer to the head of a linked list

};

int main() {
char in;
Stack operandStack;

cout << "Enter a postfix expression (ending with " << SENTINEL << " and press Enter):\n";
cin >> in ;
while ( in != SENTINEL) {
if (isOperator( in )) {
// pop two numbers from stack
int n1, n2;
if (operandStack.isEmpty()) {
// pring error message
/*your code here*/

exit(1);
}
n2 = operandStack.top();
operandStack.pop();

if (operandStack.isEmpty()) {
// pring error message
/*your code here*/

exit(1);
}
n1 = operandStack.top();
operandStack.pop();

// push the result of calculation to the top of operandStack
/*your code here*/

} else {
// push the number to the top of opernadStack
/*your code here*/

}
cin >> in ;
}

// pop a number from the top of stack
int result;
result = operandStack.top();
operandStack.pop();

if (operandStack.isEmpty()) // nothing left in the stack
cout << "\nThe result is: " << result << endl;
else // there are still numbers in the stack
{
// pring an error message
/*your code here*/

}

return 0;
}

Stack::Stack() {
/*your code here*/
}

bool Stack::isEmpty() const {
/*your code here*/
}

int Stack::top() const {
/*your code here*/
}

void Stack::pop() {
/*your code here*/
}

void Stack::push(int data) {
/*your code here*/
}

int calculate(int o1, int o2, char op) {
/*your code here*/
}

bool isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}

int charToInt(char c) {
return (static_cast<int>(c) - static_cast<int>('0'));}

In: Computer Science

-The table below details the individual Consumer Price Indices (CPI) for individual expenditure categories for 2016...

-The table below details the individual Consumer Price Indices (CPI) for individual expenditure categories for 2016 and 2017:

CPI Category

2016

2017

Price Change

Gasoline

195.915

216.781

Apparel

122.637

120.614

College textbooks

346.15

342.34235

What was the price change between 2016 and 2017 in the gasoline expenditure category?

1. 216.781%

2. 110.65%

3. 10.65%

4. 195.915%

please explain me how to calculate and answers.

- Read the following excerpt from a U.S. Energy Information Administration Report that was published on January 9, 2018:

Crude Oil Prices. Brent crude oil averaged $54/barrel (b) in 2017, an increase of $10/b from 2016 levels. Prices increased fairly steadily through the second half of the year, with year-end prices higher than the annual average. Daily Brent spot prices ended 2017 near $67/b, which was the highest level since December 2014. The monthly average spot price of Brent crude oil increased by $2/b in December to $64/b, marking only the fourth time that monthly Brent crude oil prices averaged more than $60/b in the past 36 months

Most of the upward price movement in recent months reflects continuing draws in global oil inventory levels. EIA estimates that global petroleum and other liquid fuels inventories fell by an average of 0.4 million b/d in 2017, which was the first year of annual average draws since 2013. In addition, oil prices were supported by OPEC’s November 30, 2017, announcement to extend its crude oil supply reduction agreement through the end of 2018. Also, Brent prices increased in December because of a disruption to the North Sea’s Forties crude oil pipeline system early in the month. The Forties pipeline system is one of the primary distribution networks for Brent crude oil delivery in the North Sea, and its outage curtailed available supply in the near term. Trade press reports indicate the Forties pipeline system restarted operations in late December 2017.

Questions:

Based on the excerpt, was the increase in the gasoline expenditure category CPI due to a change in supply or demand in the market?

1. Demand, because there were several factors affecting the market that were caused by producers of crude oil. In particular, inventory levels increased, OPEC extended production increases, and there was a disruption in a major pipeline system.

2. Supply, because there were several factors affecting the market that were caused by producers of crude oil. In particular, inventory levels declined, OPEC extended production reductions, and there was a disruption in a major pipeline system.

3. Supply because price increases are generally due to production decisions. In addition, supply creates its own demand, thus the supply side of the market will determine equilibrium prices.

4. Demand because as prices rose we saw a reduction in the quantity demanded in the market. This led to the reduction in crude oil inventory levels and the production disruptions.

what is answer?

-Read the following excerpt from a Forbes article that was published on November 3, 2017:

Now department stores’ frantic plunge into the off-price sector is in danger of killing off the full-price apparel business for good, experts warn.

In addition to discounting merchandise in their full-line stores, marked-down goods are increasingly feeding the pipeline in department stores’ ever burgeoning off-price channel, from the already heavily promotional Macy’s expanding its BackstageLinks to an external site. spin-off concept to Nordstrom’s Rack format.“The off-price business is driving growth and getting bigger than the full-price channel,” said Susan LeeLinks to an external site., a partner with consultancy Simon-Kucher.

Today, Nordstrom operates 216 Nordstrom Rack off-price stores, nearly double the number of its 122 full-line stores, just as Saks Fifth Avenue’s 39-store full-line chain is a fraction of its 118-store Off 5th outlet fleet.

The Amazon Factor

Amazon isn’t doing the full-price apparel business any favors either. While fashion brands are by no means flocking to the site, still fearful of losing control of their brand image, the discount-aggressive e-tailer is gunning for apparel, and has scored some big symbolic wins, such as itspartnership with NikeLinks to an external site..

Lord & Taylor department stores, for one, recently started pricing matching AmazonLinks to an external site.. (Not to mention partnering with Wal-Mart in an online mall venture.)

Questions:

Based on the excerpt, was the decrease in the apparel expenditure category CPI due to a change in supply or demand in the market?

1. Supply. This is due to a reduction in overall competition in the low priced apparel market.

2. Supply. This is due to increased competition among suppliers in the apparel market, which reduced prices.

3. Demand because consumers tastes and preferences shifted to higher priced apparel items.

4. Demand. This is due to decreased competition among suppliers in the apparel market, which reduced prices.

In: Economics