Question

I've written this program in C++ to compare 2 pizzas using classes and it works fine....

I've written this program in C++ to compare 2 pizzas using classes and it works fine. I need to convert it to java using both buffered reader and scanner and can't get either to work.

//C++ driver class for Pizza program

#include <iostream>

#include <string>

#include <algorithm>

#include <iomanip>

using std::cout;

using std::cin;

using std::string;

using std::endl;

using std::transform;

using std::setprecision;

using std::ios;

using std::setiosflags;

#include "Pizza.h"

int main()

{

            char response = 'Y';

            while (response == 'Y')

            {          

                  //info for first pizza

                  Pizza pizza1;

                  pizza1.obtainPizzaInfo();

                  pizza1.displayCost();

                 

                  //info for second pizza

                  Pizza pizza2;

                  pizza2.obtainPizzaInfo();

                  pizza2.displayCost();

           

                  if (pizza1.calcPriceSqIn()== pizza2.calcPriceSqIn())

                  {

                        pizza1.displayBestDeal("both");

                  }

                  else

                  {

                        if (pizza1.calcPriceSqIn() < pizza2.calcPriceSqIn())

                        {

                              pizza1.displayBestDeal("first");

                        }

                        else

                        {

                              pizza2.displayBestDeal("second");

                        }//end if for unequal costs

                  }//end if for equal costs

     

            cout << "Do you want to compare more pizzas?" << endl;

            cin >> response;

            response = toupper(response);

      }//end while for response

}//end main

//class declaration (header file)

class Pizza

{

private:

            int size;

            string shape;

            double price;

     

public:

            //constructor prototypes

            Pizza();

            Pizza(int, string, double);

            //accessor prototypes

            int getSize();

            string getShape();

            double getPrice();

            //mutator prototypes

            void setSize(int);

            void setShape(string);

            void setPrice(double);

            //facilitator prototypes

            double calcSqInches();

            double calcPriceSqIn();

            void displayCost();

            void displayBestDeal(string);

            void obtainPizzaInfo();

};

//implementation section

      //constructors

Pizza::Pizza()

      {

      }//end of default constructor

Pizza::Pizza(int sz, string sh, double pr)

      {

            size = sz;

            shape = sh;

            price = pr;

      }//end of overloaded constructor

      //accessors

int Pizza::getSize()

      {

            return size;

      }//end of getSize

string Pizza::getShape()

      {

            return shape;

      }//end of getShape

double Pizza::getPrice()

      {

            return price;

      }//end of getPrice

      //mutators

void Pizza::setSize(int sz)

      {

            size = sz;

      }//end of setSize

void Pizza::setShape(string sh)

      {

            shape = sh;

      }//end of setShape

void Pizza::setPrice(double pr)

      {

            price = pr;

      }//end of setPrice

      //facilitators

double Pizza::calcSqInches()

      {

            double sqInches;

            double radius = size/2;

            const double pi = 3.142;

            if (shape=="square")

                  {

                        sqInches = size * size;

                  }

            else

                  {

                        sqInches = pi * radius * radius;

                  }

            return sqInches;

      }//end of calcSqInches

double Pizza::calcPriceSqIn()

      {

            double priceSqIn;

            priceSqIn = price/calcSqInches();

            return priceSqIn;

      }//end of calcPriceSqIn

void Pizza::displayCost()

      {

            //set all numeric output to 2 decimal places

            cout << setiosflags(ios::fixed) << setprecision(2);

            double sqInches = calcSqInches();

            cout << "This pizza is " << sqInches << " square inches." << endl;

            cout << "The cost per square inch of this " << shape << " pizza is $" << calcPriceSqIn()<< endl;

      }//end of displayCost

void Pizza::displayBestDeal(string which)

      {

            if (which == "both")

            {

                  cout << "The cost of both pizzas are the same." << endl;

                  cout << "Both pizzas cost $" << calcPriceSqIn() << " per square inch" << endl;

            }

            else

            {

                  cout << "The " << number << " (" << shape << ", " << size << "-inch) pizza is the best deal." << endl;

            }

      }//end displayBestDeal

void Pizza::obtainPizzaInfo()

{

            //information for pizza 1

            cout << "Enter the size of this pizza: ";

            cin >> size;

            cout << "Enter the price of this pizza: ";

            cin >> price;

            cout << "Enter the shape of this pizza: ";     

            cin.ignore(100, '\n');

            getline(cin, shape);

            transform(shape.begin(), shape.end(), shape.begin(), tolower);         

           

            while (shape != "round" && shape != "square")

            {

                  cout << "The shape must be round or square." << endl;

                  cout << "Enter the shape of this pizza again: " << endl;

                  getline(cin, shape);

                  transform(shape.begin(), shape.end(), shape.begin(), tolower);

            }//end while for shape

}

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

