• 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

mackattk

Member
I'm back again.

I am trying to get some functions to run in my program, and some reason it just isn't wanting to work. I have been trying different ways to get this working, but no luck so far.

The thing compiles fine, but when I try to run it I get this error:

Code:
1>estepPass9.obj : error LNK2019: unresolved external symbol "double __cdecl bestbuy(double &,double &,double,double,double)" (?bestbuy@@YANAAN0NNN@Z) referenced in function _main
1>C:\Users\Mark\Documents\Visual Studio 2010\Projects\Pass9\Debug\Pass9.exe : fatal error LNK1120: 1 unresolved externals
1>
1>Build FAILED.

Here is my input:

Code:
#include <iostream>
#include <iomanip>
using namespace std;

void bestbuy (double &min, int &lownumber, double price1, double price2, double price3);
void discountResults (double price, double discountPercent);
void howMany (double amountMoney, double cost);

int main()
{
	int menu =0;
	int b=0;
	double a=0, c=0, d=0, e=0;
	char choice;

	while (menu != 99)
	{
	cout << "(B)est Buy Calculation" << endl;
	cout << "(D)iscount Calculation" << endl;
	cout << "(H)ow Many Calculation" << endl;
	cout << "(Q)uit" << endl << endl;
	cout << "Please enter the option (B, D, H, or Q)" << endl;
	cin >> choice;

switch(choice)
	{
	case 'b':
	case 'B': 
		bestbuy(a, b, c, d, e);
		cout << "The smallest price is " << a << "and is price number" << b << endl;
		break;
	case 'd':
	case 'D': cout << "You entered D" << endl;
		break;
	case 'h':
	case 'H': cout << "You entered H" << endl;
		break;
	case 'q':
	case 'Q': cout << "You entered Q" << endl;
		system("pause");
		return 0;
		break;
	default: cout << "Please enter B, D, H, or Q" << endl;
		break;
	}
	cout << "Please enter the option (B, D, H, or Q)" << endl;
	}
	return 0;
}


void bestbuy(double min, int lownumber, double price1, double price2, double price3)
{
	cout << "Please enter three prices seperated by a space" << endl;
	cin >> price1 >> price2 >> price3;
	if (price1<=price2 && price1 <= price3)
	{
		min=price1;
		lownumber=1;
	}
	else if (price2 <=price1 && price2 <=price3)
	{
		min=price2;
		lownumber=2;
	}
	else
	{
		min=price3;
		lownumber=3;
	}
}

The program is largely incomplete, but I am stuck on this best buy calculation that is refusing to run.
 
Here is my input:

Code:
double bestbuy (double &min, double &lownumber, double price1, double price2, double price3);

double bestbuy(double min, double lownumber, double price1, double price2, double price3)
{
	....Code Was Here...
}

The program is largely incomplete, but I am stuck on this best buy calculation that is refusing to run.

This should make it a little more obvious. Hint: Look at your prototype. Look at the function implementation's declaration.
 

Spoo

Member
I'm back again.

...

The program is largely incomplete, but I am stuck on this best buy calculation that is refusing to run.

You're function prototype doesn't match the implementation. You're missing & symbols.

edit: also, you're going to have some serious issues when it does manage to run. If you write a return statement, and then have another one immediately after it, that's unreachable code.
 

mackattk

Member
This should make it a little more obvious. Hint: Look at your prototype. Look at the function implementation's declaration.

Thanks, got it. I have major problems trying to figure out what is going wrong, and I end up messing other things up that were correct in the first place.

You're function prototype doesn't match the implementation. You're missing & symbols.

edit: also, you're going to have some serious issues when it does manage to run. If you write a return statement, and then have another one immediately after it, that's unreachable code.

Fixed, changed it back to a void function without any returns.
 

Karl2177

Member
No problem. It's a common mistake to fail to rebuild something, and I love being right. I hope we were of help.
For the record, I totally read that in L's voice. Your avatar made it so compelling.


-snip-

The program is largely incomplete, but I am stuck on this best buy calculation that is refusing to run.

I don't think it will resolve the issue at the top, but I remember having to specifically set my doubles to 0.0 for them to perform like doubles should. Otherwise I only had a semester of C++, so I'm sorry I can't be of a ton of help. :/

EDIT: Welp, nevermind that. You got it. :)
 
You're function prototype doesn't match the implementation. You're missing & symbols.

edit: also, you're going to have some serious issues when it does manage to run. If you write a return statement, and then have another one immediately after it, that's unreachable code.

