• 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

hateradio

The Most Dangerous Yes Man
I use the JetBrains IDEs with the Darcula themes since I'm too lazy to change it. When I use Sublime Text I use Monokai.

Notepad++ I use Son of Obsidian.

And for everything I use PT Mono because it's the sexiest font ever.



iQCbfLrjD5H60.gif
 
I have to use PHP for a group project. Any place where I can learn the basics and get going pretty fast? Anything specific I need to know about it?

1. Stuff outside PHP tags are just echo'd as plain text.
2. Turn on all the strict settings and hit people that try to use it like Perl instead of nice readable C/C++.

How do you have your IDE set up with the colours and stuff? For a course I'm taking, we have to code via Linux (Ubuntu), so I have terminal set up as follows (white default text btw)

vim using desert/dark theme, 14pt Inconsolata-Dz font, 83% opaque black terminal.

I have a question regarding database design.

Have always used paths or simply filenames with the path determined by other parts of the record. e.g. "/base/mp3/path/artist/album/track.mp3" coming from the artist/album/track/filetype fields.
 
I'm kind of all over the place when it comes to IDEs/editors. I generally try to use an IDE if there's one available. For Java, it's IntelliJ, for C++ Visual Studio (on Linux I use QtCreator), C#/F# also Visual Studio (with ReSharper). As for fonts, I use Consolas or Source Code Pro, both are nice. I've started using vim because it's the only editor available on the build server at work but so far I've only been using it for editing simple configuration files and looking at logs and stuff. (press i, edit stuff, ctrl-c, :wq) I used Emcas when I was programming in Clojure for a while and it's pretty nice too. I just find using Sublime Text is faster for me because the keyboard shortcuts adhere to modern standards (Ctrl-O to open file, Ctrl-N for new file and so on)
 

PFD

Member
Github now has a free student pack with all sorts of cool things. You just need a Github account and an accepted student email. Among other things, you get a free subscription for Unreal Engine 4, 100$ in credit for DigitalOcean (hosting service), private Travis CI builds and a Github Micro account.

https://education.github.com/pack

Wow, thanks for mentioning this. I got a free 2 year micro GitHub membership with a student pack chock-full of stuff incl. Unreal Engine. They only asked for my student email, and I was accepted pretty much instantaneously.
 

Mine01

Member
Hi guys, I'm 21 years old currently working as a teacher and studying a programming carrer. (currently at 6/7 sem of a 10 sem carrer).

Ok, next week I'm starting a new job as a developer in a small software company. But I have a couple of questions.

How different is pogramming at school than programming out there?.
I've done a couple of big projects. (webpages with databases, and well, mostly webpages, visual studio applications and stuff like that.)

I'm pretty good at it, i think.

Im good at c++, c#, html, javascript, php, css... not that good with java.

Anyway Im kinda scared because as I said, all of my developing experience comes from school... where most software is pretty simple, yet my new boss told me I shouldn't be scared.. but I am lol.

I get that most experience comes from working, but stil, any new programmer who can tell me what I learned at school gonna be enough to start working?
 

Kalnos

Banned
^What you learned through university will be enough to get you started and your employer understands that. You will continue (and always) learn new things at work. They will have tons of conventions, libraries, legacy code, etc to learn. Sometimes you may have a day where you want to bash your head against a wall because you're stuck, that's normal IMO.

One of the biggest differences from school work is that you will have to learn to read other peoples code instead of starting every assignment from scratch. There are seriously too many differences to list.

Just avoid slacking off on GAF/Reddit too much. :p
 

Mine01

Member
^What you learned through university will be enough to get you started and your employer understands that. You will continue (and always) learn new things at work. They will have tons of conventions, libraries, legacy code, etc to learn. Sometimes you may have a day where you want to bash your head against a wall because you're stuck, that's normal IMO.

One of the biggest differences from school work is that you will have to learn to read other peoples code instead of starting every assignment from scratch. There are seriously too many differences to list.

Just avoid slacking off on GAF/Reddit too much. :p

I hate doing that but I know i have to :(.

Most of the time at school when i work with a partner I just do all the code because I hate doing what you said lol.
 

Godslay

Banned
Hi guys, I'm 21 years old currently working as a teacher and studying a programming carrer. (currently at 6/7 sem of a 10 sem carrer).

Ok, next week I'm starting a new job as a developer in a small software company. But I have a couple of questions.

How different is pogramming at school than programming out there?.
I've done a couple of big projects. (webpages with databases, and well, mostly webpages, visual studio applications and stuff like that.)

I'm pretty good at it, i think.

Im good at c++, c#, html, javascript, php, css... not that good with java.

Anyway Im kinda scared because as I said, all of my developing experience comes from school... where most software is pretty simple, yet my new boss told me I shouldn't be scared.. but I am lol.

I get that most experience comes from working, but stil, any new programmer who can tell me what I learned at school gonna be enough to start working?

I agree with Kalnos. Also to add to the reading other people's code, it's a blessing and a curse. It's a blessing because you can learn so much from it, but you can also pick up bad habits. If you are maintaining it, it can be a pain, but you'll pick up good ways and bad ways to do things. Either way you learn.

I'll add that if it's a good place to work they'll know how to dish out just enough to keep you busy as well as keeping you challenged and learning. The most important thing isn't what you've learned in school to be honest. Some of it transfers directly, but it's just base to start with.

If you were honest with your experience and skill level and they hired you based upon that they'll know your green. Just be ready to learn, be humble, ask questions, admit your mistakes, and you'll be fine. The experience will come and you'll get better. Good luck!
 

Mine01

Member
Yea I was as honest as I could because that reason, plus the guy is friend of my uncle... when I told him I didn't know that much, he told me it's ok to ask questions, search online and stuff like that.
 

Husker86

Member
Does anyone have a simple explanation of how freelance work, mainly websites, is distributed?

In a couple months I am going to start looking for simple, low-paying projects on freelance websites just to get some experience.

I am wondering how the transfer of work is handled. Do I just give them a zip of the website source? I assume I show it to them before getting paid, and in that case can't they just see the source and copy it?

I just want to get an idea of how projects like these are normally handled from start to finish.
 
I am trying to compile my program but I keep getting this error and I am unsure how to fix it. Could someone help me out on what the error means and how to fix it?

Code:
invalid conversion from 'void (*)(int)' to 'void* (__attribute__((__cdecl__)) *)(void*)' [-fpermissive]
initializing argument 3 of 'int pthread_create(pthread_t*, pthread_attr_t_* const*, void* (__attribute__((__cdecl__)) *)(void*), void*)' [-fpermissive]|

The line referenced in the error message is this one in main():
Code:
rc = pthread_create(&threads[i], NULL, ProcessNumbers, (void *)i);
 
pthreads
I think the complaint is about how the function you want to run is passed in.
I think if you check out some examples they'll declare something to point to the function and pass that. (I'm on a phone so can't do much more)
 
I am trying to compile my program but I keep getting this error and I am unsure how to fix it. Could someone help me out on what the error means and how to fix it?

Code:
invalid conversion from 'void (*)(int)' to 'void* (__attribute__((__cdecl__)) *)(void*)' [-fpermissive]
initializing argument 3 of 'int pthread_create(pthread_t*, pthread_attr_t_* const*, void* (__attribute__((__cdecl__)) *)(void*), void*)' [-fpermissive]|

The line referenced in the error message is this one in main():
Code:
rc = pthread_create(&threads[i], NULL, ProcessNumbers, (void *)i);

Here is the code:
Code:
#include statements

#define NUMELEM 242
#define NUM_THREADS     4

using namespace std;

ifstream input(input.txt"); 

pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int counter = 1;

void ProcessNumbers( unsigned int const& thid )
{
    const unsigned numTasks = NUMELEM/NUM_THREADS, numTougherThreads = NUMELEM%NUM_THREADS;

    for( unsigned int index0 = (thid < numTougherThreads ? thid * (numTasks+1) : NUMELEM - (NUM_THREADS - thid) * numTasks), index = index0; index < index0 + numTasks + (thid < numTougherThreads) ; ++index)
    {
        string number;
        getline(input, number);
        pthread_mutex_lock( &mutex1 );
        int data;
	data = atoi(number.c_str());
        cout << "Threadid " << tid+1 << " processes the " << counter << "th number which is " <<  data << " and the Square root is " << sqrt(data) << "." << endl;
        counter++;
        pthread_mutex_unlock( &mutex1 );
}
cout << "-------------------------Threadid " << thid+1 << " finished---------------------" << endl;
}


int main()
{
   int rc;
   int i;
   pthread_t threads[NUM_THREADS];
   pthread_attr_t attr;
   void *status;

   for( i=0; i < NUM_THREADS; i++ ){
      rc = pthread_create(&threads[i], NULL, ProcessNumbers, (void *)i);
      if (rc){
         cout << "Error:unable to create thread," << rc << endl;
         exit(-1);
      }
   }

   pthread_attr_destroy(&attr);
   for( i=0; i < NUM_THREADS; i++ ){
      rc = pthread_join(threads[i], &status);
      if (rc){
         cout << "Error:unable to join," << rc << endl;
         exit(-1);
      }
   }
   pthread_exit(NULL);
}

I think you need to pass a pointer to the function in the third argument there. Also, I haven't used pthreads in a good while but I think the argument for the thread function should be a void pointer and you have to convert it back inside the function.

Edit: Actually scratch the first bit, it's the return value that has to be a pointer to void. To expand a little on the error, the pthread create function expects a function with the type signature void* function(void *) or a function that takes a void pointer and returns a void pointer. You are passing a function that takes an unsigned integer and returns void, and the compiler doesn't know how to handle it. I think :p
 

Roflobear

Member
Hey guys, I was wondering if anyone could point me in the right direction here. In about 2 weeks, I have an assignment in JavaScript due. It's not a terribly complex assignment but I've never programmed in JavaScript before. I'm pretty comfortable with Java, so I was wondering if anyone knew of a good online resource where I could learn the basics of JavaScript in about a week or so. Thanks for any help
 

leroidys

Member
Hey guys, I was wondering if anyone could point me in the right direction here. In about 2 weeks, I have an assignment in JavaScript due. It's not a terribly complex assignment but I've never programmed in JavaScript before. I'm pretty comfortable with Java, so I was wondering if anyone knew of a good online resource where I could learn the basics of JavaScript in about a week or so. Thanks for any help
Code academy
 

Slavik81

Member
Edit: Actually scratch the first bit, it's the return value that has to be a pointer to void. To expand a little on the error, the pthread create function expects a function with the type signature void* function(void *) or a function that takes a void pointer and returns a void pointer. You are passing a function that takes an unsigned integer and returns void, and the compiler doesn't know how to handle it. I think :p
This is accurate.

It expects a function with the signature:
Code:
void * (void *)
but you're giving it a function with the signature:
Code:
void (unsigned int const&)
 

Water

Member
-Teach us C++ with current examples.
-Give us a book that utilizes C++11 features (which are welcome)
-Force us to code in C++98 with no header files.
Huh. I can maybe see the point in the header file thing to make sure people understand exactly what headers are before they start using them, but then it'd only be for an exercise or two. C++98 I don't really see as worth teaching to beginners since someone who is comfortable with C++11 can trivially just not use any of the new functionality. Any idea what your teacher is up to with those limitations?
 

Rapstah

Member
I've got a question about abstract and virtual methods in C#. If I have a base class with a completely abstract method, and then want to provide a standard implementation for that method in another extending abstract class, how would you do it without "override virtual", which is apparently not allowed on an abstract method?

Here's how I would like to do it, represented as an animal example (because I like that example). All animals can say something, but by default, felines should say "meow".

Code:
abstract class animal
{
[INDENT]public abstract void talk();[/INDENT]
}

abstract class feline: animal
{
[INDENT]public override virtual void talk()
{
[INDENT]Console.WriteLine("Meow!");[/INDENT]
}[/INDENT]
}
 
I've got a question about abstract and virtual methods in C#. If I have a base class with a completely abstract method, and then want to provide a standard implementation for that method in another extending abstract class, how would you do it without "override virtual", which is apparently not allowed on an abstract method?

Here's how I would like to do it, represented as an animal example (because I like that example). All animals can say something, but by default, felines should say "meow".

So, you want to have an abstract base class, an abstract class inheriting that class that provides default behavior, but inheriting classes should be allowed to override that behavior? I think the following should do this:

Code:
abstract class Animal {
    public abstract void talk();
}

abstract class Feline: Animal {
    public override void talk() {
        Console.WriteLine("meow");
    }
}

class Cat: Feline {
    public override void talk() {
        Console.WriteLine("meow I'm a cat!");
    }
}

edit: Made the methods public.
 

Rapstah

Member
So, you want to have an abstract base class, an abstract class inheriting that class that provides default behavior, but inheriting classes should be allowed to override that behavior?

Oh, thanks, I didn't even think of just making the method just non-virtual or abstract and overriding it anyway. Thanks! It seems to work in my real program.
 
I have to use PHP for a group project. Any place where I can learn the basics and get going pretty fast? Anything specific I need to know about it?

http://laravel.com
https://laracasts.com

If you are using PHP then Laravel is the best framework going and Jeff Way explains things really well. There are some free lessons on there as well.

We recently switched from our own framework to Laravel as a base and things have gotten so much cleaner to manage.

If you are learning from scratch just try to follow a very simple blog tutorial. PHP is relatively easy however and if you use a framework and read up on standards etc and already know OOP it is hard to go wrong.
 
pthreads
I think the complaint is about how the function you want to run is passed in.
I think if you check out some examples they'll declare something to point to the function and pass that. (I'm on a phone so can't do much more)

I think you need to pass a pointer to the function in the third argument there. Also, I haven't used pthreads in a good while but I think the argument for the thread function should be a void pointer and you have to convert it back inside the function.

Edit: Actually scratch the first bit, it's the return value that has to be a pointer to void. To expand a little on the error, the pthread create function expects a function with the type signature void* function(void *) or a function that takes a void pointer and returns a void pointer. You are passing a function that takes an unsigned integer and returns void, and the compiler doesn't know how to handle it. I think :p

Thanks. I was able to fix it thanks to your help.
 
Huh. I can maybe see the point in the header file thing to make sure people understand exactly what headers are before they start using them, but then it'd only be for an exercise or two. C++98 I don't really see as worth teaching to beginners since someone who is comfortable with C++11 can trivially just not use any of the new functionality. Any idea what your teacher is up to with those limitations?
He claims it's for portability and what's "easiest." Bear in mind, this isn't an entry-level CS course, but an upper-level class. We've already had at least six classes that have taught us C++ as well.
http://laravel.com
https://laracasts.com

If you are using PHP then Laravel is the best framework going and Jeff Way explains things really well. There are some free lessons on there as well.

We recently switched from our own framework to Laravel as a base and things have gotten so much cleaner to manage.

If you are learning from scratch just try to follow a very simple blog tutorial. PHP is relatively easy however and if you use a framework and read up on standards etc and already know OOP it is hard to go wrong.
Thanks for the response!
 
I need some help. I've spent hours on this single function that I cannot get to work correctly. I'm missing something but I don't know what.

So my assignment is to make my own string class. I am allowed to use cstring functions (I'm working in C++), though. My prof gave us the driver file and the header file. I am simply implementing each function.

The function I am having issue with is this:

Code:
void String::append(const String &str)
{
	char *new_contents = new char[(len + str.len) + 1];		

	strcpy(new_contents, contents);
	strcat(new_contents, str.contents);
	

}

All I want to do is append whatever is in String str to the String that the function was called on. My issue with this is that I don't understand how the appended string is going to get back to main. I feel like there should be one more line of code that completes this, but I'm not sure what else to do.

Here is what is happening in main:
Code:
cout << "\nEnter a value to append to str1 (no spaces): ";
cin >> s1;
str1.append(s1); // trying to append s1 to str1


Here's the output I'm getting (notice how the new strings aren't appending to the originals):

Code:
Enter a value to append to str1 (no spaces): why

Enter a value to append to str2 (no spaces): not

Enter a value to append to str3 (no spaces): working

After appending...
str1 holds "hey" (length = 3) // these are the original names (they aren't being appended)
str2 holds "neo" (length = 3)
str3 holds "gaf" (length = 3)

Any ideas? I have a good feeling I'm tunnel visioning at this point and missing something very obvious. Please, if you have a suggestion, I'd really appreciate it. I can post more code as well if needed. Thanks in advance.
 

Slavik81

Member
Two more lines of code, actually. In append you need to point your contents to new_contents and release the memory used by the old contents.
 
Two more lines of code, actually. In append you need to point your contents to new_contents and release the memory used by the old contents.

Thanks. So it should look something like this?

Code:
void String::append(const String &str)
{
	char *new_contents = new char[(len + str.len) + 1];		

	strcpy(new_contents, contents);
	strcat(new_contents, str.contents);

	contents = new_contents;

	delete new_contents;
}

Although, I don't think I'm pointing contents to new_contents correctly, am I? Sorry, I'm still very new to pointers and how they work.
 

Slavik81

Member
Close. That's the new contents you're deleting. You need to delete the old stuff.

Hint: it's easier to delete the right thing if you move that delete.

Also, use "delete[]" when you're deleting an array.

Although, I don't think I'm pointing contents to new_contents correctly, am I? Sorry, I'm still very new to pointers and how they work.
That part's fine.
 

Water

Member
He claims it's for portability and what's "easiest." Bear in mind, this isn't an entry-level CS course, but an upper-level class. We've already had at least six classes that have taught us C++ as well.
C++11 is more friendly and reasonable for newbies than C++98. I guess it's "easiest" for your instructor if he doesn't have to learn modern C++. :p

Even when you have to use C++98/03 for some real world project, good coding style is normally close to how you'd write the same thing in C++11. You can emulate some of the newer functionality yourself or scrounge it up from Boost or other libraries - if you know what to aim for. And coding in C++11 gives you a pretty good idea of that.
 

Water

Member
I need some help. I've spent hours on this single function that I cannot get to work correctly. I'm missing something but I don't know what.

So my assignment is to make my own string class. I am allowed to use cstring functions (I'm working in C++), though. My prof gave us the driver file and the header file. I am simply implementing each function.
Unless you've been told to use raw pointers, new and delete, using something like std::vector<char> to store the data would probably be safer and more convenient. Since vector stores data sequentially, you can get a raw pointer to the data and read from it, so it doesn't prevent you from using C string functions either.
 
C++11 is more friendly and reasonable for newbies than C++98. I guess it's "easiest" for your instructor if he doesn't have to learn modern C++. :p

Even when you have to use C++98/03 for some real world project, good coding style is normally close to how you'd write the same thing in C++11. You can emulate some of the newer functionality yourself or scrounge it up from Boost or other libraries - if you know what to aim for. And coding in C++11 gives you a pretty good idea of that.

[rant]

I think I'm more upset with the teaching style than what I'm actually learning. From where I'm sitting (with limited experience, mind you), C++ accomplishes the goal of being all things to all people. However, it comes at the price of an incredibly confusing web of syntax and built-in constructs.

Our university does what I would do; namely, they narrow down the syntax and libraries per project to focus on what they're trying to teach you. Since we start with C, there's not much to narrow down. However, when we transition to learning C++ they continue as if we're just extending C.

This means as an upper-level undergraduate student, I'm still being forced to use C style arrays, create all my own list structures, and (as in this instance) forgo header files for "ease." Want to teach me how C++ is capable of being a high-level assembly language? That's fine. Just don't force me to approach every program with that mindset.

[/rant]
 

Chris R

Member
Not pretty, but it works.

Code:
string input = "01234";
string output = input.Length < 5 ? input : input.Length < 7 ? input.Insert(4, ".") : input.Insert(4, ".").Insert(7, ".");
 

CrankyJay

Banned
Not pretty, but it works.

Code:
string input = "01234";
string output = input.Length < 5 ? input : input.Length < 7 ? input.Insert(4, ".") : input.Insert(4, ".").Insert(7, ".");

Yeah, that's roughly what i ended up doing. Dunno what I was thinking of Regex Replace or a String.Format but this is easier.

Thanks.
 

danthefan

Member
Is there a go-to IDE or whatever for Python? Or should I be using the command line? I've been using IDLE so far but the text editor is awful. I'll need to use Python for work a bit and to be honest I'm just looking for convenience rather than becoming an expert.
 
Close. That's the new contents you're deleting. You need to delete the old stuff.

Hint: it's easier to delete the right thing if you move that delete.

Also, use "delete[]" when you're deleting an array.


That part's fine.

Thanks. Am I getting closer..? I talked to a few classmates today and it seems I'm not the only one having a lot of trouble with this, which makes me feel a bit better :p

Code:
void String::append(const String &str)
{
	char *new_contents = new char[(len + str.len) + 1];		

	strcpy(new_contents, contents);
	strcat(new_contents, str.contents);

	delete [] contents;

	contents = new_contents;
	
}

Actually, I just realized this code causes the program to crash right after I finish entering what I want to append.

Unless you've been told to use raw pointers, new and delete, using something like std::vector<char> to store the data would probably be safer and more convenient. Since vector stores data sequentially, you can get a raw pointer to the data and read from it, so it doesn't prevent you from using C string functions either.

Unfortunately I'm pretty restricted with what I'm allowed to use. Vectors crossed my mind the other day but I have to keep it this way :(
 

Saprol

Member
Code:
       BankAccount.makeDeposit(dDepositAmount); [b]<- ERROR non static method makeDeposit cannot be referenced from a static context in the main class[/b]

However, when I do this I get non static method makeDeposit cannot be referenced from a static context in the main class.

dBalance must be a private double in the bank account class.

Have you created a BankAccount object?
 

BreakyBoy

o_O @_@ O_o
Is there a go-to IDE or whatever for Python? Or should I be using the command line? I've been using IDLE so far but the text editor is awful. I'll need to use Python for work a bit and to be honest I'm just looking for convenience rather than becoming an expert.

Most Python devs I know don't use IDEs, just editors like vim/emacs/Sublime.

That being said, I asked around and I was pointed to this blog entry as a good overview of the current options: http://pythoncentral.org/comparison-of-python-ides-development/

I have to say though that with the right plugins you can make editors like Sublime do most of the IDE-like things you might be looking for. Code completion, folding, highlighting, linting, even debugging for certain languages/environments.
 

r1chard

Member
Is there a go-to IDE or whatever for Python? Or should I be using the command line? I've been using IDLE so far but the text editor is awful. I'll need to use Python for work a bit and to be honest I'm just looking for convenience rather than becoming an expert.

Anything but IDLE*.

PyCharm if you want a full IDE. Sublime Text if you want a smart graphical editor with plugin gizmos.



It's really sad, but IDLE is basically controlled by a bunch of folk who resist all efforts to make it not suck :(
 

kingslunk

Member
Is there a go-to IDE or whatever for Python? Or should I be using the command line? I've been using IDLE so far but the text editor is awful. I'll need to use Python for work a bit and to be honest I'm just looking for convenience rather than becoming an expert.

Vim.
 

BreakyBoy

o_O @_@ O_o
Now that I've taken the time to actually read the link I posted instead of pass it along, this related article reflects my views on text editors vs IDEs pretty nicely:

http://www.pythoncentral.io/text-editors-vs-ides-for-python-development-selecting-the-right-tool/

I have far more experience with the text editor side of things* and I generally agree with his reflections on those as well:

http://www.pythoncentral.io/best-text-editors-for-python-development/

As such, I wouldn't be surprised to find that his IDE overview was spot on as well.

* Except emacs. I keep meaning to give that a go someday, but it's such a deep dive, and I'm only now feeling super comfortable with vim after a few years.
 

Vire

Member
Have you created a BankAccount object?

Yeah, I was being silly and had it set to BankAccount.makeDeposit instead of the object itself! Thank you.

I'm now stuck on something else though, we have to use a boolean method to determine if the user can withdraw or not:

so I have this

Code:
 public boolean makeWithdrawal(double dWithdrawalAmt){
        
        boolean bCheckWithdrawal = false;
        
        if(dBalance<dWithdrawalAmt){
        bCheckWithdrawal = false;
        
        }
    
        if(dBalance>dWithdrawalAmt){
        bCheckWithdrawal = true;
        
        dBalance=dBalance-dWithdrawalAmt;
        }
        
        return bCheckWithdrawal;
    }

and

Code:
else if(nAccountOption == 4 && nCount >=0){
       System.out.print("Please enter the withdrawal amount: ");
       dWithdrawalAmount = input.nextDouble();
       
       //If it's a default constructor call Withdrawal method to determine if you are eligible to withdraw.
       if(nSelection == 1 && bankEmpty.makeWithdrawal(dWithdrawalAmount) == false){
       
       System.out.println("Insufficient funds. Withdrawal not made.");
       System.out.println("");
       }//end if
       
       //If it's a default constructor call Withdrawal method to determine if you are eligible to withdraw.
       if(nSelection == 1 && bankEmpty.makeWithdrawal(dWithdrawalAmount) == true){
           
           System.out.println("Withdrawal successful");
           System.out.println("");
           
       }
       
       //If it's an overload constructor call Withdrawal method to determine if you are eligible to withdraw.
       if (nSelection == 2 && bankAvailable.makeWithdrawal(dWithdrawalAmount) == false){ 
       System.out.println("Insufficient funds. Withdrawal not made.");
       System.out.println("");
       }
       
       //If it's an overload constructor call Withdrawal method to determine if you are eligible to withdraw.
       if (nSelection == 2 && bankAvailable.makeWithdrawal(dWithdrawalAmount) == true){ 
          // SUBTRACT WITHDRAWAL FROM BALANCE
           
            System.out.println("Withdrawal successful");
           System.out.println("");
       }
      
       }//end else if

I've been staring at it for too long and I have a feeling the answer is right in front of me, but when I do the output I get this:
output said:
run:
ACCOUNT PROCESSING MENU
1. Create new account - empty account
2. Create new account - information available
3. Make deposit
4. Make withdrawal
5. Calculate monthly interest
6. View account balance
7. Next available account number
8. Update monthly interest rate
9. Print account information
10. Exit
Please enter your preferred option: 1
Account #12345 successfully created.

Please enter your preferred option: 3
Please enter the deposit amount: 1000

Please enter your preferred option: 4
Please enter the withdrawal amount: 25
Withdrawal successful

Please enter your preferred option: 9
Account number: 12345
Account balance: $950.0

So for some reason it's doing the withdrawal twice.
 

Chris R

Member
It's doing it twice because you are calling it twice.

When nSelection == 1 (or two) you will call bankEmpty.makeWithdrawal(dWithdrawalAmount) twice.

Either set the result returned from your bankEmpty.makeWithdrawal(dWithdrawalAmount) to a variable or setup an inner if/else clause that calls bankEmpty.makeWithdrawal(dWithdrawalAmount) a single time.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
I'm running into an issue with a JavaScript program I've been working on in my spare time. The concept is that the program will draw a "pixel grid" on the screen then later on iterate through and change the color of the "pixels" based on various parameters.

At this stage I have a working display and I can manually change all of the colors and such just fine. What I need to do though is to store each individual "pixel" in an array as it's own object. The "pixels" will have an X/Y coordinate stored for their top left corner, along with their current color.

The problem I'm running into is that after storing all of the objects into the array, if I go to access those objects, every single one has the values of the last object. If I access the objects while creating and storing, it shows that the proper values are being stored, but accessing them after shows incorrect values.

Here's the code. It's rather short.

Code:
// inner window size constants
var WIDTH = 1050;
var HEIGHT = 550;

var pixels = [];

var colors = [
    '#000000', '#080808', '#101010', '#181818', '#202020', '#282828',
    '#303030', '#383838', '#404040', '#484848', '#505050', '#585858',
    '#606060', '#686868', '#707070', '#787878', '#808080', '#888888',
    '#909090', '#989898', '#A0A0A0', '#A8A8A8', '#B0B0B0', '#B8B8B8',
    '#C0C0C0', '#C8C8C8', '#D0D0D0', '#D8D8D8', '#E0E0E0', '#E8E8E8',
    '#F0F0F0', '#F8F8F8', '#FFFFFF'
];

var pixel = {
    rowPos : 0,
    colPos : 0,
    color : "#000000"
};


function draw() {
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

    // set canvas size
	context.canvas.width = WIDTH;
	context.canvas.height = HEIGHT;

	// defines the pixel density of display
	var pixelRows = 10;
	var pixelColumns = 33;

	var pixelRowPos = 0;
        var pixelColPos = 0;

        var pixelWidth = 30;
        var pixelHeight = 50;

	var colorIndex = 0;


    for (var i = 0; i < pixelRows * pixelColumns; i++) {

        context.beginPath();
        context.rect(pixelColPos, pixelRowPos, pixelWidth, pixelHeight);
        context.fillStyle = colors[colorIndex];
        context.fill();
        context.lineWidth = 1;
        context.strokeStyle = '#ffffff';
        context.stroke();

        pixel.rowPos = pixelRowPos;
        pixel.colPos = pixelColPos;
        pixel.color = colors[colorIndex];
        pixels[i] = pixel;

        // While creating, prints out each object's values.
        // This is printing correctly with the correct values.
        console.log(pixels[i]);

        if (pixelColPos == 960) {
            pixelRowPos += 50;
            pixelColPos = 0;
        } else {
            pixelColPos += 30;
        }
    }
}

function start() {

    // This will eventually be where the manipulation logic will live.
    // Right now it is just iterating through the array and printing each object's info.

    // This is where the incorrect data is displayed.
    for (var k = 0; k < pixels.length; k++) {
        console.log(pixels[k]);
    }

}

Any help would be much appreciated. Thanks in advance.
 

Vire

Member
It's doing it twice because you are calling it twice.

When nSelection == 1 (or two) you will call bankEmpty.makeWithdrawal(dWithdrawalAmount) twice.

Either set the result returned from your bankEmpty.makeWithdrawal(dWithdrawalAmount) to a variable or setup an inner if/else clause that calls bankEmpty.makeWithdrawal(dWithdrawalAmount) a single time.

EDIT: So something like this?

Code:
 //If it's a default constructor call Withdrawal method to determine if you are eligible to withdraw.
       if(nSelection == 1 && bankEmpty.makeWithdrawal(dWithdrawalAmount) == true){
       
      System.out.println("Withdrawal successful");
           System.out.println("");
       }//end if
       

       else if(nSelection == 1){
           
           System.out.println("Insufficient funds. Withdrawal not made.");
           System.out.println("");
           
       }
Works :)
 
Top Bottom