// Pizza.java : Java program for Pizza program using Scanner
import java.util.Scanner;

public class Pizza {
  
   private int size;
   private String shape;
   private double price;
   //constructors
   // default constructor
   public Pizza()
   {
       size = 0;
       shape="";
       price = 0;
   }
  
   // overloaded constructor
   public Pizza(int sz, String sh, double pr)
   {
       size = sz;
shape = sh;
price = pr;
   }
  
   //accessors
   // getSize returns the size of pizza
   public int getSize()
   {
       return size;
   }
  
   // getShape returns shape of the pizza
   public String getShape()
   {
       return shape;
   }

   // getPrice returns the price of the pizza
   public double getPrice()
   {
       return price;
   }
  
   // mutators
   // setSize sets the size of pizza
   public void setSize(int sz)
   {
       size = sz;
   }
  
   // setShape sets the shape of the pizza
   public void setShape(String sh)
   {
       shape = sh;
   }
  
   //setPrice sets the price of pizza
   public void setPrice(double pr)
   {
       price = pr;
   }
  
   //facilitators
   // returns the area of the pizza
   public double calcSqInches()
   {
       double sqInches;
double radius = size/2;
final double pi = 3.142;
if (shape=="square")
{
   sqInches = size * size;
}
else
{
   sqInches = pi * radius * radius;
}

return sqInches;
   }
  
   // returns price per square inch
   public double calcPriceSqIn()
   {
       double priceSqIn;
priceSqIn = price/calcSqInches();
return priceSqIn;
   }
  
   // display the cost of the pizza
   public void displayCost()
   {
       double sqInches = calcSqInches();

System.out.printf("This pizza is %.2f square inches.\n", sqInches);
System.out.printf("The cost per square inch of this %s pizza is $%.2f\n",shape,calcPriceSqIn());
   }
  
   public void displayBestDeal(String which)
   {
       if (which == "both")
       {
           System.out.println("The cost of both pizzas are the same.");
           System.out.printf("Both pizzas cost $%.2f per square inch\n",calcPriceSqIn());
}
else
{
System.out.printf("The %s (%s, %d-inch) pizza is the best deal.\n",which,shape,size);
}
   }
  
   // method to obtain information of the pizza
   public void obtainPizzaInfo()
   {
       //information for pizza 1
       Scanner scan = new Scanner(System.in);
System.out.print("Enter the size of this pizza: ");
size = scan.nextInt();
System.out.print("Enter the price of this pizza: ");
price = scan.nextDouble();
scan.nextLine();
System.out.print("Enter the shape of this pizza: ");   
shape = scan.nextLine();
  
while ((!shape.equalsIgnoreCase("round")) && (!shape.equalsIgnoreCase("square")))
{
System.out.println("The shape must be round or square.");
System.out.print("Enter the shape of this pizza again: ");
shape = scan.nextLine();
}//end while for shape
   }
  
   public static void main(String[] args) {
      
       Scanner scan = new Scanner(System.in);
       String response= "y";
      
       while(response.equalsIgnoreCase("y"))
       {
           //info for first pizza
Pizza pizza1 = new Pizza();
pizza1.obtainPizzaInfo();
pizza1.displayCost();

//info for second pizza
Pizza pizza2 = new Pizza();
pizza2.obtainPizzaInfo();
pizza2.displayCost();
  
if (pizza1.calcPriceSqIn()== pizza2.calcPriceSqIn())
{
pizza1.displayBestDeal("both");
}
else
{
if (pizza1.calcPriceSqIn() < pizza2.calcPriceSqIn())
{
pizza1.displayBestDeal("first");
}
else
{
pizza2.displayBestDeal("second");

}//end if for unequal costs

}//end if for equal costs
  
System.out.print("Do you want to compare more pizzas (y/n) ? ");
response = scan.nextLine();
       }

scan.close();
      
   }

}

//end of Pizza.java

Output:

2.

