Open Side Menu Go to the Top
Register
aisflat439's Homework thread aisflat439's Homework thread

02-26-2013 , 08:19 PM
Rather than create a new post each week, I think I'll just post one thread that has my homework. Your comments about what I'm doing and thoughts are welcome. Just please don't give me answers point me in a direction instead so I can continue to improve at these concepts.

This week we are overloading operators in C++. My understanding of this concept is not good yet at all. The instructions were fairly specific so I still have to change a few things. I'm annoyed at C++ now and I'm gonna do some Java stuff instead for a few hours.

my .h file
Code:
# ifndef MONEY_H
# define MONEY_H

class Money
{
private:

    
public:
    double dAmount;
    long _cents;
    double dDecimalAmount;
    //Start with your constructor
    Money ();
    // make default constructor
    Money(double dAnyThingCanGoHere);
    //Copy constructor
    Money(const Money&);
    
    //setters and getters
    void setMoneyAmount(double);
    double getMoneyAmount();
    long getMoneyAsInt();
    Money& operator=(const Money&);
    Money& operator+=(const Money&); 
    const Money operator+(const Money &other) const;
    bool operator<(const Money&) const;
    bool operator>(const Money&) const; 
};


#endif
Money Method Files (you'll see my notes to myself as well)
Code:
#include <iomanip>
#include <iostream>
#include "Money.h"

//Money Default constructor
Money::Money ()
{
    double dAmount = 1.00;
    long _cents = 3;
}
// Money Constructor
// Tells Money how to set the fields in default.
// Anything can go here because it's a constructor
// We are just telling Money to expect a double
Money::Money (double dAnythingCanGoHere)
{
    // Here we tell the Money class that a setMoneyAmount
    // function will adjust the amount held in dAmount
    // This same function does our int for us which may be bad
    setMoneyAmount(dAnythingCanGoHere);
}

// Copy constructor
    //Not really sure if I need this but in order to build it
    //All i need is all the Values you need to make any object
    // and set them equal to the copy object and build a copy
    //constructor over in .h
Money::Money(const Money& copyObject)
{
    dAmount = copyObject.dAmount;
    _cents = copyObject._cents;       
}
//Methods (relax these are just functions with slightly diffent syntax)

//This function passes in an amount by reference 
//and sets dAmount (the private double in the Money class
//equal to that amount.  It also adjusts _cents which may be bad.
void Money::setMoneyAmount(double dUserAmount)
{
    double dTemp = 0;
    dTemp = dUserAmount;
    dAmount = dUserAmount;
    dTemp = dTemp * 100;
    _cents = static_cast<long>(dTemp);
    
}
//this function can be used any time in main to get the amount held in 
//dAmount
double Money::getMoneyAmount()
{
    return  dAmount;   
}
// This function is a getter.  If I call it before changing the value in 
// _cents it should just return 3 
long Money::getMoneyAsInt()
{
    return _cents;
}
// equals operator
// Take a const-reference to the right-hand side of the assignment.
// Return a non-const reference to the left-hand side.
// This only gives me 6 places and I don't know why.  Maybe has 
// something to do with my long 
Money& Money::operator =(const Money& rhsObject)
{
    dAmount = rhsObject.dAmount;
    return *this;
}
//  plus equals (a=a+b)
Money& Money::operator+=(const Money &rhsObject)
{
    dAmount = dAmount + rhsObject.dAmount;
    return *this;
}
//  plus (a+b)
const Money Money::operator+(const Money &other) const
{
    return Money(*this) += other;
} 
//   Less than operator (<)
bool Money::operator< (const Money &rightObj) const
{
    return dAmount < rightObj.dAmount;
}
//   Greater than (>) operator
bool Money::operator> (const Money &rightObj) const
{
    return dAmount > rightObj.dAmount;
}
Main prog.
Code:
#include <iomanip>
#include <iostream>
#include "Money.h"

using namespace std;

int main()
{
    double dUserInput = 0;
    Money m1, m2, m3;
            
    cout << "Please enter a money value: " << endl;
    cin >> dUserInput;
    m1.setMoneyAmount(dUserInput);
    //cout << endl << m1.getMoneyAsInt() << endl;
    // create a money object with user input
    cout << "m1 set to " << m1.getMoneyAmount() << endl << endl;

//    cout << "also as an int " << m1.getMoneyAsInt() << endl;

    // create money obect 2 by = to money obj 1
    cout << "Creating a new Money m2 object using the assignment operator: " << endl;
    m2 = m1;
    cout << "m2.asDecimal(): $" << m2.getMoneyAmount() << endl << endl;
    
    //create money 3 by adding  money 1 and 2
    cout << "Creating a new Money m3 object by adding m1 + m2: " << endl;
    m3 = (m1 + m2);    
    cout << "m3.asDecimal(): $" << m3.getMoneyAmount() << endl << endl;
    //cout << endl << m3.getMoneyAsInt() << endl;
    // compare money 1 and 3 using an if statement
    cout << "Comparing m1 and m3: " << endl;
    if ( m1 < m3 ){
          cout << m3.getMoneyAmount() << " is greater than " << m1.getMoneyAmount() << endl << endl;
          }
      else if (m1 > m3){
          cout << m1.getMoneyAmount() << " is greater than " << m3.getMoneyAmount() << endl << endl;
          }
            else {
            cout << m1.getMoneyAmount() << " is equal to " << m3.getMoneyAmount() << endl << endl;
            }
    
    cout << "Using += to add 5 to m3: " << endl;
    m3 += 5;
    // this sets a flag but I'm not sure what everything means
    cout.setf(ios::fixed);
    cout << "m3.AsDecimal(): $" << setprecision(2) << m3.getMoneyAmount() << endl;
    
    system("PAUSE");
    return 0;
}
aisflat439's Homework thread Quote
03-05-2013 , 04:01 PM
This week in class we learned about three concepts, the Enum Type, Structs and the selection operator ( -> ).

The homework was the easiest that I've encountered in this class. I think that all the time I spent on pointers earlier in the semester made understanding dynamic arrays of objects easy as could be. The selection operator is a time saver as well.

I'm still not really sure why you would ever use a Struct in practice so if any of you have experience using them and why I'd like to hear it.

Here is the homework assignment for this week. I'm always open to comments on this as well. I also had to create the same I/O for a struct rather than a class. I haven't done this yet. I fugured going from Class to Struct would be easier than Struct to Class.

**Note: I'm still using both system("Pause") and namespace as directed by prof**

my .h File
Code:
#ifndef BABY_H
#define BABY_H
#include <string>
using namespace std;

enum EyesEnum {blue, brown, black, hazel, green};

class Baby
{
    private:
        int _weight;
        double _length;
        string _day;
        EyesEnum _eyeColor;
        
    public:

        //default
        Baby();
        //constructor
        Baby(int, double, string, EyesEnum);
        //Setters and getters
        void setWeight(int);
        void setLength(double);
        void setDay(string);
        // Your enum setter takes the name of the ENUM that its using
        void setEyeColor(EyesEnum);
        //PrintMethod
        int getWeight();
        double getLength();
        string getDay();
        //your enum getter returns the name of the ENUM (not an enum)
//        EyesEnum getEyeColor();
        string getEyes();
        //Destructor
//        ~Baby();
};


#endif
Method Files

Code:
#include <iostream>
#include <string>
#include "Baby.h"

using namespace std;

Baby::Baby()
{
}

//Baby Default constructor
Baby::Baby(int iWeight, double dLength, string sDay, EyesEnum eyeColor)
{
    _weight = 1;
    _length = 3.00;
    _day = "sun";
    _eyeColor = eyeColor;
    
}
/*// Tells Baby how to Build a baby
Baby::Baby (int iWeight, double dLength, string sDay, EyesEnum eyeColor)
{
    setWeight(iWeight);
    setLength(dLength);    
    setDay(sDay);
    setEyeColor(eyeColor);
}
*/
void Baby::setWeight(int iUserInputWeight)
{
    _weight = iUserInputWeight;   
}

void Baby::setLength(double dUserInputLength)
{
    _length = dUserInputLength;   
}

void Baby::setDay(string sUserInputDay)
{
    _day = sUserInputDay;
}

int Baby::getWeight()
{
    return _weight;
}

double Baby::getLength()
{
    return _length;
}

string Baby::getDay()
{
    return _day;   
}
// Enum below
void Baby::setEyeColor(EyesEnum eyeColor)
{
    _eyeColor = eyeColor;
}

//EyesEnum Baby::getEyeColor()
//{
//    return _eyeColor;
//}

string Baby::getEyes()
{
    if (_eyeColor == hazel)
    {
        return "Hazel";
    }   
    else if (_eyeColor == blue)
    {
        return "Blue";
    }
    else if (_eyeColor == green)
    {
        return "Green";
    }
    else if (_eyeColor == black)
    {
        return "Black";
    }
    else
    {
        return "Brown";
    }
}
Main()

Code:
#include <iomanip>
#include <iostream>
#include <string>
#include "Baby.h"

using namespace std;

int main()
{
    int iOunces = 0, iNumBabies = 0, iEyeColor = 0;
    double dInches = 0.00;
    string sWeekday = "";
  
    cout << "Please enter the number of babies: ";
    cin >> iNumBabies;   
    cout << endl;
    Baby* pBaby = new Baby[iNumBabies];
    
    for (int i=0; i < iNumBabies; i++)
    {
    cout << "Please enter baby #" << i + 1 << "'s weight <ounces>: ";
    cin >> iOunces;
    (pBaby + i)->setWeight(iOunces);
    cout << "Please enter babt #" << i + 1 << "'s height <inches>: ";
    cin >> dInches;
    (pBaby + i)->setLength(dInches);
    cout << "Please enter the day of the week that baby #" << i + 1 << " was born: ";
    cin >> sWeekday;
    (pBaby + i)->setDay(sWeekday);
    cout << "Please enter the eye color for Baby #" << i + 1 << endl;
    cout << "<Blue = 1, Brown = 2, Black = 3, Hazel = 4, Green = 5>: ";
    cin >> iEyeColor;
    (pBaby + i)->setEyeColor(static_cast<EyesEnum>(iEyeColor - 1));
    cout << endl;
    }
    
    for (int i = 0; i < iNumBabies; i++)
    {    
    cout << endl << "Baby #" << i + 1 << "'s info: " << endl;
    cout << "Height: " << (pBaby + i)->getLength() << " inches" << endl;
    cout << "Weight: " << (pBaby + i)->getWeight() << " ounces" << endl;
    cout << "Born on: " << (pBaby + i)->getDay() << endl;
    cout << "Eye Color: " << (pBaby + i)->getEyes() << endl << endl; 
    }    
    cout << endl;
    
    delete[] pBaby;
    
    system("PAUSE");
    return EXIT_SUCCESS;
}
aisflat439's Homework thread Quote
03-05-2013 , 06:55 PM
did you have any questions or anything?
aisflat439's Homework thread Quote
03-05-2013 , 07:02 PM
i haven't actually read your programs because it's hard to do in the tiny code window so if you have any specific questions post them here and i'll look
aisflat439's Homework thread Quote
03-06-2013 , 10:35 PM
@ Fubster - I've been posting my completed assignments for the forum to comment on if they see something they would have done differently.

I wrote this for my Java class. The instructions were to ask the user for a year and evaluate if it's a leap year. Since I'm ahead in the book I added the pop up dialogue boxes.

My evaluation of leap years is effective but it seems like a lot of code for something so simple. Would you have written the if statements in a more concise way?

Code:
import javax.swing.JOptionPane;

public class LeapYear {

	//*******************************************************
	//	Determines if the user inputs a leap year
	//*******************************************************
	public static void main(String[] args) {
		int year = 1900;
		boolean isLeapYear;
		String numStr, result;
		int again;
		
		do 
		{	
			numStr = JOptionPane.showInputDialog("Enter a year :");
			// add the break statement to exit the loop on cancel
			if (numStr == null)break;
			year = Integer.parseInt(numStr);
			
			if (year % 400 == 0)
				{
				isLeapYear = true;
				}
			else if (year % 100 == 0)
				{
				isLeapYear = false;
				}
			else if (year % 4 == 0)
				{
				isLeapYear = true;
				}
			else 
				{	
				isLeapYear = false;
				}	
			
			if (year < 1582)
				{
				result = "Gregorian calendar starts in 1582.";
				}
			else if (isLeapYear == false)
				{
				result = "The year " + year + " is not a leap year.";
				}
			else 
				{
				result = "The year " + year + " is a leap year!";
				}
			
			JOptionPane.showMessageDialog(null, result);
			again = JOptionPane.showConfirmDialog(null, "Do Another?","Check Another Leap Year?",JOptionPane.YES_OPTION);
		}
		
		while (again == JOptionPane.YES_OPTION);

	}

}
aisflat439's Homework thread Quote
03-07-2013 , 12:16 AM
If you care about terseness, then you could definitely condense down your if blocks.

Code:
private static boolean isLeapYear(int year) {
    if ( (year % 4 == 0 && year % 100 != 0 ) 
         || year % 400 == 0) {
        return true;
    }
    return false;
}
aisflat439's Homework thread Quote
03-07-2013 , 01:19 AM
That is so much simpler to read...

I haven't gotten to the point where I can look at a piece of code I've written and simplify it. I'm assuming that comes with experience and more classes.
aisflat439's Homework thread Quote
03-07-2013 , 02:50 AM
I agree generally that being able to refactor your code so that it is easier to read comes with experience.

In this specific case I'm just following my rule of thumb that if you have a bunch of if else blocks then there's probably a way to make the logic clearer (I find if else blocks kinda hard to read, personally).

The other thing is that I thought it would be easier to read to make isLeapYear a function. That way you're separating the calculation (isLeapYear) from the display (your main function). Breaking things up like that makes things easier to follow IMO.

To be fair, this kind of refactoring isn't really a big deal for small programs, especially if you're still learning. But once you have an application with hundreds of files and thousands of lines of code then making the logic easy to read and follow makes a big difference.
aisflat439's Homework thread Quote
03-27-2013 , 05:17 PM
Starting in on inheritance this week. I understood the homework quite well and had little difficulty with the problem. I assume that with practice making classes that use inheritance it will take less time. The example is again quite boring. The next few weeks we will be learning vectors and from what I understand that is pretty challenging. I don't know that there is much to say about this problem but if you see something you would like to comment on I always appreciate feedback as my prof doesn't provide much.

Assignment was to make a book class that had data members Author, Title, ISBN, and Price. Author and Title were to be arguments. Create a derived class that adds grade level and overrides if price is below $20 and above $80.

Book.h

Book.cpp


Textbook.h


Textbook.cpp


MainProgram
aisflat439's Homework thread Quote
03-27-2013 , 06:36 PM
-It is generally a bad practice to put "using namespace std" in a .h file. Use "using std::string" instead.
-You should always name your parameters in the .h file, even though it isn't required. So do "Book(string title, string author);" and "setTitle(string title);", etc.
-How are you storing an ISBN number in an int? Isn't an ISBN like a 13 digit number with dashes?
-Since you are overriding setPrice() in a derived class of Book, you should use the "virtual" keyword: "virtual void setPrice(double price);"
-Textbook::setPrice() checks the price correctly, but before you call setPrice(), the price will be initialized to an invalid value.
-The line "_price = price;" in the else clause of Textbook::setPrice() is not indented properly. In fact, if you use the curly braces around the if clause, you should probably also use them around the else clause even though they are not required, and vice versa, for readability purposes.
aisflat439's Homework thread Quote
03-28-2013 , 04:31 AM
lots of stuff taught in c++ classes is simplified for pedagogical purposes.
aisflat439's Homework thread Quote
03-28-2013 , 04:40 AM
Quote:
Originally Posted by aisflat439
Starting in on inheritance this week. I understood the homework quite well and had little difficulty with the problem. I assume that with practice making classes that use inheritance it will take less time. The example is again quite boring. The next few weeks we will be learning vectors and from what I understand that is pretty challenging. I don't know that there is much to say about this problem but if you see something you would like to comment on I always appreciate feedback as my prof doesn't provide much.

Assignment was to make a book class that had data members Author, Title, ISBN, and Price. Author and Title were to be arguments. Create a derived class that adds grade level and overrides if price is below $20 and above $80.

Book.h

Book.cpp


Textbook.h


Textbook.cpp


MainProgram
i'm far from an expert, but everything seems fine. i think that getMember functions are supposed to be const. Your comments are really mysterious.

There's no reason to have the private: there since you're not declaring any private members, but I assume that's part of the homework instructions.

What is EXIT_SUCCESS? I've never seen that. Is that #define 'd somewhere maybe?
aisflat439's Homework thread Quote
03-28-2013 , 04:42 AM
Quote:
-Since you are overriding setPrice() in a derived class of Book, you should use the "virtual" keyword: "virtual void setPrice(double price);"
good call, didn't see that.
aisflat439's Homework thread Quote
03-28-2013 , 06:15 AM
Quote:
Originally Posted by Fubster
What is EXIT_SUCCESS? I've never seen that. Is that #define 'd somewhere maybe?
<cstdlib>
aisflat439's Homework thread Quote
03-28-2013 , 07:04 AM
Quote:
Originally Posted by aisflat439
Starting in on inheritance this week. I understood the homework quite well and had little difficulty with the problem. I assume that with practice making classes that use inheritance it will take less time. The example is again quite boring. The next few weeks we will be learning vectors and from what I understand that is pretty challenging. I don't know that there is much to say about this problem but if you see something you would like to comment on I always appreciate feedback as my prof doesn't provide much.

Assignment was to make a book class that had data members Author, Title, ISBN, and Price. Author and Title were to be arguments. Create a derived class that adds grade level and overrides if price is below $20 and above $80.

Book.h

Book.cpp


Textbook.h


Textbook.cpp


MainProgram
On your book class. There are different types of books like say fiction and non fiction. I'm guessing that your inheritance assignments will inherit the book class IE it will be the base class.
aisflat439's Homework thread Quote
03-29-2013 , 09:41 AM
Quote:
Originally Posted by Fubster
i'm far from an expert, but everything seems fine. i think that getMember functions are supposed to be const. Your comments are really mysterious.
Since these are academic examples my Comments are often notes to myself explaining how to achieve a certain result. Typically I'll solve the homework the easiest way I know how and then add in the concepts that are specific to the homework.
aisflat439's Homework thread Quote
03-29-2013 , 09:57 AM
Quote:
Originally Posted by sards
-It is generally a bad practice to put "using namespace std" in a .h file. Use "using std::string" instead.
We have discussed this in class some. It is how the prof expects the assignment to be completed. Once I complete this class I intend to make that switch.

Quote:
Originally Posted by sards
-You should always name your parameters in the .h file, even though it isn't required. So do "Book(string title, string author);" and "setTitle(string title);", etc.
This conflicts with my profs guidance. I'm curious about what advantage naming params in the .h has vs the other way.

Quote:
Originally Posted by sards
-How are you storing an ISBN number in an int? Isn't an ISBN like a 13 digit number with dashes?
It was just a task. Were I to need to output the format I think in the getISBN() function I switch to void and output it as a statement with the dashes.

Quote:
Originally Posted by sards
-Since you are overriding setPrice() in a derived class of Book, you should use the "virtual" keyword: "virtual void setPrice(double price);"
We learned virtual last night. And, were I to write this now I would definitely make it virtual, especially since the abstract book isn't ever going to be called.

Quote:
Originally Posted by sards
-Textbook::setPrice() checks the price correctly, but before you call setPrice(), the price will be initialized to an invalid value.
That's true but follows the directions. I would want to have all the data in the TextBook class and want to validate the data in the TextBook class. I suppose that I would create a layer of temporary data that would get validated before storing it as actual data? TBH I can't think of how I would do that. Great thought.
Quote:
Originally Posted by sards
-The line "_price = price;" in the else clause of Textbook::setPrice() is not indented properly. In fact, if you use the curly braces around the if clause, you should probably also use them around the else clause even though they are not required, and vice versa, for readability purposes.
Makes sense. I'll make this adjustment in the future.
aisflat439's Homework thread Quote
03-29-2013 , 10:08 AM
Quote:
Originally Posted by adios
On your book class. There are different types of books like say fiction and non fiction. I'm guessing that your inheritance assignments will inherit the book class IE it will be the base class.
Yes in this example the Book class was to be an abstract book class that would never actually get called. Last night we learned about virtual functions, abstract classes, and polymorphism. I think part of the reason this assignments was so peculiar was that we hadn't been introduced to these three concepts. I completed this assignment quite easily but felt confused about why a book class would ever exist. Now I see that it would be an abstract class usually. The new assignment seems significantly more difficult but that may just have to do with my lack of comfort with pointers.

@ all - thanks again for taking the time to look and point things out. I appreciate the help learning.
aisflat439's Homework thread Quote
03-29-2013 , 06:21 PM
Quote:
Originally Posted by aisflat439
This conflicts with my profs guidance. I'm curious about what advantage naming params in the .h has vs the other way.
If you have something in a .h file like "void doSomething(int, float, char, double);" it is not clear at all what those parameters are supposed to be. If I were reading the code in the .h file, I would have to consult the .cpp file to find the answer. Sometimes the .cpp file isn't even available, and all you have is a .h file and a binary library. Commenting the function will help, but which of the following would you rather see?
Code:
// Returns (2nd parameter * 3.5) ^ (1st parameter)
float doSomeMath(int, float);
or
Code:
// Returns (base * 3.5) ^ exponent;
float doSomeMath(int exponent, float base);
Naming the parameters in the .h file will also help with things like IDE support (Intellisense) and automatic documentation generation. And finally, the only downside to it is that you have to do slightly more typing.
aisflat439's Homework thread Quote
04-04-2013 , 04:32 PM
I had to do this histogram assignment for school. Make an array of 100 random int then output an asterix for each int between 0-9, 10-19 etc...

I completed the homework well enough for the class (due sunday). I don't really like my solution and at the end of this code have started working on a better solution. I can't quite verbalize what I'm thinking just now but I feel like i could make an array of asterix that adjust themselves after looping through the array of random numbers?

I dunno. That or I'm thinking of making the asterix an object that checks itself versus the random number array?

Anyone have thoughts about alternative ways to look at this?

Code:
import java.util.Random;
public class Histogram {

	// Creates random numbers outputs them as a histogram
	
	public static void main(String[] args) {
		
		int star1 = 0, star2 = 0, star3 = 0, star4 = 0, star5 = 0;
		int star6 = 0, star7 = 0, star8 = 0, star9 = 0, star0 = 0;
		
		int[] list = new int[100];		
		//Create an array of 100 random numbers
		for (int i = 0; i < 100; i++)
		{
			list[i] = new Random().nextInt(99);
		}
		// populate those into stars for later use
		for (int i = 0; i < list.length; i++)
		{
			if ((list[i] > 0) && (list[i] < 10)) star1++;
			else if ((list[i] >= 10) && (list[i] < 19)) star2++;
			else if ((list[i] >= 20) && (list[i] < 29)) star3++;
			else if ((list[i] >= 30) && (list[i] < 39)) star4++;
			else if ((list[i] >= 40) && (list[i] < 49)) star5++;
			else if ((list[i] >= 50) && (list[i] < 59)) star6++;
			else if ((list[i] >= 60) && (list[i] < 69)) star7++;
			else if ((list[i] >= 70) && (list[i] < 79)) star8++;
			else if ((list[i] >= 80) && (list[i] < 89)) star9++;
			else star0++;					
		}
		//print 
		System.out.print(" 0-9  | ");
		for (int i = 0; i < star1; i++)
			System.out.print("*");
		
		System.out.print("\n10-19 | ");
		for (int i = 0; i < star2; i++)
			System.out.print("*");
		
		System.out.print("\n20-29 | ");
		for (int i = 0; i < star3; i++)
			System.out.print("*");
		
		System.out.print("\n30-39 | ");
		for (int i = 0; i < star4; i++)
			System.out.print("*");		
		
		System.out.print("\n40-49 | ");
		for (int i = 0; i < star5; i++)
			System.out.print("*");
		
		System.out.print("\n50-59 | ");
		for (int i = 0; i < star6; i++)
			System.out.print("*");
		
		System.out.print("\n60-69 | ");
		for (int i = 0; i < star7; i++)
			System.out.print("*");	
		
		System.out.print("\n70-79 | ");
		for (int i = 0; i < star8; i++)
			System.out.print("*");
		
		System.out.print("\n80-89 | ");
		for (int i = 0; i < star9; i++)
			System.out.print("*");
		
		System.out.print("\n90-99 | ");
		for (int i = 0; i < star0; i++)
			System.out.print("*");	
	// attempt at a better answer

		int[] tList = new int[100];		
		int[] tStar = new int[tList.length]; 
		//Create an array of 100 random numbers
		for (int i = 0; i < 100; i++)
		{
			tList[i] = new Random().nextInt(99);
		}
		
		for (int i = 0; i < 100; i++)
			for (int j = 0; j < 100; j++)
			{ 
				if ((tList[i] >= 00)&&(tList[i] < 9)) tStar[j]++;
				else if ((tList[i] >= 10)&&(tList[i] < 19)) tStar[j]++;
				else tStar[j]++;
			}
	}	

}
aisflat439's Homework thread Quote
04-08-2013 , 08:07 AM
Quote:
Originally Posted by aisflat439
Rather than create a new post each week, I think I'll just post one thread that has my homework. Your comments about what I'm doing and thoughts are welcome. Just please don't give me answers point me in a direction instead so I can continue to improve at these concepts.
Good idea. If only I thought of doing this a year ago. Instead, I plague the MSLHE NC thread. Oh well.

Now for some ~useful comments.

Quote:
Originally Posted by aisflat439
Code:
import java.util.Random;
public class Histogram {

	// Creates random numbers outputs them as a histogram
	
	public static void main(String[] args) {
		
		int star1 = 0, star2 = 0, star3 = 0, star4 = 0, star5 = 0;
		int star6 = 0, star7 = 0, star8 = 0, star9 = 0, star0 = 0;
There are less painful ways of representing multiple entities of the same variable type, imo.

Code:
		int[] list = new int[100];		
		//Create an array of 100 random numbers
		for (int i = 0; i < 100; i++)
		{
			list[i] = new Random().nextInt(99);
		}
Check the array library for functions on arrays, there might be something that does this in one line.

Code:
		// populate those into stars for later use
		for (int i = 0; i < list.length; i++)

		{
			if ((list[i] > 0) && (list[i] < 10)) star1++;
			else if ((list[i] >= 10) && (list[i] < 19)) star2++;
			else if ((list[i] >= 20) && (list[i] < 29)) star3++;
			else if ((list[i] >= 30) && (list[i] < 39)) star4++;
			else if ((list[i] >= 40) && (list[i] < 49)) star5++;
			else if ((list[i] >= 50) && (list[i] < 59)) star6++;
			else if ((list[i] >= 60) && (list[i] < 69)) star7++;
			else if ((list[i] >= 70) && (list[i] < 79)) star8++;
			else if ((list[i] >= 80) && (list[i] < 89)) star9++;
			else star0++;					
		}
Haven't you already looped through your array once?

Code:
		//print 
		System.out.print(" 0-9  | ");
		for (int i = 0; i < star1; i++)
			System.out.print("*");
		
		System.out.print("\n10-19 | ");
		for (int i = 0; i < star2; i++)
			System.out.print("*");
		
		System.out.print("\n20-29 | ");
		for (int i = 0; i < star3; i++)
			System.out.print("*");
		
		System.out.print("\n30-39 | ");
		for (int i = 0; i < star4; i++)
			System.out.print("*");		
		
		System.out.print("\n40-49 | ");
		for (int i = 0; i < star5; i++)
			System.out.print("*");
		
		System.out.print("\n50-59 | ");
		for (int i = 0; i < star6; i++)
			System.out.print("*");
		
		System.out.print("\n60-69 | ");
		for (int i = 0; i < star7; i++)
			System.out.print("*");	
		
		System.out.print("\n70-79 | ");
		for (int i = 0; i < star8; i++)
			System.out.print("*");
		
		System.out.print("\n80-89 | ");
		for (int i = 0; i < star9; i++)
			System.out.print("*");
		
		System.out.print("\n90-99 | ");
		for (int i = 0; i < star0; i++)
			System.out.print("*");
Would you output your data this way if you had 100 histogram entities to print?

Code:
	// attempt at a better answer

		int[] tList = new int[100];		
		int[] tStar = new int[tList.length]; 
		//Create an array of 100 random numbers
		for (int i = 0; i < 100; i++)
		{
			tList[i] = new Random().nextInt(99);
		}
		
		for (int i = 0; i < 100; i++)
			for (int j = 0; j < 100; j++)
			{ 
				if ((tList[i] >= 00)&&(tList[i] < 9)) tStar[j]++;
				else if ((tList[i] >= 10)&&(tList[i] < 19)) tStar[j]++;
				else tStar[j]++;
			}
	}	

}
I'm not really sure what you're trying to do with two nested loops at the end of your attempt to improve the code.

Last edited by Breich; 04-08-2013 at 08:17 AM.
aisflat439's Homework thread Quote
04-14-2013 , 06:57 PM
Quote:
Originally Posted by Breich

Would you output your data this way if you had 100 histogram entities to print?
Nope not now days later. The thing that burns me up is that I'll look back on an assignment and I'll see it totally differnt. Sigh..

This week I have to build a poker hand dealer. By far the hardest assignment I've had to do so far. By a mile... I'll be posting code as I work things out. All I have right now is a shuffler really
aisflat439's Homework thread Quote
04-15-2013 , 04:23 PM
So I have to build a program that deals a hand of poker this week for school. Fortunately, a lot of this code already exists from previously completed exercises making this task a bit easier. Building this with Objects is really a difficult design problem for me so far. I think I may be way off with my design because adding players is super challenging. That or I just haven't thought it through clearly yet (pretty likely).

My classes are Deck, Card, and Player.

Decks are made up of an array of 52 Card types, and have a suffle method and a dealCard method

Code:
#include "Card.h"

class Deck
{
    private:
        Card _cards[52];
        int _nextCard;
    public:
        Deck();
        Card dealCard();
        void shuffle();
};
Card looks like this
Code:
#include <string>
using namespace std;

class Card
{
    static const string CARD_RANK[];
    static const string CARD_SUIT[];
    
    private:
        int _card;   
    public:
        Card();
        Card(int);
        int getCardValue();
        string getSuit() const;
        string getRank() const;
};
This is runs fine so far. I can make an Array of 52 cards in main and print out whichever ones I want. I'm having trouble with my Player class.

My plan is to have a player get assigned 2 int values for their cards then I can instantiate each player with their random cards. I can do the same for flop, turn and river, as well as burn cards. (I don't need to account for the button moving yet). Does this plan make sense? Because my code when I'm trying to make players sure doesn't.

Maybe it would be best to have Player inherit from Card so that player can have a getHand() method? It doesn't really make sense for a player to have a getHand() method. Maybe I should have a Hand class that gets two cards but then how to I have it get the correct cards from the deck? I'm pretty confused...

Last edited by aisflat439; 04-15-2013 at 04:29 PM.
aisflat439's Homework thread Quote
04-15-2013 , 06:33 PM
Quote:
Originally Posted by aisflat439
My plan is to have a player get assigned 2 int values for their cards then I can instantiate each player with their random cards.
I'm not sure what you mean by this. But you should use your Deck::dealCard() method to deal the cards to the players and to the flop/turn/river.
Quote:
Maybe it would be best to have Player inherit from Card so that player can have a getHand() method? It doesn't really make sense for a player to have a getHand() method.
Player should not inherit from Card, because a Player is not a type of Card. However, I think it makes perfect sense for a Player to have a getHand() method, and a Hand class that contains two cards would work just fine. But I think an even simpler approach would look something like this:
Code:
class Player
{
    string _name;    
    Card _holeCards[2];
    
    void setHoleCard(int cardIndex, Card card) // cardIndex is 0 or 1
    {
        _holeCards[cardIndex] = card;
    }

    Card getHoleCard(int cardIndex)
    {
        return _holeCards[cardIndex];
    }
  
    ...etc...
};
Then you can have a Table class which can contain a number of Player instances. Then create a Table::dealHand() method.
aisflat439's Homework thread Quote
04-16-2013 , 11:54 AM
Quote:
Originally Posted by sards

Player should not inherit from Card, because a Player is not a type of Card. However, I think it makes perfect sense for a Player to have a getHand() method, and a Hand class that contains two cards would work just fine.
This sentence was super helpful thanks! I needed to think from the whole "is-a" perspective. The path is signifigantly clearer now.
aisflat439's Homework thread Quote

      
m