That's right. In fact, he should change it to a void since judging by what he's attempting to do. He only needs to modify the passed by reference double values.
 

mackattk

Member
That's right. In fact, he should change it to a void since judging by what he's attempting to do. He only needs to modify the passed by reference double values.

Thanks for all your help, I was able to finish the rest of the assignment relatively quickly once I got over that hurdle. When I start to get frustrated at programming, I really just need take a break and go outside for a bit.

I am also going to college online, so it seems to be a little tougher trying to figure things out on my own without being able to bother my classmates, lol.
 

neemmss

Member
I keep getting discouraged going forward in learning python. The books and video tutorials I am reading sometimes confuse me to the point that I do not even understand what they are doing and that alone makes me want to stop. I really want to learn, but I am having a tough time understanding sometimes.

Do you have any tips on learning a language the right way? Should I be taking notes a certain way?
 

f0rk

Member
Can anyone give me a hand with an error I'm getting in fortran? It's a big program I'm editing to make it work on a different function v(i) = 10*exp(-(i^2))

The code I have is
Code:
Do 20 I=I,N
V(I)=10*exp(-(I*I))
F(I)=exp(-V(I))-1

20  CONTINUE

The error in the compiler is

Code:
 V(I)=10*exp(-(I*I))     1
Error: 'x' argument of 'exp' intrinsic at (1) must be REAL or COMPLEX
 
I keep getting discouraged going forward in learning python. The books and video tutorials I am reading sometimes confuse me to the point that I do not even understand what they are doing and that alone makes me want to stop. I really want to learn, but I am having a tough time understanding sometimes.

Do you have any tips on learning a language the right way? Should I be taking notes a certain way?

Learning a programming language works the same as any other language. Constantly practice is the only think you can do. Once you learn 2 or 3, you should be able to pick up any language. Once the language barrier is passed, it then comes down to problem solving skills.
 

Kinitari

Black Canada Mafia
So I'm back, and while I've made progress on the multiple columns to single date issue I had earlier (thanks for the CDate tip Zoe, I made a new query in the original database that smooshes together the columns and runs a CDate on them) - I am hitting a pretty frustrating road block in the last step to making this shit work! I'll try to keep it concise.

In my tableAdapter's fill method, I have some pretty straightforward SQL that works up until the WHERE statement which looks like:

Code:
WHERE     [Client Visits Date Query].[Logged In] > #" & timeAfter & "#
 AND [Client Visits Date Query].[Logged In] < #" & timeBefore & "#

excuse the horrible names :p, but basically my timeBefore and timeAfter are datetime parameters I get from the winform that has the datepicker that represent the date block I want to search for clients. So I am trying to populate my DGV with a row's "Logged in" time when it falls between the two times.

All seemed to be going decently, small hickup with the parameter syntax, but got passed that. Now I get this new fancy error:

Cannot convert entry to valid date/time; TO_DATE function might be required.
At this point I am pretty lost. I have a feeling that somehow, somewhere my dates from either my database or my datepicker are formatted in a way that is causing the issue - I just have no idea where it's happening, don't know how to apply the TO_DATE function to my query in any meaningful way either.

My formatting in the (access) database is:

Code:
CDate([Month] & "/" & [Date] & "/" & [Year] & " " & [Time In]) AS [Logged In]
representing the 4 columns I've smushed into a datetime via CDate

While my DatePicker is a bit more complex, I actually have 3 datepicker controls running in that form, 1 that runs as a calendar style picker, and the other two that are just time pickers. So the user picks the Calendar date, then selects the after time then the before time to create a range. I then smush those together into a new dateTime ala:

Code:
DateTimeAfter = dateTimePicker1.Value.Date + DateTimePicker2.Value.TimeOfDay;
DateTimeBefore = dateTimePicker1.Value.Date + dateTimePicker3.Value.TimeOfDay;

And while they both seem to work, this issue crops up. My Google-Fu is of pretty much no use with this issue, so I turn to GAF again, hoping for a miracle.


Also - while I am generally looking for help in solving my issue, if anyone wants to give me general programming advice that they can think of from seeing my code/methodology, please share - I'm still extremely new at this (fresh out of school) so the advice is super essential for me.
 

Hari Seldon

Member
I keep getting discouraged going forward in learning python. The books and video tutorials I am reading sometimes confuse me to the point that I do not even understand what they are doing and that alone makes me want to stop. I really want to learn, but I am having a tough time understanding sometimes.

Do you have any tips on learning a language the right way? Should I be taking notes a certain way?

Have you tried the coursera stuff? There are two classes on python there. One is more basic, the other is faster pace but ramps up to game programming by week 4 ( doing Pong this week).
 

usea

Member
Can anyone give me a hand with an error I'm getting in fortran? It's a big program I'm editing to make it work on a different function v(i) = 10*exp(-(i^2))

The code I have is
Code:
Do 20 I=I,N
V(I)=10*exp(-(I*I))
F(I)=exp(-V(I))-1

20  CONTINUE

The error in the compiler is

Code:
 V(I)=10*exp(-(I*I))     1
Error: 'x' argument of 'exp' intrinsic at (1) must be REAL or COMPLEX
I've never written fortran, but it sounds like it's complaining that the argument of the exp(x) function has to be real or complex. I think you're passing it an integer instead. Check out these pages
https://en.wikipedia.org/wiki/Fortran_language_features#Intrinsic_data_types
https://en.wikibooks.org/wiki/Fortran/Fortran_examples
 

Zoe

Member
So I'm back, and while I've made progress on the multiple columns to single date issue I had earlier (thanks for the CDate tip Zoe, I made a new query in the original database that smooshes together the columns and runs a CDate on them) - I am hitting a pretty frustrating road block in the last step to making this shit work! I'll try to keep it concise.

Once again, keep in mind I'm not familiar with Access's syntax. Two suggestions:

1) Use BETWEEN if it exists in Access
2) It looks like that might be converting timeAfter/timeBefore into strings before the query attempts to convert it to a datetime. Have you tried it without the #"& stuff?
 

injurai

Banned
I'm a bit confused on how Interfaces differ from classes in Java. Why the need? Any good resources that detail this. As far as I can see an Interface just renames a class... or something...
 

Chris R

Member
So I'm back, and while I've made progress on the multiple columns to single date issue I had earlier (thanks for the CDate tip Zoe, I made a new query in the original database that smooshes together the columns and runs a CDate on them) - I am hitting a pretty frustrating road block in the last step to making this shit work! I'll try to keep it concise.

What does your [Logged In] column look like?
 
I'm a bit confused on how Interfaces differ from classes in Java. Why the need? Any good resources that detail this. As far as I can see an Interface just renames a class... or something...

Simply put, an interface tells other pieces of your code what your class is capable of doing. Other pieces of code can now know about parts of your class without knowing about the class itself.

For a convoluted example because I'm terrible at examples, say you have some stupid drawing application where you have different types of shapes. All shapes in the application are stored in one giant array. Say you want to calculate the area of all the shapes. The problem is that some of the primitives may not necessarily have an area:

Code:
/* base primitive class that all shapes derive from */
abstract class Shape { /* definition */ };

/* an interface stating that a shape can calculate its own area */
interface IAreaCalculatable { int getArea(); };

/* lines don't really have an area */
class Line : Shape { /* definition */ };

/* squares and circles do, however */
class Square : Shape, IAreaCalculatable { /*definition */ };
class Circle : Shape, IAreaCalculatable { /*definition*/ };

double calculateTotalArea(Shape[] shapes) {
   double total = 0.0;
   foreach( Shape shape in shapes ) {
       if ( shape is IAreaCalculatable )
           total += (IAreaCalculatable)shape.getArea();
   }
   return total;
}
 

Kinitari

Black Canada Mafia
Once again, keep in mind I'm not familiar with Access's syntax. Two suggestions:

1) Use BETWEEN if it exists in Access
2) It looks like that might be converting timeAfter/timeBefore into strings before the query attempts to convert it to a datetime. Have you tried it without the #"& stuff?

I really should use BETWEEN :p don't know why I didn't. But I gave it a shot, and the same error cropped up.

What does your [Logged In] column look like?

If data from the table does not have a login time(some of the older stuff was around before they implemented a time stamp), it's month/day/year - ie, 10/6/2012.

If it does have a timestamp, it's month/day/year h:mm, ie 10/6/2012 4:15pm
 

Chris R

Member
I really should use BETWEEN :p don't know why I didn't. But I gave it a shot, and the same error cropped up.



If data from the table does not have a login time(some of the older stuff was around before they implemented a time stamp), it's month/day/year - ie, 10/6/2012.

If it does have a timestamp, it's month/day/year h:mm, ie 10/6/2012 4:15pm

Have you tried using a static time in place of the column value to see if the issue lies with the column? If it doesn't work with a static date value then you would know that something is acting up when you are trying to compare using the timeBefore and timeAfter variables.
 

jokkir

Member
I have a question about having better looking code:

When is the proper time using PHP on a webpage? I'm thinking of rewriting my webpage so it's better designed.

I know for HTML/CSS/Javascript, the general convention is to separate the content, design, and effects separately. How would that work with PHP? What I was doing was just if the stuff was in a table, I would create a loop for the <td> and <tr> tags but for some reason, I'm thinking that's just bad design?
 

Kinitari

Black Canada Mafia
Have you tried using a static time in place of the column value to see if the issue lies with the column? If it doesn't work with a static date value then you would know that something is acting up when you are trying to compare using the timeBefore and timeAfter variables.

Oddly enough I hadn't given that a thought, I've mostly been assuming I was passing the parameter wrong. My workday is over, so I'll give ita shot tomorrow and let you know!
 

usea

Member
I have a question about having better looking code:

When is the proper time using PHP on a webpage? I'm thinking of rewriting my webpage so it's better designed.

I know for HTML/CSS/Javascript, the general convention is to separate the content, design, and effects separately. How would that work with PHP? What I was doing was just if the stuff was in a table, I would create a loop for the <td> and <tr> tags but for some reason, I'm thinking that's just bad design?
Yeah, that's definitely not a good idea. PHP isn't for content, design or effects. It's a programming language executed on the server (rather than the web browser), like user input or displaying information from a database. It's also concerned with how you display that data, but that's because it's bad. It doesn't sound like you have any server-side processing that needs to be done, so if that's the case then you don't need a server-side language like php.

If you do need it, you can use a template framework to separate your layout/content from your code.
 

Tantalus

Neo Member
I have a question about having better looking code:

When is the proper time using PHP on a webpage? I'm thinking of rewriting my webpage so it's better designed.

I know for HTML/CSS/Javascript, the general convention is to separate the content, design, and effects separately. How would that work with PHP? What I was doing was just if the stuff was in a table, I would create a loop for the <td> and <tr> tags but for some reason, I'm thinking that's just bad design?

I've found this method of implementing PHP to be fairly readable.

Code:
<body>
<p>
<?php for($x=0; $x<10; ++$x): ?>
    <a href="hello.php">link</a>
<?php endfor; ?>
</p>
</body>

Everything between the beginning of the for: loop and endfor; is outputted in the loop, as if it were being echoed in PHP. This works the same way for if: and endif as well as foreach: and endforeach.

I think using a loop to generate a table is fine when you need the table to change based on something server side. A table that shows private messages, for example. If the user in question has 10 messages, you're going to need 10 rows, if they have 2 messages, then you only need 2 rows. In these cases I would write it like so:

Code:
<table>
<?php for($x=0; $x<$numberMessages; ++$x): ?>
    <tr>
        <td>Message number <?php echo $x; ?></td>
        <td><?php echo $messages[$x]; ?></td>
    </tr>
<?php endfor; ?>
</table>

That said, it is a good idea to separate business logic (database queries and whatnot) from presentational stuff like markup. I don't think that this always needs an entire "templating engine", but those are an okay place to start with to get the idea of separating your code down
 
I'm a bit confused on how Interfaces differ from classes in Java. Why the need? Any good resources that detail this. As far as I can see an Interface just renames a class... or something...

DISCLAIMER: Everything below this line I wrote without checking for compiling, there might be mistakes.
-----

There are 3 separate things to be aware of: Interfaces, Abstract Classes, and Classes.

A Class is a description of the fields and methods that belong to an object. Classes can be instantiated and the resulting object used.

An Abstract Class is a class that cannot be instantiated, if you try to create an object from an Abstract Class the compiler will cry. 0 or more methods in an Abstract class may be left undefined and these must be implemented by a (Concrete) Class that extends that Abstract Class.

For example:
Code:
public abstract class Foo
{
    public abstract void abstractMethod(); //look no implementation
    public abstract void concreteMethod()
    {
        //code goes here
    }
}

public class Bar extends Foo
{
    public void abstractMethod()
    {
        //code to implement abstract method goes here
    }
}

In the above example, Bar is required to implement the method defined in Foo but you cannot create a new Foo object as it is Abstract.

Code:
Foo foo = new Foo();
will fail,
Code:
Foo bar = new Bar();
will succeed.

An Interface is just an Abstract Class that can only define Abstract Methods, it can not provide method implementations. A Class that extends an Interface must implement all of the methods defined in the Interface. This guarantees that a class that implements an Interface will have certain methods available and Interfaces themselves can be used as types in method calls.

The reason that Interfaces exist instead of just allowing multiple Abstract Classes is an explicit design decision to help avoid the Diamond Problem, the summary of this is that if a Class could inherit multiple Abstract Classes that might have provided an implementation for a method, the compiler has no way of knowing which implementation is referred to. (Some languages avoid this in more elegant ways, see Python). Since an Interface is not allowed to provide any implementation for methods, Classes can safely inherit any number of interfaces and avoid the Diamond Problem.

tldr:
Class: normal behaviour, can inherit 1 and only 1 Abstract Class or infinity Instances
Abstract Class: Cannot be instantiated, 0 or more method implementations may be omitted.
Interface: Same as an Abstract Class but cannot implement any methods. Exists to avoid the Diamond Problem.
 

Zoe

Member
I have a question about having better looking code:

When is the proper time using PHP on a webpage? I'm thinking of rewriting my webpage so it's better designed.

I know for HTML/CSS/Javascript, the general convention is to separate the content, design, and effects separately. How would that work with PHP? What I was doing was just if the stuff was in a table, I would create a loop for the <td> and <tr> tags but for some reason, I'm thinking that's just bad design?

You use a server-side renderer when you have dynamic content to display. If everything is static, there's really no reason to not just have it in straight HTML.

That being said, depending on your needs, it may be beneficial to future-proof your site to load dynamically via some kind of CMS.
 

Tomat

Wanna hear a good joke? Waste your time helping me! LOL!
The more one of my professors talks about the Computer Science degree, the more I'm starting to think it's a major for code monkeys.

Prof makes it sound like Software Engineering was the way to go since they design the code and had it off to programmers.
 

usea

Member
The more one of my professors talks about the Computer Science degree, the more I'm starting to think it's a major for code monkeys.

Prof makes it sound like Software Engineering was the way to go since they design the code and had it off to programmers.
Every job is radically different from the next. To generalize an entire field like that is laughable. There are small consulting shops (like, tens of thousands of them) where every person does the design, implementation, documentation, etc. They do it all. There are huge companies where your role is well-defined and you maybe just do UML diagrams all day, or you just code to a spec (these are becoming much more rare). There are a huge number of small companies where you're expected to be a full-stack engineer, which means not just programming and designing software, but designing the front-end of a website, administering servers and databases, talking to customers over chat, etc. There are tons of places where you will only maintain old software, never making anything new. If you can think of it, there are places that would have you do it.

A degree does not equal a job. You can get the same jobs with a CS degree or Software Engineering, or a music degree. A degree is a set of courses, and the main take-away from courses is what skills and knowledge you obtain. That's it. Make a list of the courses that are different between the two and decide which ones you think would be better. Don't pay any mind to people who run their mouth and generalize things like that professor.

At my school, there was only CS. It included software engineering courses (like eliciting requirements from real clients, working on a group project, estimating time, etc), theory courses (everything from data structures to numerical analysis to machine learning), IT courses like linux administration, and web design courses. You could basically create your own set of courses for your degree, within some limits. Other schools have very specific degrees focused on different areas like CS for theory-only with no practical skills (a phd track, really), a developer track that's very light on theory, etc. In the end, they're just sets of courses. The name of the concentration or major doesn't matter at all.
 

Zoe

Member
At UT, Software Engineering was more code monkey. CS there is more theoretical. You could go through at least two years without ever writing any code.
 
The more one of my professors talks about the Computer Science degree, the more I'm starting to think it's a major for code monkeys.

Prof makes it sound like Software Engineering was the way to go since they design the code and had it off to programmers.

At UTD, it was 90% a math degree, 8% software design, and 2% code monkey since I tested out of Comp Sci 1 and 2.
 

injurai

Banned
The more one of my professors talks about the Computer Science degree, the more I'm starting to think it's a major for code monkeys.

Prof makes it sound like Software Engineering was the way to go since they design the code and had it off to programmers.

At my school they call it Computer Science and Software Engineering (CSE) which we deal with a lot of abstract views of code. Stuff that basically lays out how parts need to interact but now how they get implemented. But then we end up and implement them so we learn both parts.

We then have a Computer Information Sciences (CIS) which will be more IT, networking, presumably code monkey stuff. Its usually recommended to spend a few years writing code though at a company before moving up. Otherwise you may not recognize the challenges your implementors will be facing.
 

Slavik81

Member
The more one of my professors talks about the Computer Science degree, the more I'm starting to think it's a major for code monkeys.

Prof makes it sound like Software Engineering was the way to go since they design the code and had it off to programmers.

I'd like to point out that if the design were complete, the architects handing off designs to programmers would actually just be able to compile their designs into working programs. The act of programming is fundamentally an act of design. Even in your stated example, the programmers would be doing significant design themselves to fill in the holes the architects left.

But regardless, a degree in Software Engineering vs Computer Science will not be the difference between working in those jobs. The role of software architect is one that requires significant experience with the specific technologies being used, and familiarity with the company's products, it's customers and its employees. It is not something to drop a new graduate into.

Beyond that, I don't think the roles you're talking about are even desirable. As usea mentioned, there are places that do that, but there are many (perhaps more?) that do not. I think Martin Fowler's piece "Who Needs an Architect?" is quite good, and he suggests that the ideal architect is very different from the one you describe.

For the record, I have a degree in Electrical Engineering. My peers have degrees in Computer Science, Electrical Engineering, Computer Hardware Engineering and Software Engineering. There is quite a bit of latitude in the path you take to becoming a software developer. Honestly, being a bright person and having a background in computing is sufficient. No matter what degree you choose, you will have to learn quite a lot after you graduate.
 
I graduated 2 years ago, in the middle of a PhD right now and every single day I learn more and more about all the stuff I don't know. What I discovered very quickly after I finished my degree (Computer Science and Software Engineering, theory and practice, work placement for 1 year so more hands on than a lot of courses) was that I now knew enough to begin learning all the other stuff I needed to know on my own. It's an enormous mistake to think that a degree means anything other than that you have had a light introduction to the groundwork of knowledge that is out there.

Also, not all of us PhD's are straightjacketed by theory and unable to implement anything, some of us recognise that code is a vector to apply theory and make sure we're good at it. :p
 

BHZ Mayor

Member
I graduated 2 years ago, in the middle of a PhD right now and every single day I learn more and more about all the stuff I don't know. What I discovered very quickly after I finished my degree (Computer Science and Software Engineering, theory and practice, work placement for 1 year so more hands on than a lot of courses) was that I now knew enough to begin learning all the other stuff I needed to know on my own. It's an enormous mistake to think that a degree means anything other than that you have had a light introduction to the groundwork of knowledge that is out there.

Also, not all of us PhD's are straightjacketed by theory and unable to implement anything, some of us recognise that code is a vector to apply theory and make sure we're good at it. :p

I'm currently experiencing the fallout from this truth bomb.
 

Kinitari

Black Canada Mafia
Have you tried using a static time in place of the column value to see if the issue lies with the column? If it doesn't work with a static date value then you would know that something is acting up when you are trying to compare using the timeBefore and timeAfter variables.

Sorry for the late reply, been doing a lot of other things at work last few days. After doing some fiddling, looks like it's my column that is having trouble being converted into a datetime - gonna try to do some stuff to work around that (this internship is a pretty baller learning experience) - if you or anyone else wants to give me any advice in the process, I'd appreciate it!

edit: !!!!!!

Fucking breakthrough! I tried fiddling a bit with my columns, and suddenly realized that my FIRST entry was going through before an error was thrown at me - tried to figure out why, and noticed that the first entry was in the mm/dd/yyyy format, (unintentionally, the date was 12/14/2010) where as the data is by default d/m/yyyy. Tried throwing a format function around that motherfucker and PRESTO, almost all my entries went through the query although i was still hit with a random error - it might just because I am in debug mode and I did something silly with my syntax.

BOOM. It seems like a weird problem, I assumed dates could compare between different formats without an explicit cast, but whatevs!

edit2: Okay, figured out where my other error came from - basically changing the format of my column worked great for the date portion, but for the time portion it isn't working at all. So I am going to spend the next little while figuring out why this is, but this seems to be a problem other people on the internet have had (specifically the 'datatype mismatch' error) - so I probably have many new avenues of tackling this problem, and I've made SOME progress.

What I've noticed is that I am learning SOOO goddamn much from real world experience. What I learn in a day here is easily equivalent to a week at school. Sometimes moreso
 

smiggyRT

Member
Quick c# question here, basically pushing random numbers into a stack then popping them off and printing them to the console. Thing is the same 10 numbers are getting displayed in the console.

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Lab3_Library
{
    class Program
    {
        static void Main(string[] args)
        {
            MmuStack mystack = new MmuStack();
            int i = 0;

           while ( i < 10 )
            {
                Random random = new Random();
                int randgen = random.Next(0, 100);

                mystack.Push(randgen);
                i++;
            }

           while (i > 0)
           {
               System.Console.WriteLine(mystack.Pop());
               i--;
           }

            System.Console.ReadKey();
        }
    }
}

And the push/pop code
Code:
      private const int maxsize = 10;
        private int top = 0;
        private int[] array = new int[maxsize];

        public void Push(int value)
        {
            array[top] = value;
            top++;
        }

        public int Pop()
        {
            top--;
            return array[top];
        }
 

Slavik81

Member
Random is a pseudorandom number generator, and the default constructor uses the current time as its seed. That loop executes so quickly that the system clock reports the same time when each of those Random instances is created. Thus they are all created with the same seed. Thus, the sequence of values returned by each instance of Random is identical. You are using the first value of some random number sequence ten times.

Create just one instance of Random. You can call Next on it repeatedly to get multiple values out of the random sequence.
 

smiggyRT

Member
Random is a pseudorandom number generator, and the default constructor uses the current time as its seed. That loop executes so quickly that the system clock reports the same time when each of those Random instances is created. Thus they are all created with the same seed. Thus, the sequence of values returned by each instance of Random is identical. You are using the first value of some random number sequence ten times.

Create just one instance of Random. You can call Next on it repeatedly to get multiple values out of the random sequence.

Ah that did the trick, had no idea current time was used as its seed. Thanks for that.
 

Kinitari

Black Canada Mafia
Most languages do, IIRC.

Well, that's good to know so I can keep an eye out for that.

Zoe - you're really good with c# if I remember correct, currently working out my problems with my database, and it's a fun process - but I realize my knowledge in oleDB is lacking. I hate using MSDN as a learning tool, so I was wondering if you know of any good online literature that I could read today, that'd make me more comfortable with it?
 
As an FYI about Random, it's not thread-safe. If you are going to have multiple threads running and you have a shared Random, you're going to want to synchronize access to it. Otherwise, let each thread have its own instance.
 

usea

Member
As an FYI about Random, it's not thread-safe. If you are going to have multiple threads running and you have a shared Random, you're going to want to synchronize access to it. Otherwise, let each thread have its own instance.
I didn't know that, thanks. I'm usually very careful about considering concurrent access in a class since I mostly write back end code in a concurrent environment. But I certainly wouldn't have expected Random to behave that way.
 
I'm a bit confused on how Interfaces differ from classes in Java. Why the need? Any good resources that detail this. As far as I can see an Interface just renames a class... or something...

Simply put, an interface tells other pieces of your code what your class is capable of doing. Other pieces of code can now know about parts of your class without knowing about the class itself.

For a convoluted example because I'm terrible at examples, say you have some stupid drawing application where you have different types of shapes. All shapes in the application are stored in one giant array. Say you want to calculate the area of all the shapes. The problem is that some of the primitives may not necessarily have an area:

Not a bad example, it's the one that most introductory textbooks use, but the problem I usually have with the Shape / Fruit Interface examples is that they don't really do a good job of showing why or when you'd need to use it. I can completely understand the confusion a beginner would take from those examples, abstracting everything out to Interfaces when it's really unnecessary.

The power of Interfaces comes with the decoupling of the intention of a class from it's implementation. This provides you with a lot of flexibility if you ever need to make changes to the implementation or write a new implementation altogether. Very few changes outside of the new implementation and dependency injection code need to be made.

When you start to reach more complex design patterns, such as MVC, it's much easier to understand when and where you'd use them.
 

Anduril

Member
Hey guys,

I'm a total programming noob, trying to learn Java. Currently I'm using Java for Dummies, cause it's been the most idiot and noob-proof from the books I've tried, but I've come across an exercise that doesn't compile even with the downloaded source from the books homepage. I have no idea why and was wondering if anyone of you might lend a hand.

It's the chapter about reading the contents of files, with two classes and an outside file.

Employee.java:

Code:
import static java.lang.System.out;

public class Employee {
    private String name;
    private String jobTitle;

    public void setName(String nameIn) {
        name = nameIn;
    }

    public String getName() {
        return name;
    }

    public void setJobTitle(String jobTitleIn) {
        jobTitle = jobTitleIn;
    }

    public String getJobTitle() {
        return jobTitle;
    }