// Pizza.java : Java program for Pizza program using BufferedReader
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Pizza {
  
   private int size;
   private String shape;
   private double price;
   //constructors
   // default constructor
   public Pizza()
   {
       size = 0;
       shape="";
       price = 0;
   }
  
   // overloaded constructor
   public Pizza(int sz, String sh, double pr)
   {
       size = sz;
shape = sh;
price = pr;
   }
  
   //accessors
   // getSize returns the size of pizza
   public int getSize()
   {
       return size;
   }
  
   // getShape returns shape of the pizza
   public String getShape()
   {
       return shape;
   }

   // getPrice returns the price of the pizza
   public double getPrice()
   {
       return price;
   }
  
   // mutators
   // setSize sets the size of pizza
   public void setSize(int sz)
   {
       size = sz;
   }
  
   // setShape sets the shape of the pizza
   public void setShape(String sh)
   {
       shape = sh;
   }
  
   //setPrice sets the price of pizza
   public void setPrice(double pr)
   {
       price = pr;
   }
  
   //facilitators
   // returns the area of the pizza
   public double calcSqInches()
   {
       double sqInches;
double radius = size/2;
final double pi = 3.142;
if (shape=="square")
{
   sqInches = size * size;
}
else
{
   sqInches = pi * radius * radius;
}

return sqInches;
   }
  
   // returns price per square inch
   public double calcPriceSqIn()
   {
       double priceSqIn;
priceSqIn = price/calcSqInches();
return priceSqIn;
   }
  
   // display the cost of the pizza
   public void displayCost()
   {
       double sqInches = calcSqInches();

System.out.printf("This pizza is %.2f square inches.\n", sqInches);
System.out.printf("The cost per square inch of this %s pizza is $%.2f\n",shape,calcPriceSqIn());
   }
  
   public void displayBestDeal(String which)
   {
       if (which == "both")
       {
           System.out.println("The cost of both pizzas are the same.");
           System.out.printf("Both pizzas cost $%.2f per square inch\n",calcPriceSqIn());
}
else
{
System.out.printf("The %s (%s, %d-inch) pizza is the best deal.\n",which,shape,size);
}
   }
  
   // method to obtain information of the pizza
   public void obtainPizzaInfo() throws IOException
   {
       //information for pizza 1
       BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the size of this pizza: ");
size = Integer.parseInt(reader.readLine());
System.out.print("Enter the price of this pizza: ");
price = Double.parseDouble(reader.readLine());
//scan.nextLine();
System.out.print("Enter the shape of this pizza: ");   
shape = reader.readLine();
  
while ((!shape.equalsIgnoreCase("round")) && (!shape.equalsIgnoreCase("square")))
{
System.out.println("The shape must be round or square.");
System.out.print("Enter the shape of this pizza again: ");
shape = reader.readLine();
}//end while for shape
   }
  
   public static void main(String[] args) throws IOException {
      
       BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
       String response= "y";
      
       while(response.equalsIgnoreCase("y"))
       {
           //info for first pizza
Pizza pizza1 = new Pizza();
pizza1.obtainPizzaInfo();
pizza1.displayCost();

//info for second pizza
Pizza pizza2 = new Pizza();
pizza2.obtainPizzaInfo();
pizza2.displayCost();
  
if (pizza1.calcPriceSqIn()== pizza2.calcPriceSqIn())
{
pizza1.displayBestDeal("both");
}
else
{
if (pizza1.calcPriceSqIn() < pizza2.calcPriceSqIn())
{
pizza1.displayBestDeal("first");
}
else
{
pizza2.displayBestDeal("second");

}//end if for unequal costs

}//end if for equal costs
  
System.out.print("Do you want to compare more pizzas (y/n) ? ");
response = reader.readLine();
       }
      
       reader.close();
      
   }

}

//end of program

Output:

Add a comment
Know the answer?
Add Answer to:
I've written this program in C++ to compare 2 pizzas using classes and it works fine....
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • CODES: main.cpp #include <iostream> #include <string> #include "ShoppingCart.h" using namespace std; char PrintMenu() { char answer;...

    CODES: main.cpp #include <iostream> #include <string> #include "ShoppingCart.h" using namespace std; char PrintMenu() { char answer; cout << "MENU" << endl; cout << "a - Add item to cart" << endl; cout << "d - Remove item from cart" << endl; cout << "c - Change item quantity" << endl; cout << "i - Output items' descriptions" << endl; cout << "o - Output shopping cart" << endl; cout << "q - Quit" << endl << endl; while (true) {...

  • USE C++. Just want to confirm is this right~? Write a class named RetailItem that holds...

    USE C++. Just want to confirm is this right~? Write a class named RetailItem that holds data about an item in a retail store. The class should have the following member variables: description: A string that holds a brief description of the item. unitsOnHand: An int that holds thw number of units currently in inventory. price: A double that holds that item's retail price. Write the following functions: -appropriate mutator functions -appropriate accessor functions - a default constructor that sets:...

  • Consider the following C++code snippet and what is the output of this program? # include<iostream> using...

    Consider the following C++code snippet and what is the output of this program? # include<iostream> using namespace std; void arraySome (int[), int, int); int main () const int arraysize = 10; int a[arraysize]-1,2,3,4,5, 6,7,8,9,10 cout << "The values in the array are:" << endl; arraySome (a, 0, arraySize) cout<< endl; system ("pause") return 0; void arraySome (int b[], int current, int size) if (current< size) arraySome (b, current+1, size); cout << b[current] <<""; a) Print the array values b) Double...

  • Need to implement Account.cpp and AccountManager.cpp code //Account.hpp #ifndef _ACCOUNT_HPP_ #define _ACCOUNT_HPP_ #include <string> using std::string;...

    Need to implement Account.cpp and AccountManager.cpp code //Account.hpp #ifndef _ACCOUNT_HPP_ #define _ACCOUNT_HPP_ #include <string> using std::string; class Account { public: Account(); Account(string, double); void deposit(double); bool withdraw(double); string getName() const; double getBalance() const; private: string name; double balance; }; #endif ////////////////////////////////////////////// //AccountManager.hpp #ifndef _ACCOUNT_MANAGER_HPP_ #define _ACCOUNT_MANAGER_HPP_ #include "Account.hpp" #include <string> using std::string; class AccountManager { public: AccountManager(); AccountManager(const AccountManager&); //copy constructor void open(string); void close(string); void depositByName(string,double); bool withdrawByName(string,double); double getBalanceByName(string); Account getAccountByName(string); void openSuperVipAccount(Account&); void closeSuperVipAccount(); bool getBalanceOfSuperVipAccount(double&) const;...

  • When running the program at the destructor  an exception is being thrown. Can someone help me out?...

    When running the program at the destructor  an exception is being thrown. Can someone help me out? vararray.h: #ifndef VARARRAY_H_ #define VARARRAY_H_ class varArray { public:    varArray(); // void constructor    int arraySize() const { return size; } // returns the size of the array    int check(double number); // returns index of element containg "number" or -1 if none    void addNumber(double); // adds number to the array    void removeNumber(double); // deletes the number from the array   ...

  • In C++ ***//Cat.h//*** #ifndef __Cat_h__ #define __Cat_h__ #include <string> using namespace std; struct Cat { double...

    In C++ ***//Cat.h//*** #ifndef __Cat_h__ #define __Cat_h__ #include <string> using namespace std; struct Cat { double length; double height; double tailLength; string eyeColour; string furClassification; //long, medium, short, none string furColours[5]; }; void initCat (Cat&, double, double, double, string, string, const string[]); void readCat (Cat&); void printCat (const Cat&); bool isCalico (const Cat&); bool isTaller (const Cat&, const Cat&); #endif ***//Cat.cpp//*** #include "Cat.h" #include <iostream> using namespace std; void initCat (Cat& cat, double l, double h, double tL, string eC,...

  • //Need help ASAP in c++ please. Appreciate it! Thank you!! //This is the current code I have. #include <iostream> #include <sstream> #include <iomanip> using namespace std; cl...

    //Need help ASAP in c++ please. Appreciate it! Thank you!! //This is the current code I have. #include <iostream> #include <sstream> #include <iomanip> using namespace std; class googlePlayApp { private: string name; double rating; int numInstalls; int numReviews; double price;    public: googlePlayApp(string, double, int, int, double); ~ googlePlayApp(); googlePlayApp();    string getName(); double getRating(); int getNumInstalls(); int getNumReviews(); string getPrice();    void setName(string); void setRating(double); void setNumInstalls(int); void setNumReviews(int); void setPrice(double); }; googlePlayApp::googlePlayApp(string n, double r, int ni, int nr, double pr)...

  • c++ programming : everything is done, except when you enter ("a" ) in "F" option ,...

    c++ programming : everything is done, except when you enter ("a" ) in "F" option , it does not work. here is the program. #include <iostream> #include <string> #include <bits/stdc++.h> #include <iomanip> #include <fstream> using namespace std; #define MAX 1000 class Inventory { private: long itemId; string itemName; int numberOfItems; double buyingPrice; double sellingPrice; double storageFees; public: void setItemId(long id) { itemId = id; } long getItemId() { return itemId; } void setItemName(string name) { itemName = name; } string...

  • fully comments for my program, thank you will thumb up #include <iostream> #include <fstream> #include <string>...

    fully comments for my program, thank you will thumb up #include <iostream> #include <fstream> #include <string> #include <iomanip> using namespace std; struct book { int ISBN; string Author; string Title; string publisher; int Quantity; double price; }; void choice1(book books[], int& size, int MAX_SIZE) { ifstream inFile; inFile.open("inventory.txt"); if (inFile.fail()) cout <<"file could not open"<<endl; string str;    while(inFile && size < MAX_SIZE) { getline(inFile, str); books[size].ISBN = atoi(str.c_str()); getline(inFile, books[size].Title);    getline(inFile, books[size].Author); getline(inFile, books[size].publisher);          getline(inFile,...

  • I need to make a few changes to this C++ program,first of all it should read...

    I need to make a few changes to this C++ program,first of all it should read the file from the computer without asking the user for the name of it.The name of the file is MichaelJordan.dat, second of all it should print ,3 highest frequencies are: 3 words that occure the most.everything else is good. #include <iostream> #include <map> #include <string> #include <cctype> #include <fstream> #include <iomanip> using namespace std; void addWord(map<std::string,int> &words,string s); void readFile(string infile,map<std::string,int> &words); void display(map<std::string,int>...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT