• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

The rules encourage really bad coding if you're using Java. :p And some of the challenges rely more on correctly interpreting the requirements (which can be a bit ambiguous or underspecified) than coding skills...

Hm, interesting. I don't write Java though. Any reason why it encourages bad coding for Java in particular?


Finished up a Mandelbrot set coding assignment today. Fairly easy assignment, but it reminded me why I went into coding in the first place. I still love that great feeling of satisfaction when you finally get a program doing what you want.
 

iapetus

Scary Euro Man
Is this just a dig at Java or can you elaborate?

Single file submission means you can't organise classes properly. Not a dig at Java - I'm a top 15% Java coder. ;)

I'm not too sure about the difficulty structure so far either - the easiest problem so far was one of the 'challenging' ones with a job offer associated with it...
 

iapetus

Scary Euro Man
Oh my...why would they do that?

1. Their online editor only handles a single file.
2. It's easier to test.
3. It's easier to review the code online, and the database structure for the site is simpler.
4. The first languages they implemented were probably fine with using a single file.
5. There's probably an assumption that most challenges are contained enough that you don't need a complex multi-class system to solve them. This assumption is wrong, if you're trying to write elegant solutions. :p

I've written a couple of nicely OO solutions, but with those constraints I find myself more pushed towards everything-is-static-methods C-programming-in-Java style code.
 

hateradio

The Most Dangerous Yes Man
Hey guys and gals. I apologize for not reading through this entire thread, but here's my situation:

-I work in Sales Operations and therefore most of my job focuses on Salesforce admin duties
-I've had the job for a year and half, so I know my way around Salesforce
-I don't know APEX code (Salesforce's coding language), nor any type of coding language
-We keep running into issues or suggestions that require APEX/Visualforce
-Instead of continually asking around for code, I want to finally learn APEX myself

I was pointed towards this site: www.sfdc99.com

The site provides easy instructions for APEX newbs, but the creator, David Liu, emphasizes that APEX is based on Java, so learning Java is advised.

David recommends this book, which supposedly teaches Java in a colorful, visual way.
Head First is a decent book for beginners. I have never heard of APEX, but after looking at it, it just looks like Java.
 
1. Their online editor only handles a single file.
2. It's easier to test.
3. It's easier to review the code online, and the database structure for the site is simpler.
4. The first languages they implemented were probably fine with using a single file.
5. There's probably an assumption that most challenges are contained enough that you don't need a complex multi-class system to solve them. This assumption is wrong, if you're trying to write elegant solutions. :p

I've written a couple of nicely OO solutions, but with those constraints I find myself more pushed towards everything-is-static-methods C-programming-in-Java style code.

Yeah, all valid points though the assumption you suggest is maybe a little naive of them. Still, it seems like a fairly large oversight for anybody who has used Java for anything slightly complex.
 

Osiris

I permanently banned my 6 year old daughter from using the PS4 for mistakenly sending grief reports as it's too hard to watch or talk to her
There was another coding challenge site I used to use but damned if I can remember the name of it, let's see if anyone here can help me.

The challenges we're (or at least started) with sockets related challenges, and worked in a chain, i.e. the first challenge, once successfully ran led you to the next challenge, and so it continued, with the successful output of each challenge connecting you to the next.

Basically a coders scavenger hunt.

Anyone?
 

maeh2k

Member
My initial take is that I wouldn't change the code until I knew more.
The interface of the function is awkward for most uses, but might be right for some very specific uses where you already have the temporary memory reserved. For more general use, there should be a convenience wrapper that handles memory.
Presumably some kind of optimization and fine control is required since one wouldn't write their own sort implementation otherwise. Upon learning what the actual requirements and data are, it's probably time to hit Knuth and others for good specialized implementations. I sure don't have advanced mergesorts memorized. Some usual improvements would include switching to insertion sort at a low enough N, and using concurrency. I'm a bit wary of the way the existing code fetches the original values at the bottom of the recursion, but am not sure if it's an actual problem. Moving the copy outside the recursion would at least save one recursion argument and clean up memory accesses a bit, but as with most optimizations, profiling would be necessary to see whether it actually matters and how much.

Agreed. I wouldn't change the algorithm at all. But I would try (and have tried) to refactor the code to make it cleaner and more readable.

The algorithm might even contain an error. k is set to (p+q)/2, which for an array with two elements might translate to (0+1)/2 = 0; So k wouldn't be the start of the second half of the array. I haven't tested it and haven't given it a ton of thought, but these kinds of errors are hard to see in the code.
 

maeh2k

Member
I've recently finished my CS degree, but I don't have a lot of actual programming experience. So before I go out looking for a job, I decided to first work a bit on my programming skills. I'm currently doing an internship for a couple of months and I've been reading a couple of programming books.
Currently I'm reading Clean Code, which is all about writing simple and understandable programs. It's a pretty good book, but it doesn't replace actual practice.

While looking at possible jobs I came across a company that has a little programming challenge for their applicants (cf challenge in German). There's this small, compact, and hard to read function, and the task is, to understand the function and to improve upon it.

Code:
void m(int[] a, int[] b, int[] c, int p, int q) {
    if (p + 1 < q) {
       m(a, c, b, p, (p + q) / 2);
       m(a, c, b, (p + q) / 2, q);
       for (int i = p, j = p, k = (p + q) / 2; i < q; i++) {
           b[i] = (k >= q || j < (p + q) / 2 && c[j] <= c[k]) ? 
                   c[j++] : c[k++];
       }
    } else {
        b[p] = a[p];
    }
}

What does the function do? SPOILER ALERT:
It's merge sort, if you don't feel like deciphering it yourself

How can you improve on it?

So I tried to implement a cleaner version of the algorithm. I haven't spent a ton of time on the implementation; haven't tested or even compiled anything; and I didn't introduce exception handling and stuff.

To encourage a bit of discussion of the cleanest way to implement the algorithm, I've written three versions:

Version 1: basic merge sort class
- wrapped algorithm with class that handles the additonal arrays
- turned the function into a method object to limit the passing of parameters
- constructor (of internal class) is still messy
- fields of internal class go unused for one-item array
- temporal dependency of private method calls

Version 2: split off multi-element case into another class
- added class for SplitArray that can split the array, sort both halves, and merge them
- more cohesion in classes (fields always used)
- a bit confusing to seperate algorithm into two classes
- still temporary dependency (merge only after sorting of halves)

Version 3: encapsulated sub-arrays into additional class
- class SubArray that bundles the indexes (p,q) with the arrays
- less indexes, less parameters
- merge sort algorithm limited to one class
- less temporary dependency between private method calls, since merging required parameters from recursion


Any opinions, suggestions or alternative solutions?
 

Osiris

I permanently banned my 6 year old daughter from using the PS4 for mistakenly sending grief reports as it's too hard to watch or talk to her
I think you'd be better off buying a $30 book, that you can use to reference whenever you want and find things easier than spending $40 on a 4 hour video.

For the level of Java he needs to learn I'd say even a $30 book is unnecessary for now, John Purcell's Java for Complete Beginners is free on Udemy and will get him up and running with Java and a basic understanding of coding.
 

Water

Member
Agreed. I wouldn't change the algorithm at all. But I would try (and have tried) to refactor the code to make it cleaner and more readable.

The algorithm might even contain an error. k is set to (p+q)/2, which for an array with two elements might translate to (0+1)/2 = 0; So k wouldn't be the start of the second half of the array. I haven't tested it and haven't given it a ton of thought, but these kinds of errors are hard to see in the code.
It's not an error. Look at the arguments to the two recursive calls in the original code; both take the same index. Therefore the range arguments to the function are inclusive-exclusive (which you should expect anyway; Dijkstra gives a rationale for it in this classic paper).

I looked at the first and last versions of your code, and I don't see an improvement upon the original, rather the opposite. You are obscuring a simple function by torturously splitting it into a bunch of snippets. The original implementation is pretty easy to read to begin with, and fixing the names, cleaning up the interface and adding a comment or two would make it more so. There's no reason to write any of those classes. You're burning far more memory, making memory access less regular and wasting performance compared to the original.
 

maeh2k

Member
I looked at the first and last versions of your code, and I don't see an improvement upon the original, rather the opposite. You are obscuring a simple function by torturously splitting it into a bunch of snippets. The original implementation is pretty easy to read to begin with, and fixing the names, cleaning up the interface and adding a comment or two would make it more so. There's no reason to write any of those classes. You're burning far more memory, making memory access less regular and wasting performance compared to the original.

I don't know. In books about refactoring they often tend to turn functions into lots of very small functions that by themselves are very easy to understand. In the book Clean Code that I've just finished the author surely would have criticized the original function for its readability. Especially the for loop is really hard to read.
If you jump into the sort function of my first version, it seems pretty readable:
Code:
public void Sort()
        {
                if(OnlyOneElement())
                        SortOneElementList();
                else
                {                      
                        SplitArrayInTheMiddle();
                        RecursivelySortLeftAndRightHalfIntoTmpArray()
                        MergeBothParts();
                }
        }
 

Osiris

I permanently banned my 6 year old daughter from using the PS4 for mistakenly sending grief reports as it's too hard to watch or talk to her
I don't know. In books about refactoring they often tend to turn functions into lots of very small functions that by themselves are very easy to understand. In the book Clean Code that I've just finished the author surely would have criticized the original function for its readability. Especially the for loop is really hard to read.
If you jump into the sort function of my first version, it seems pretty readable:

Refactoring for readability has to be balanced against optimization for execution speed, function calls are expensive, and with something like a sort I would think that execution speed is a higher priority.
 
Refactoring for readability has to be balanced against optimization for execution speed, function calls are expensive, and with something like a sort I would think that execution speed is a higher priority.

It definitely depends on the use case, but I would usually say readability > execution speed in most cases. Since making your code more readable often doesn't have a large impact on execution times. If your program is having speed issues, then you can sacrifice readability.

But yeah, I guess that depends on what you're refactoring for.
 

iapetus

Scary Euro Man
My first question on seeing the code was: "What do you mean by improve?"

Different people will have different answers to that; maybe it needs to be more reusable, maybe it needs to be more performant. The only guarantee is that it needs more helpful variable names.
 

Slavik81

Member
Refactoring for readability has to be balanced against optimization for execution speed, function calls are expensive, and with something like a sort I would think that execution speed is a higher priority.

That looks sorta like Java or C# so I'm not sure how those languages handle function calls. I'm used to C and C++, where functions calls are cheap like borsch. And, on top of that, if the definition is available any half-decent compiler will inline small functions.

I kinda agree that the refactoring breaks things down a little too much for my taste. My bigger complaint is about the use of class member variables to pass data between internal functions. It's hard to follow what methods depend on what data because it's all implicit. The storage of a temporary buffer at class scope is particularly egregious.
 

Osiris

I permanently banned my 6 year old daughter from using the PS4 for mistakenly sending grief reports as it's too hard to watch or talk to her
That looks sorta like Java or C# so I'm not sure how those languages handle function calls. I'm used to C and C++, where functions calls would are cheap like borsch. And, on top of that, if the definition is available any half-decent compiler will inline small functions.

I kinda agree that the factoring was breaks things down a little too much for my taste. My bigger complaint is about the use of class member variables to pass data between internal functions. It's hard to follow what methods depend on what data because it's all implicit. The storage of a temporary buffer at class scope is particularly egregious.

C# calls are fairly expensive, however although not a traditional compiler, you are right, the JIT will inline small functions under certain circumstances, however one of the exceptions (excuse the pun) to JIT inlining is any exception handling blocks, which means in the case of the code above it's not that big a deal, but as far as good practice goes in C# I'd say less is more.

There is also the fact that before .NET 4.5, the JIT was very conservative over what it would inline, and even versions after are still quite conservative compared to C/C++ compilers, although the MethodImplOptions.AggressiveInlining enum helps loosen this conservative nature a little.
 
I have a question regarding degrees. I can graduate with a BA in CS this semester and I kinda want to since I rather not spend more money(and that I really want to get out of my school). I heard a BS may be better, but it would require me to take an additional 2 CS classes and a physics course. I'm trying to get an internship this semester and I heard that's what's really matter.
 
I have a question regarding degrees. I can graduate with a BA in CS this semester and I kinda want to since I rather not spend more money(and that I really want to get out of my school). I heard a BS may be better, but it would require me to take an additional 2 CS classes and a physics course. I'm trying to get an internship this semester and I heard that's what's really matter.

I guess it really depends upon what you want to do post college.

My general experience is that the ability to demonstrate your skills and knowledge is more important than what piece of paper you got.
 

usea

Member
I have a question regarding degrees. I can graduate with a BA in CS this semester and I kinda want to since I rather not spend more money(and that I really want to get out of my school). I heard a BS may be better, but it would require me to take an additional 2 CS classes and a physics course. I'm trying to get an internship this semester and I heard that's what's really matter.
That is kind of a dilemma eh? What are the CS classes? What would you be doing with your time if you're not in school next semester?

If the choice is between a well-paying job and an extra semester for BS, that's a different tradeoff than if you'd be spending your time looking for a job. Also if the CS classes are useful for interesting, that's another thing to consider. There are a lot of classes I wish I had gotten to take before I left school.
 

Chris R

Member
Ok, I have VS ultimate 2013 installed, but I have no idea how to start an HTML or CSS project within the program. Do you have any idea how to do this?

You will want to start a ASP.Net project (well, you don't need to, but it wires up IIS for you, makes testing easier I feel).

You don't NEED to use .aspx files, you can add a basic .html file to the project after it has been created and set that as your default file to load when you start to debug/test your pages.
 
That is kind of a dilemma eh? What are the CS classes? What would you be doing with your time if you're not in school next semester?

If the choice is between a well-paying job and an extra semester for BS, that's a different tradeoff than if you'd be spending your time looking for a job. Also if the CS classes are useful for interesting, that's another thing to consider. There are a lot of classes I wish I had gotten to take before I left school.
1)The two classes I would consider taking would be:

Operating Systems Design-which would also count as graduate credit but I have no intention of getting a masters really. I would have taken this instead of linear programming since I have the prerequisites to take it but I heard it's one of the toughest course you can take as an undergraduate. My friend advise not to take it, who's working for a good company atm so trying to follow his footsteps but he has a BS, with all the other courses I'm taking.

Internet Technology-I heard they create their own torrent client in this class which I think would be really neat to create.

2) Prepping for the JLPT and continue coding while looking for a full time job as a part timer.

But yeah, I definitely see where you're getting at. It's definitely something I should think over some more. Some interns/jobs seem like they don't care while some do like the big bank companies such as JP Morgan.

I guess it really depends upon what you want to do post college.

My general experience is that the ability to demonstrate your skills and knowledge is more important than what piece of paper you got.
And that, I have no idea.
 

BreakyBoy

o_O @_@ O_o
So, I just bombed a job interview. I'm ok about it since I had a million reasons not to want to take the job if offered*. Not to mention, after talking with the guy that I would have replaced, I got the impression that I probably wasn't the best fit for the job. I mean, I hate 'losing', and that is what this feels like, but overall I'm content that I was able to get through the first two screenings with my resume/writing.

I am pissed that I completely blanked on the technical questions side of the interview though. Especially considering that they were simple questions (#1 was FizzBuzz!), and of course, I thought of better ways to answer every single one as soon as I calmed down.

So, my takeaway is that I need to get better at interviewing. I'm happy where I am, but one never knows what might happen. The obvious way to practice is to routinely apply for jobs so that I can get interviewed. The problem is, how do I do this, without risking having prospective employers call my current employer to confirm things on my resume?

Have any of you done this? If so, how do you handle that potential problem with your current employer getting wind of the fact that you're testing the market?

* I would need to move cross-country ASAP; I'm in the middle of getting a mortgage for a condo for my parents; I suspected that I wouldn't get compensated as well as I currently am; etc
 

usea

Member
So, my takeaway is that I need to get better at interviewing. I'm happy where I am, but one never knows what might happen. The obvious way to practice is to routinely apply for jobs so that I can get interviewed. The problem is, how do I do this, without risking having prospective employers call my current employer to confirm things on my resume?

Have any of you done this? If so, how do you handle that potential problem with your current employer getting wind of the fact that you're testing the market?
If you talk to a recruiter or HR, mention that you're currently employed. Or make sure your resume says something like "March 2011 - Present". It's extremely rare that they would call your current employer and tip them off that way. Like, they'd be really bad at their job if they did that. I've heard this from multiple recruiters and HR people. It's a common question I've heard at job talks.

And yep, practice makes perfect. This goes for interviews as well.
 

iapetus

Scary Euro Man
My general experience is that the ability to demonstrate your skills and knowledge is more important than what piece of paper you got.

To a point. Initially, at least, that piece of paper gets you through the door so that you can demonstrate your skills and knowledge...
 

Water

Member
I don't know. In books about refactoring they often tend to turn functions into lots of very small functions that by themselves are very easy to understand. In the book Clean Code that I've just finished the author surely would have criticized the original function for its readability. Especially the for loop is really hard to read.
If you jump into the sort function of my first version, it seems pretty readable:
Code:
public void Sort()
        {
                if(OnlyOneElement())
                        SortOneElementList();
                else
                {                      
                        SplitArrayInTheMiddle();
                        RecursivelySortLeftAndRightHalfIntoTmpArray()
                        MergeBothParts();
                }
        }
This code tells me exactly nothing. Every mergesort splits, recursively sorts and merges. If I'm looking inside your mergesort implementation at all, it's because I want to know how it's doing things. You also haven't reduced the complexity of the code or raised the abstraction level with this, because all of these methods are messing with some hidden shared state, and aren't decoupled at all. So now I have to jump around the code to hunt for the detail that is swept under the rug; much harder to read. There's no reason for a mergesort algorithm to be a class with state. It's a function.
 
What is happening here?

Code:
C#

char test = '4';
int tryNum = Convert.ToInt32(test);
Console.WriteLine(tryNum);

OUTPUT: 52

I'm confused. If test is a string instead of a character, then it would convert test to 4, but if it's a char then it converts it to 52?

This works great:

Code:
char test = '4';
string test2 = Convert.ToString(test);
int tryNum = Convert.ToInt32(test2);
Console.WriteLine(tryNum);

But why?
 

nan0

Member
What is happening here?


I'm confused. If test is a string instead of a character, then it would convert test to 4, but if it's a char then it converts it to 52?

This works great:

But why?

Because ToInt32() converts the char into its actual decimal ASCII value. 52 is the ASCII value of the char "4". Use Char.GetNumericValue() to get the actual numeric value the char has (if you don't want to go through the string conversion)
 
1)The two classes I would consider taking would be:

Operating Systems Design-which would also count as graduate credit but I have no intention of getting a masters really. I would have taken this instead of linear programming since I have the prerequisites to take it but I heard it's one of the toughest course you can take as an undergraduate. My friend advise not to take it, who's working for a good company atm so trying to follow his footsteps but he has a BS, with all the other courses I'm taking.

Internet Technology-I heard they create their own torrent client in this class which I think would be really neat to create.

2) Prepping for the JLPT and continue coding while looking for a full time job as a part timer.

But yeah, I definitely see where you're getting at. It's definitely something I should think over some more. Some interns/jobs seem like they don't care while some do like the big bank companies such as JP Morgan.


And that, I have no idea.

Let me just say from experience that Operating Systems is the kind of class that either makes a man out of you, or completely breaks your will. My professor considered it the hardest class of any undergrad class at the university and he wasn't one of those hard ass professors either.

That being said, as someone who has worked off and on in the games industry, operating systems was probably one of the most valuable classes I took, both in terms of knowledge gained and just prepping me to handle horrible hours and work loads.

To a point. Initially, at least, that piece of paper gets you through the door so that you can demonstrate your skills and knowledge...

Well sure. I've mentioned this in another thread about going to school and I know that I've had interview opportunities presented to me that people I've worked with similar experience/skill sets didn't get because my degree came from a more prestigious school. I did not get hired anywhere solely based on my degree however.
 
Let me just say from experience that Operating Systems is the kind of class that either makes a man out of you, or completely breaks your will. My professor considered it the hardest class of any undergrad class at the university and he wasn't one of those hard ass professors either.

That being said, as someone who has worked off and on in the games industry, operating systems was probably one of the most valuable classes I took, both in terms of knowledge gained and just prepping me to handle horrible hours and work loads.
Yeah, thus why my friend advise me not to take it if I was taking other a schedule filled with CS courses. He didn't even take it, took something with graphics which is what I wanted to take but it seems they dropped that course a while ago. What I could do is take the other physics I need and Internet and Tech in the summer and then take that one other CS elective class I need for a BS. It would either be the OS design class or software engineering in the fall. I want to discuss it with a dean first. Money is an issue. I definitely have to weigh the options out.

Thanks for the input guys.
 

Nelo Ice

Banned
So after briefly trying to teach myself programming on Codeademy and Coursera, I found that I actually enjoyed it but didn't go through with the coursera courses since I got behind since I didn't realize it started until a week into it so I got behind and only finished about 2 weeks worth. With that said I found what little I did learn to be incredibly interesting and realized programming may be my calling.

Anyway I decided I'd head back to school and I'm currently enrolled in a C++ class at my local CC. With that said I'm now questioning if I even need to be at school. Been going to the CC for way too long and took 2 semesters off trying to figure out what the hell I wanted to do for a career. Based on all the things I've read here on GAF I should be teaching myself but main reason I went back is I figured I'd a degree to even have a chance at getting a job. Along with making those all important connections and getting an internship.

Going to speak with a counselor asap so I can figure out what I need to do transfer but my GEs have been done for awhile now. I'm currently just paranoid I'll have to do work my way up with prereqs all over again for a few more years to get the classes I need to transfer with a CS degree. Right now I'm unsure if it will all be worth it since again I'm not sure if I even need it and if I do that means even more years at my CC or transferring. I've already wasted plenty of time trying to figure out my career after realizing my previous major of nursing was not for me.
 
^ School is great. Like you said, you get a degree, but not only that you're also forced to do all the exercises and forced to learn how to explain all the terms and stuff. It's also really motivational. My C# course was really intense; 8-10 hours of studying almost every day, but it was fun because we were working together and I felt that I learned a lot in just a month. Codeacademy is amazing too, I'm using that right now to learn more.
 
It's definitely possible to learn how to program without going to school. However, being a good developer requires more than just pure programming skills, and I think a lot of that can sometimes be difficult to learn on your own. Maybe it doesn't matter so much when you're working on projects alone at home, but when you're in a team with 20 other people, things get a little more tricky.
 

Water

Member
It's definitely possible to learn how to program without going to school. However, being a good developer requires more than just pure programming skills, and I think a lot of that can sometimes be difficult to learn on your own. Maybe it doesn't matter so much when you're working on projects alone at home, but when you're in a team with 20 other people, things get a little more tricky.
If you only learn alone, you probably won't be a solid, productive solo programmer either. The value of many practices and techniques in programming is not obvious before you are exposed to them, and they take a lot of work and time to learn, so without someone to push you it's unlikely you'll struggle through the initial pain of adopting them. The risk is that you end up just skimming the surface. Don't become the stereotypical "web developer" who knows and kind-of uses ten different languages and messes with databases at a full-time job, but fundamentally sucks at programming in ways that even an introductory computer science course would correct.

Not saying you have to go to school, but either you need to somehow interact with others, or you need the kind of ironclad motivation that 95% of people do not have.
 

haikira

Member
If someone could point a beginner in the right direction, it would be very appreciated.

I have a class called SystemFile, which just takes in a string, which will be a file path and sets a bunch of properties based off that string. I'm wanting to now make an array of objects using that class, passing the filepaths gathered in the first line of code.

I have a feeling I'm going about this completely wrong.

// Array of filepath strings.
string[] files = Directory.GetFiles(this.OldFileDirectory.Text);

// Array of file objects.
SystemFile[] fileBatch = new SystemFile[files.Length];

// Fill fileBatch array with objects, using the file path strings.
 
If someone could point a beginner in the right direction, it would be very appreciated.

I have a class called SystemFile, which just takes in a string, which will be a file path and sets a bunch of properties based off that string. I'm wanting to now make an array of objects using that class, passing the filepaths gathered in the first line of code.

I have a feeling I'm going about this completely wrong.

You can use a loop to go through your fileBatch[] array, then set each of their filepath attribute. You need to create a setter function though.
Code:
fileBatch[i].setFilePath(files[i]);

However, I wouldn't recommend your approach. You're creating an empty array then filling in the blanks. The problem is that the size of the array is can change, since it depends on how many filepaths you retrieved. I believe array sizes are fixed in Java, which I think is what you're using. I would instead use List, which is dynamic in size.
Code:
List<SystemFile> fileBatch = new ArrayList<SystemFile>();