    public void cutCheck(double amountPaid) {
        out.printf("Pay to the order of %s ", name);
        out.printf("(%s) ***$", jobTitle);
        out.printf("%,.2f\n", amountPaid);
    }
}

DoPayroll.java:

Code:
import java.util.Scanner;
import java.io.File;
import java.io.IOException;

class DoPayroll {

    public static void main(String args[])
                                  throws IOException {
        Scanner diskScanner =
            new Scanner(new File("EmployeeInfo.txt"));

        for (int empNum = 1; empNum <= 3; empNum++) {
            payOneEmployee(diskScanner);
        }
    }

    static void payOneEmployee(Scanner aScanner) {
        Employee anEmployee = new Employee();

        anEmployee.setName(aScanner.nextLine());
        anEmployee.setJobTitle(aScanner.nextLine());
        anEmployee.cutCheck(aScanner.nextDouble());
        aScanner.nextLine();
    }
}

And the outside file, EmployeeInfo.txt:

Code:
Barry Burd
CEO
5000.00
Harriet Ritter
Captain
7000.00
Your Name Here
Honorary Exec of the Day
10000.00
As I try to run it, I get the following error in Eclipse:

Code:
Exception in thread "main" java.util.InputMismatchException
	at java.util.Scanner.throwFor(Unknown Source)
	at java.util.Scanner.next(Unknown Source)
	at java.util.Scanner.nextDouble(Unknown Source)
	at DoPayroll.payOneEmployee(DoPayroll.java:22)
	at DoPayroll.main(DoPayroll.java:13)

I researched what the error is (different data type acquired than specified), but I just cant figure out why it doesnt work. It's the copy-pasted example from the downloaded source, goddarnit! :)
 
You can more easily figure where you should start by using the error information (which includes a stack trace) to find out exactly where in the code it happened.

Code:
Exception in thread "main" java.util.InputMismatchException
	at java.util.Scanner.throwFor(Unknown Source)
	at java.util.Scanner.next(Unknown Source)
	at java.util.Scanner.nextDouble(Unknown Source)
	at DoPayroll.payOneEmployee(DoPayroll.java:22) <-- this
	at DoPayroll.main(DoPayroll.java:13)           <--- and this

So in this, you can pinpoint that, in your code, the last place it was before everything went wrong is at line 22, in DoPayroll.java . And then, using the fact that it was an "InputMismatchException", you can figure that the Scanner expected the next input it has to be a double, but it turned out to not be.

I'm going to make a guess as to what caused the error, going off the documentation I read for Scanner.

When you do the call
Code:
anEmployee.cutCheck(aScanner.nextDouble());
at first, the next call
Code:
aScanner.nextLine();
skips "whitespace" as its default behavior (which includes newline characters), reads the current input until the next newline ( which will end up being "Harriet Ritter"), and throws it away somewhere.

So in the next call, the input looks like this:
Code:
Captain
7000.00
Your Name Here
Honorary Exec of the Day
10000.00
and the next time you use nextDouble, it's trying to parse "Your" as a double, causing the error.
 

usea

Member
Hey guys,

I'm a total programming noob, trying to learn Java. Currently I'm using Java for Dummies, cause it's been the most idiot and noob-proof from the books I've tried, but I've come across an exercise that doesn't compile even with the downloaded source from the books homepage. I have no idea why and was wondering if anyone of you might lend a hand.

It's the chapter about reading the contents of files, with two classes and an outside file.

[...]

As I try to run it, I get the following error in Eclipse:

Code:
Exception in thread "main" java.util.InputMismatchException
	at java.util.Scanner.throwFor(Unknown Source)
	at java.util.Scanner.next(Unknown Source)
	at java.util.Scanner.nextDouble(Unknown Source)
	at DoPayroll.payOneEmployee(DoPayroll.java:22)
	at DoPayroll.main(DoPayroll.java:13)

I researched what the error is (different data type acquired than specified), but I just cant figure out why it doesnt work. It's the copy-pasted example from the downloaded source, goddarnit! :)
You got a runtime exception. That means the code compiled just fine, but it crashed when you ran it. That's very different from a compiler error. I'm not trying to nitpick, just trying to let you know that those are different.
 

Bruiserk

Member
This is not a programming question, but I'm assuming one of you has to be able to answer this. For the "Product of Sums" part, why is ~B + ~C not an essential prime implicant? Can't it only be covered by the 2x2? The 0 I am looking at which makes it essential is the top-right in the 2x2 square.

qhpXS.png
 
Top Bottom