Use a for loop to iterate through your files[] array. Create a single SystemFile "sysFile", then add it to your fileBatch[]:
Code:
fileBatch.add(sysFile);

This way is simpler, since you just keep adding new SystemFile objects without worrying how many you have.

I haven't used Java in ages so I'm not sure of the syntax, but the idea is there.
 

Jackben

bitch I'm taking calls.
Would anyone mind giving me a nudge in the right direction here? I'm a bit lost on where to go for this assignment.

Your program should accomplish the following:

Use an ENUM :

enum Shape
{
Circle,
Square
};

Continue prompting the user for a shape type (0 or 1) until they type anything different,
and then display the “total area output”.

While the user continues to enter the correct shape type, prompt them for either the
length of the side of a square, or the radius of the circle.

Calculate and sum up the “total area” of the circle and square areas.

When the user has indicated they want to quit, display the total area.

IUjBqy4.jpg


NyNWFq1.jpg

Here is what I have so far.

The do while loop doesn't resolve to anything but prompting to be re-entered. Kinda confused and feel like I'm missing/ignoring something to do with enumeration. The way I am proceeding I would assign square or circle shape type by an int value of 0 or 1. Which is doesn't really make use of the enum type at all.
 
First of all, you should move your two if-cases into the do-while loop. Do you understand how do-while loops work?

There are a lot of other issues with the code, but that is why it is just prompting for re-enter.
 

Jackben

bitch I'm taking calls.
First of all, you should move your two if-cases into the do-while loop. Do you understand how do-while loops work?
Ugh that is definitely something I should have known. I took an intro course in C++ last summer (first programming language as well) and this is the first time I've come back to it with an Object-Oriented programming class this spring in C++. So I'm feeling pretty rusty. IIRC do while continues to execute until the argument is no longer true, at which point it exits the program. I'm not sure how complicated you can get within the do-while loop though. I'll start by pasting the two if's into the loop.
There are a lot of other issues with the code
I figured as much. I'm not very good right now but I do appreciate the help.
 
IIRC do while continues to execute until the argument is no longer true, at which point it exits the program. I'm not sure how complicated you can get within the do-while loop though. I'll start by pasting the two if's into the loop.

Not quite. As you said, the code inside the loop-body will be executed for each iteration until the condition is not true anymore (in this case, when userShape > 1). After that it will just continue executing the code that comes after the do-while loop, which in this case are the two if-cases. However, since userShape now is > 1, the code inside the if-cases won't execute and the program will just exit.

You can put as complicated code as you like inside the while-loop.
 

Jackben

bitch I'm taking calls.
Edited Program Here.

Two things to note: Compiles and runs correctly according to specifications, however I didn't do anything with the enumeration data type which needs to be addressed since that was a specification of the assignment. But I'm not sure how this should be implemented...Also another thing that I can't figure out is why user input for the length and radius doesn't accept the first input by a user, you have to enter a value and press enter twice for some reason.
 
Would anyone mind giving me a nudge in the right direction here? I'm a bit lost on where to go for this assignment.



Here is what I have so far.

The do while loop doesn't resolve to anything but prompting to be re-entered. Kinda confused and feel like I'm missing/ignoring something to do with enumeration. The way I am proceeding I would assign square or circle shape type by an int value of 0 or 1. Which is doesn't really make use of the enum type at all.

That is because this is not a very good use of enums, IMHO. At least not one I like. But it's totally workable.

You are comparing the input to hard-coded numbers (0 or 1). Remember that each enum element is assigned by default a number starting from 0,
so you should compare your input to that value of the enum. Since ints and enums are not compatible in C++ AFAIK, you will have to cast.

Then your <if> would be like this:

if (static_cast<Shape>( usershape ) == Shape.Circle)
{
//do circle stuff
}
else if (static_cast<Shape>( usershape ) == Shape.Square)
{
//do square stuff
}

That way you are now using the enum! lol

I personally only use enums for internal references and rarely compare them to user input or database values, but that is just my philosophy.

I am casting twice just to show, but you can optimize that of course.


Edit: You could probably add another <else> with a break in case the input doesn't equal either Shape and exit from there, instead of checking if the input is <= 1, since that is a hard-coded value.
 
Top Bottom