• 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

Water

Member
If you use a halfway decent IDE spotting syntax errors is even easier, too, as they'll have some manner of big red marker to point them out. :p

I doubt they'll have an IDE at the exam.
Come to think of it - if he's currently using something with syntax highlighting and on-the-fly error detection, turning those off for a while might actually be a good idea.
 

Water

Member
No. It's one of the many ways in which the way we teach things differs vastly from the way we use them in the real world. :p
I sincerely doubt the errors in the test will be mis-spelled variable names or unbalanced parenthesis - that would be completely retarded. Probably more like typical semantic errors that you won't notice unless you have a passable grasp of syntax, not necessarily something the compiler complains about. C and C++ in particular have a lot of stuff that can go wrong silently.

Plus, even if the compiler would complain about something, getting a small snippet of code in an exam and being told there's something wrong with it is not that different. It's not a test of whether the student has a permanently active bug-dar, it's a test of whether the student understands what the code is doing. (Though it might be fun if some exercise also gave you compiler warnings and messages along with harder bugs - and some non-bugs the student is supposed to deal with by squelching the warning!)
 

iapetus

Scary Euro Man
I sincerely doubt the errors in the test will be mis-spelled variable names or unbalanced parenthesis - that would be completely retarded.

I've seen both those examples in professional training exercises.

I've also seen (my personal favourite) an exercise in a training course from a large vendor where you have to spot the mistakes in a piece of code. However, the actual mistake was that they printed the corrected piece of code from the solutions page in place of the bug-riddled version. Confused the hell out of the course attendees.

Probably more like typical semantic errors that you won't notice unless you have a passable grasp of syntax, not necessarily something the compiler complains about. C and C++ in particular have a lot of stuff that can go wrong silently.

if (a = b)...

That said, these days that sort of thing tends to at least give you warnings. You might argue that if the syntax is correct, it's not a syntax error, of course. ;)

Plus, even if the compiler would complain about something, getting a small snippet of code in an exam and being told there's something wrong with it is not that different. It's not a test of whether the student has a permanently active bug-dar, it's a test of whether the student understands what the code is doing.

That's a more interesting question, but I'd expect it to be done through code that's syntactically correct but logically flawed.

(Though it might be fun if some exercise also gave you compiler warnings and messages along with harder bugs - and some non-bugs the student is supposed to deal with by squelching the warning!)

Because that would be the equivalent of a real-world problem.
 
I was wondering if there was a clever way to set the setw() function for displaying the header and data so that it was based on the size of the strings.

It is probably better to analyse sample input data to determine the optimal widths and set them statically. You absolutely can do this on the fly so that column widths are set for maximum prettiness for a given data set, but this can make it harder to write programs to eat your output. That said if that is a goal you may be better off to not truncate anything and use a delimited text output: delimited text for machines, pretty text for people.
 

Water

Member
I've also seen (my personal favourite) an exercise in a training course from a large vendor where you have to spot the mistakes in a piece of code. However, the actual mistake was that they printed the corrected piece of code from the solutions page in place of the bug-riddled version. Confused the hell out of the course attendees.
I remember reading a blog post on some guy's interview process where, after asking a candidate to code something, he asks the candidate to find the bug. And he likes asking the "find the bug" question the most when there's no bug. First he sees if the candidate has too much ego to actually check the code. Then he sees if the candidate has the competence and guts to assert that there is no bug. If they get to that point, he will then try to argue something specific in the code is a bug, and sees whether the candidate can stick to their position, be diplomatic, and counter his bullshit with actual arguments instead of being a yes-man or becoming insufferable. I thought this was a fantastic idea.
if (a = b)...

That said, these days that sort of thing tends to at least give you warnings. You might argue that if the syntax is correct, it's not a syntax error, of course. ;)
Warning or no, that one is a classic. ;) But I was thinking more about stuff like operator precedence, benign-looking things like ++ slipped into a statement where they trigger undefined behavior, "int* foo, bar", and especially getting the &'s and *'s right when messing with raw pointers.
 
anyone familiar with locale for java?


using log4j for logging, and even if changing the locale, something like 'Stü' is stored as 'St?'

definitely doing something wrong here...
 

usea

Member
I remember reading a blog post on some guy's interview process where, after asking a candidate to code something, he asks the candidate to find the bug. And he likes asking the "find the bug" question the most when there's no bug. First he sees if the candidate has too much ego to actually check the code. Then he sees if the candidate has the competence and guts to assert that there is no bug. If they get to that point, he will then try to argue something specific in the code is a bug, and sees whether the candidate can stick to their position, be diplomatic, and counter his bullshit with actual arguments instead of being a yes-man or becoming insufferable. I thought this was a fantastic idea.
I got this at an interview about a month ago. After I wrote some code on the white board and went over it, he said he saw a bug. I went over each line aloud to make sure. In the end I said there were no errors. He was like "lol jk just wanted to see what you'd say"
 

iapetus

Scary Euro Man
I remember reading a blog post on some guy's interview process where, after asking a candidate to code something, he asks the candidate to find the bug. And he likes asking the "find the bug" question the most when there's no bug. First he sees if the candidate has too much ego to actually check the code. Then he sees if the candidate has the competence and guts to assert that there is no bug. If they get to that point, he will then try to argue something specific in the code is a bug, and sees whether the candidate can stick to their position, be diplomatic, and counter his bullshit with actual arguments instead of being a yes-man or becoming insufferable. I thought this was a fantastic idea.

I've seen that technique used entirely by accident. ;)
 

Water

Member
I got this at an interview about a month ago. After I wrote some code on the white board and went over it, he said he saw a bug. I went over each line aloud to make sure. In the end I said there were no errors. He was like "lol jk just wanted to see what you'd say"
He still missed the last step where he'd try to argue something you wrote was a bug. That said, it's hard to prepare an argument ahead of time when you don't know exactly how an applicant will solve a problem, and also hard to make up one on the spot that is subtle enough to not be obvious. Gonna take a good interviewer to really pull that off.
 

Kansoku

Member
Silly Java question. There is a way to pick a number form the middle of a string? Like, I have a string in the format "A=*;", where * is the number. The number can range from 0 to 15.

Do I have to use substrings to remove the front part or is there a way to go directly to that number?
 

tokkun

Member
I remember reading a blog post on some guy's interview process where, after asking a candidate to code something, he asks the candidate to find the bug. And he likes asking the "find the bug" question the most when there's no bug. First he sees if the candidate has too much ego to actually check the code. Then he sees if the candidate has the competence and guts to assert that there is no bug. If they get to that point, he will then try to argue something specific in the code is a bug, and sees whether the candidate can stick to their position, be diplomatic, and counter his bullshit with actual arguments instead of being a yes-man or becoming insufferable. I thought this was a fantastic idea.

I think the principle is fine, but it seems like an approach that will evoke stress or anxiety in the interviewee. Unless the interview is for a high stress job, this will likely reduce the reliability of your interview process. It's like intentionally dirtying your test tubes before performing an experiment.
 
Silly Java question. There is a way to pick a number form the middle of a string? Like, I have a string in the format "A=*;", where * is the number. The number can range from 0 to 15.

Do I have to use substrings to remove the front part or is there a way to go directly to that number?

You can just split the string from = (and then use parseInt if you want it as an integer)

http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
 
Silly Java question. There is a way to pick a number form the middle of a string? Like, I have a string in the format "A=*;", where * is the number. The number can range from 0 to 15.

Do I have to use substrings to remove the front part or is there a way to go directly to that number?

String.substring(start,end) ?

String string = "A=*;";
String star = string.substring(2,3);
 
I remember reading a blog post on some guy's interview process where, after asking a candidate to code something, he asks the candidate to find the bug. And he likes asking the "find the bug" question the most when there's no bug. First he sees if the candidate has too much ego to actually check the code. Then he sees if the candidate has the competence and guts to assert that there is no bug. If they get to that point, he will then try to argue something specific in the code is a bug, and sees whether the candidate can stick to their position, be diplomatic, and counter his bullshit with actual arguments instead of being a yes-man or becoming insufferable. I thought this was a fantastic idea.

as an undergrad student

this is absolutely terrifying me
 

upandaway

Member
Silly Java question. There is a way to pick a number form the middle of a string? Like, I have a string in the format "A=*;", where * is the number. The number can range from 0 to 15.

Do I have to use substrings to remove the front part or is there a way to go directly to that number?
If 'A' is always a single character then yeah just use indexes, String has charAt(i). If A can be a variable length... huh...

Iterate over the string and cast each char to int to poll the ASCII value...? Or call parseInt on every char and ignore the exception if it's not a number? Both of them sound terrible :lol
 

Water

Member
I think the principle is fine, but it seems like an approach that will evoke stress or anxiety in the interviewee. Unless the interview is for a high stress job, this will likely reduce the reliability of your interview process. It's like intentionally dirtying your test tubes before performing an experiment.

Not a problem you do this towards the end of the interview.

I think the social skills and character traits which that procedure attempts to test are important for pretty much any programming job that involves teamwork at all. You can't let others walk over you on technical issues when they are wrong (even your boss), you have to be able to resolve disagreement sensibly, not take things personally, etc. This isn't limited to high stress jobs.

It's a good question how much false negatives this procedure itself will have, such that an interviewee is unable to show those social skills and character traits specifically in the interview situation, but would possess them in the actual work environment. My gut feeling is that risk of false negatives would be small for experienced programmers, and much higher for people with no experience. If so, a negative result should be treated differently depending on the interviewee.
 
If 'A' is always a single character then yeah just use indexes, String has charAt(i). If A can be a variable length... huh...

Iterate over the string and cast each char to int to poll the ASCII value...? Or call parseInt on every char and ignore the exception if it's not a number? Both of them sound terrible :lol

If the "A part" is going to be a variable length you can find the = and go from there
 

Magni

Member
Does anyone have any experience with SQLite and WP8? I'm tearing my hair out trying to make something that should be super simple work.

I want to have a Users table be created if it doesn't exist yet on app launch. On navigating to the "entry" page, I want it to search for the first user in the table. If there is one, log in as that user and navigate to the main page, otherwise, not do anything. When logging in manually, save that user to the table. When logging out, delete all entries (there should only be one anyways) from the table.

For some reason, the table that is created in App.xaml.cs doesn't exist anywhere after that.

App.xaml.cs
Code:
// Get a reference to the SQLite database
var dbPath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "db.sqlite");
// Initialize the database if necessary
using (var db = new SQLite.SQLiteConnection(dbPath))
{
    // Create the table if they don’t exist
    db.CreateTable<User>();
}

Enter.xaml.cs
Code:
var dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.sqlite");
using (var db = new SQLiteConnection(dbPath))
{
    var existing = db.Query<User>("select * from User").First();
    if (existing != null)
    {
        ApiClient.loggedInUser = existing;
        NavigationService.Navigate(new Uri("/Pages/Feeds.xaml", UriKind.Relative));
    }
}

For some reason, nothing is happening here.

ApiClient.cs
Code:
loggedInUser = JsonConvert.DeserializeObject<User>(apiResponseString);

var dbPath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "db.sqlite");
using (var db = new SQLiteConnection(dbPath))
{
    db.RunInTransaction(() => { db.Insert(loggedInUser); });
}

And nothing is happening here either.

Any pointers?
 

Zoe

Member
Anybody have to work with/integrate Progress DB's into their .NET apps or SQL Server? Cheers or jeers?

Seems hard to find information on it.
 

hateradio

The Most Dangerous Yes Man
Silly Java question. There is a way to pick a number form the middle of a string? Like, I have a string in the format "A=*;", where * is the number. The number can range from 0 to 15.

Do I have to use substrings to remove the front part or is there a way to go directly to that number?
I don't think anyone mentioned Regular Expressions, but that's also an option.

Code:
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PatternMatcher
{
    public static void main(String[] args)
    {
        System.out.println(matcher("A=15;")); // 15
        System.out.println(matcher("A=1;"));  // 1
    }

    public static Integer matcher(String match)
    {
        Pattern pattern = Pattern.compile("A=(\\d+);"); // find digits in this pattern
        Matcher matcher = pattern.matcher(match); // match against this string
        Integer digit = null;
        if (matcher.find()) {
            digit = Integer.valueOf(matcher.group(1)); // the first match in parentheses
        }
        return digit;
    }
}
 

Seanbob11

Member
Hey guys,

I'm making an app on Android. Basically when someone presses a button it turns something on. When they press it again it turns off. I'm using a boolean to determine what state the device is at. It goes something like this.

Code:
public void onClickPower(View v) throws IOException {

        if (!ispoweron) {
                ispoweron = true;
                //Do stuff
       }
        if (ispoweron) {
                ispoweron = false;
                //Do stuff
       }

I know the problem is that the boolean changes state and runs through both if statements. I originally thought of using breaks to break out of the method but I now know that isn't allowed. I can't use a switch either I believe because it doesn't work with booleans.

I'm sure there's something simple to fix this but I'm hitting a brick wall. Thanks guys.
 

Kalnos

Banned
Hey guys,

I'm making an app on Android. Basically when someone presses a button it turns something on. When they press it again it turns off. I'm using a boolean to determine what state the device is at. It goes something like this.

Code:
public void onClickPower(View v) throws IOException {

        if (!ispoweron) {
                ispoweron = true;
                //Do stuff
       }
        if (ispoweron) {
                ispoweron = false;
                //Do stuff
       }

I know the problem is that the boolean changes state and runs through both if statements. I originally thought of using breaks to break out of the method but I now know that isn't allowed. I can't use a switch either I believe because it doesn't work with booleans.

I'm sure there's something simple to fix this but I'm hitting a brick wall. Thanks guys.

Make the second an 'else if' statement. If you can't do that then just put something like:

ispoweron = !ispoweron;

at the end of the method after both ifs (and remove the 'ispoweron = true/false' parts)
 
Thanks for this, because none of the game tutorials I've read (including a book) have touched on this.

Could you give an example of how this happens? How would I plug the code of the rules into the game logic temporarily?

Also, are we talking make an abstract class for Rules, and then make a specific class for each rule, and then having a line in the text file that tells the game to create an object for that specific class? I feel like since rules can get pretty specific, wouldn't this just lead to a bunch of rule objects, and if so is that okay?

I just can't wrap my head around how you could have could have conditions in a text file that are executed by the program. Should I just use something like Rhino or Beanshell? Though I'm not exactly sure how, it seems like maybe an external scripting language could solve this problem.

Also, what do you mean here?

Okay I get it now. Most game tutorials I've seen just put conditions and game logic for the game directly in the code, so encapsulating that into a Rule is kind of foreign to me, but I get it now.

I'm guessing that I basically do the same thing for Triggers/Game Events , right? Abstract class and then specific Trigger classes that do stuff? Or maybe by Rule you essentially mean Trigger/Game Event (not sure)..

For learning purposes, hard coding your rules isn't the worst thing initially if that's what it takes you to get things functional. Once you have things functional you can start thinking of ways to improve, otherwise you might get stuck trying to extrapolate too far out and never write code (happens to me).

In terms of real world stuff, the biggest thing to think about is "what is your data?".

Imagine you're making something like Super Mario, your data is:

1. Platform locations
2. Platform types
3. Enemy Spawn locations
4. Enemy types
5. Enemy point values
6. Power up locations
7. Check point locations
8. End point location

(among other things)

You can now start grouping these properties into objects, (ie an enemy has a position, a point value, a path type, a sprite etc). Then you can think of a way to encapsulate all these objects (maybe its an xml file, maybe is some kind of script) and your game knows how to load this "level" up, load up the objects inside of it when needed and keep track of their behaviors for their life time.

Sorry this might be a bit abstract or rambly. The basic point is that admittedly a lot of game programming tutorials are very bad at teaching you how to structure an engine but I think that's somewhat by design. They're about teaching you to solve some of the problems in creating an aspect of the game, and usually do so in the most direct (if ugly) way possible. As you gain more experience you'll better understand how to build cleaner, more reusable code.

How do you guys feel about comments? Can there be too much?

If there's a particularly messy line I can see myself adding like 3 lines of comments for it (say 15 words per line). Sure I try to write clear code but sometimes I hit a wall. I'm also not that smart so maybe just having a full explanation in English is better. But I don't know if this is okay to do.

I absolutely believe there can be too much. If your comment is either too long its emblematic of a lot of possible issues. I largely reserve comments for things that had to be done a specific way to solve some specific issue.

i.e.:

// This random special case is to prevent the game from crashing when the player picks the following heroes on () on level 35.

Also:

// You have to initialize X before Y otherwise it creates a race case. Maybe we should refactor this later?

Or:

// Yes this is ugly but Apple's stupid compiler doesn't follow normal logic

And sometimes:

// TODO: FUCK! FIX THIS AT SOME POINT WHEN ITS NOT FUCKING 4 AM AND I HAVE HAD ACTUAL SLEEP. THE PROBLEM IS PROBABLY RELATED TO blah blah blah BUT IVE HAD 2 HOURS OF SLEEP AND I CANT THINK STRAIGHT.

I try to make my code and comments useful to whatever poor soul will likely have to build on top of the project at some later date because I hate when I take over for someone else and spend my time trying to make heads or tales of their nonsensical code.

I also generally believe that most functions should fit lengthwise on a monitor because if I have to keep scrolling to the top or bottom I'll probably forget something.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
I have a Java question related to an assignment I am working.

Part of my task involves getting information out of an object that is stored inside and array of objects. This happens to multiple objects in the array and is initiated by a button.

The objects each have 4 data fields; three Strings and a double.

Say I need to pull out the information from one of the Strings in each of the objects. What process is used to accomplish this?
 

Kalnos

Banned
I have a Java question related to an assignment I am working.

Part of my task involves getting information out of an object that is stored inside and array of objects. This happens to multiple objects in the array and is initiated by a button.

The objects each have 4 data fields; three Strings and a double.

Say I need to pull out the information from one of the Strings in each of the objects. What process is used to accomplish this?

Something like this?

Code:
for (int i = 0; i < objectArray.length; i++)
{
     System.out.println(objectArray[i].yourfieldname/getter);  
}

The field (string) would need to be accessible (public/getter).
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
Something like this?

Code:
for (int i = 0; i < objectArray.length; i++)
{
     System.out.println(objectArray[i][B].yourfieldname/getter[/B]);  
}

The field (string) would need to be accessible (public/getter).

I'm not familiar with this part, or just the way you wrote it, would you mind explaining it a little more? I have attempted to utilize a similar for loop with a getter inside to return the data I need, but I'm running into errors regarding accessing a non-static.

My objects classes are inheriting from an abstract class that sets up the variable that they modify and then assign to themselves, (assignment requires using the abstract class / inheritance), so I feel that is causing me issues.

My code spans over 5 classes, so that's why I didn't post it here, but if it would help in knowing what I'm talking about I can put it up online and paste a link.
 

Kalnos

Banned
Note: I may be slightly off on syntax since I have been using C# for the past few years but the ideas should be the same.

objectArray refers to the object at position 'i' in your array. What's happening in the code I wrote is the equivalent of doing this:

Code:
YourClass selectedObject = objectArray[i];  //Get object at position i
selectedObject.myMethod();  //call one of the methods / use one of the fields of the object

As for that error:
1. Are you sure that you instantiated the objects in this array with the new keyword? (e.g. Class Object = new Class();)
2. Are you using the static keyword anywhere you shouldn't be?
 

iapetus

Scary Euro Man
Make the second an 'else if' statement.

Why an 'else if' when you're checking the value of a boolean property? This just wants to be an else.

Code:
if (powerOn) {
  // Do stuff
  powerOn = false;
} else {
  // Do other stuff
  powerOn = true;
}
 

hateradio

The Most Dangerous Yes Man
I have an ASP.NET web forms question.

I have an image upload form. After the image is uploaded, there is some post-processing that can take a few minutes.

The post-processor class tracks its own progress, and I want to show that in the HTML. So far, these two things are not communicating with each other.

My plan is to update a session variable as the process continues. I'll create a WebMethod that will return the progress. I'll reach it by using sending AJAX requests, what I'll call "pinging." I've never used WebMethods, but I've seen that they can be used for such tasks.

However, I obviously can't do that once a person submits the page because the page reloads. :p

I would use preventDefault and send everything as an XHR, but I can't send the image from that request, because it has to work on older IE browsers.

Is an iframe my only option? That way I can send the form, but only the iframe will try to load.

At that point, I can try to hook onto that submission with JS, and begin "pinging" the WebMethod for updates.


If anyone knows of a less complex method, please say so. &#128549;
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
Alright, I am having a hell of a time with this information gathering, and I have hit a brick wall. Your help would be greatly appreciated, (not looking for the code to be fixed, just guidance on what I'm doing wrong so I can learn and fix it)

I posted up my source code on GitHub here https://github.com/Granadier/Assignment04

The gist of the program is a GUI that allows you to input student information. After submit is pressed the information is gathered from the texfields, a Student or GradStudent object is created, and then it is stored in it's respective array. The other four buttons are for pulling information back out of the objects. An abstract class is used to set up the datafields and methods for the Student and GradStudent classes because it is a requirement of the assignment.

What I'm running into though is when I try and access the information from the objects I'm getting NullPointerException's. It seems that the methods I'm using to pull the information aren't receiving anything and are staying as Null.

This seems like a pretty basic concept that will apply to a lot of different situations in the future, but I can't seem to grasp what I am doing wrong here.

Thank you in advance for any help.
 

Water

Member

Harpuia

Member
Maybe I just don't understand namespaces, but Idk what is the problem here:

Code:
//main

#include <iostream>
#include "node.h"
using namespace std;
using namespace MyNode;//node.h definitions

int main()
{
    cout << "a node will be created" << endl;
    node* head;

    if(head->getNext() == NULL) cout << "the pointer is pointing to absolutely nothing" << endl;
    cout << "data will be entered" << endl;
    head->setData(10);
    cout << "data has been entered" << endl;

    cout << head->getData() << endl;
    return 0;
}

Code:
//header 

#ifndef NODE_H
#define NODE_H

namespace MyNode
{
    //template<class T>
    class node
    {
    public:
        node();//imp
        ~node();//imp
        void setData(int inp);
        int getData();
        void setLink(node* new_next);
        node* getNext();
        bool isEmpty();//imp
        void insert_new_node(const int new_data);
    private:
        int content;
        node* next;

    };
}

#endif

Code:
//implementations

#include "node.h"
#include <iostream>
using namespace std;
namespace MyNode
{


    //template<class T>
    node::node()
    {
        cout << "I've entered the constructor!" << endl;
        next = NULL;
        cout << "I'm here!" << endl;
    }

    //template<class T>
    node::~node()
    {
        cout << "I've entered the destructor!" << endl;
        if(next != 0) delete next;
        cout << "Everything is deleted!" << endl;
    }

    //template<class T>
    bool node::isEmpty()
    {
        if( next == 0) return 1;//if we have a top that's simply a pointer to the first element, this should work
        else return 0;
    }

    //template<class T>
    void node::insert_new_node(const int new_data)
    {
        node* temp;
        temp = next;

        while(temp != 0) temp = temp->next;

        temp->next = new node;

        temp->content = new_data;
    }

    void node::setData(int inp)
    {
        content = inp;
    }

    int node::getData()
    {
        return content;
    }

    void node::setLink(node* new_next)
    {
        next = new_next;
    }

    node* node::getNext()
    {
        return next;
    }
}

The cout statements in my constructor/destructor were used to prove that for some reason, they seem to not be executing at all. What's the problem here? The placing of my namespace declaration? Did I simply miss a declaration?

EDIT: The random use of 0 and NULL were me getting confused as to where exactly NULL is defined in.

EDIT2: My program basically crashed as soon as I try to use the method setData() inexplicably.

EDIT 3(ELECTRIC BOOGALOO): Derp. Looks like I forgot to give my pointer a dynamically allocated node. To make this question not pointless, what exactly is happening if I try to access whatever the pointer is pointing to?
 

upandaway

Member
Alright, I am having a hell of a time with this information gathering, and I have hit a brick wall. Your help would be greatly appreciated, (not looking for the code to be fixed, just guidance on what I'm doing wrong so I can learn and fix it)

I posted up my source code on GitHub here https://github.com/Granadier/Assignment04

The gist of the program is a GUI that allows you to input student information. After submit is pressed the information is gathered from the texfields, a Student or GradStudent object is created, and then it is stored in it's respective array. The other four buttons are for pulling information back out of the objects. An abstract class is used to set up the datafields and methods for the Student and GradStudent classes because it is a requirement of the assignment.

What I'm running into though is when I try and access the information from the objects I'm getting NullPointerException's. It seems that the methods I'm using to pull the information aren't receiving anything and are staying as Null.

This seems like a pretty basic concept that will apply to a lot of different situations in the future, but I can't seem to grasp what I am doing wrong here.

Thank you in advance for any help.
What line is giving the exception? And did you try just copy-pasting from some JTextField tutorial that you confirmed works, to check what you're doing differently?
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
What line is giving the exception? And did you try just copy-pasting from some JTextField tutorial that you confirmed works, to check what you're doing differently?

The JTextFields I am certain are working. I am able to pull data from them and I am able to create objects using that data. The "Submit" button works for creating and storing those objects.

The parts I'm getting exceptions from are the other four buttons that I had to add for this assignment. These buttons need to access the information inside of the objects that are inside of the array, and then display that information onto the GUI. When they call their methods they throw the NullPointerException to the console.

Here's some bits of the code I believe is giving me errors.

JButton for calling method:
Code:
JButton jbtStuNms = new JButton(new AbstractAction("Student Names") {
            @Override
            public void actionPerformed(ActionEvent e) {
                // On button press, print only names of just stored students
                jtaOutput.append(manager.printStuNames());
            }
        });
That calls this method from the Manager class (middle man for the GUI logic):
Code:
public String printStuNames() {
        //TODO: Define a way to print only student names
        return stuObjects[stuCount].getNme();
    }

Now the getNme() method is a method defined in the abstract Person class that Student extends. That method in the Student class looks like this:
Code:
public String getNme() {
        // Filler to test methods
        return "Hello";
    }
 

Slavik81

Member
The cout statements in my constructor/destructor were used to prove that for some reason, they seem to not be executing at all. What's the problem here? The placing of my namespace declaration? Did I simply miss a declaration?
As you've discovered, node* does not create a node. It's just a pointer to a node, and until you give it a node to point to, it points at random garbage in memory.

EDIT: The random use of 0 and NULL were me getting confused as to where exactly NULL is defined in.
NULL is defined in stdlib.h. Library headers are allowed to include other library headers, though, so it's often defined regardless of whether you explicitly include that one.

EDIT2: My program basically crashed as soon as I try to use the method setData() inexplicably.

EDIT 3(ELECTRIC BOOGALOO): Derp. Looks like I forgot to give my pointer a dynamically allocated node. To make this question not pointless, what exactly is happening if I try to access whatever the pointer is pointing to?
Just as you saw, if you try to use an uninitialized pointer, you'll get weird results. The best case scenario is that you'll get a crash. The worst case scenario is that your program will continue chugging along, but be subtlely incorrect, or crash at some later point in time when it's less obvious what the real underlying cause was.
 

upandaway

Member
The JTextFields I am certain are working. I am able to pull data from them and I am able to create objects using that data. The "Submit" button works for creating and storing those objects.

The parts I'm getting exceptions from are the other four buttons that I had to add for this assignment. These buttons need to access the information inside of the objects that are inside of the array, and then display that information onto the GUI. When they call their methods they throw the NullPointerException to the console.

Here's some bits of the code I believe is giving me errors.

JButton for calling method:
Code:
JButton jbtStuNms = new JButton(new AbstractAction("Student Names") {
            @Override
            public void actionPerformed(ActionEvent e) {
                // On button press, print only names of just stored students
                jtaOutput.append(manager.printStuNames());
            }
        });
That calls this method from the Manager class (middle man for the GUI logic):
Code:
public String printStuNames() {
        //TODO: Define a way to print only student names
        return stuObjects[stuCount].getNme();
    }

Now the getNme() method is a method defined in the abstract Person class that Student extends. That method in the Student class looks like this:
Code:
public String getNme() {
        // Filler to test methods
        return "Hello";
    }
Wait.. don't you need to use stuCount-1 there? Maybe I'm missing something.

Try to change the method to this:
Code:
public String printStuNames() {
        //TODO: Define a way to print only student names
        System.out.println(stuObjects);
        return stuObjects[stuCount].getNme();
    }
And see in the console if the array is what you expect it to be.
 

Harpuia

Member
As you've discovered, node* does not create a node. It's just a pointer to a node, and until you give it a node to point to, it points at random garbage in memory.


NULL is defined in stdlib.h. Library headers are allowed to include other library headers, though, so it's often defined regardless of whether you explicitly include that one.


Just as you saw, if you try to use an uninitialized pointer, you'll get weird results. The best case scenario is that you'll get a crash. The worst case scenario is that your program will continue chugging along, but be subtlely incorrect, or crash at some later point in time when it's less obvious what the real underlying cause was.



Thanks! I fixed up my code, but I'm getting these errors:

undefined reference to node<int>::node()
undefined reference to node<int>::setData(int)
undefined reference to node<int>::getData()

and so on and so forth; for some reason, my class's functions are undefined.

Here's the code I have:

Code:
//main
#include <iostream>
#include "node.h"
using namespace std;
using namespace Mynode;//node.h definitions

int main()
{
    cout << "a node will be created" << endl;

    node<int> head;
    head.setData(10);

    //similarly, this doesn't work either:
    //node<int>* head = new node<int>;

    cout << head.getData() << endl;

    return 0;
}

Code:
//header

#ifndef NODE_H
#define NODE_H

namespace MyNode
{
    template<class T>
    class node
    {
    public:
        node();//imp
        ~node();//imp
        void setData(T inp);
        T getData();
        void setLink(node<T>* new_next);
        node<T>* getNext();
        bool isEmpty();//imp
        void insert_new_node(const T new_data);
    private:
        T content;
        node<T>* next;

    };
}

#endif

Code:
//implementations

#include "node.h"
#include <iostream>
using std::cout;
using std::endl;

namespace MyNode
{


    template<class T>
    node<T>::node()
    {
        cout << "I've entered the constructor!" << endl;
        next = NULL;
        cout << "I'm here!" << endl;
    }

    template<class T>
    node<T>::~node()
    {
        cout << "I've entered the destructor!" << endl;
        if(next != NULL) delete next;
        cout << "Everything is deleted!" << endl;
    }

    template<class T>
    bool node<T>::isEmpty()
    {
        if( next == NULL) return 1;//if we have a top that's simply a pointer to the first element, this should work
        else return 0;
    }

    template<class T>
    void node<T>::insert_new_node(const T new_data)
    {
        node<T>* temp;
        temp = next;

        while(temp->next != NULL) temp = temp->next;

        temp->next = new node<T>;

        temp->content = new_data;
    }

    template<class T>
    void node<T>::setData(T inp)
    {
        content = inp;
    }

    template<class T>
    T node<T>::getData()
    {
        return content;
    }

    template<class T>
    void node<T>::setLink(node<T>* new_next)
    {
        next = new_next;
    }

    template<class T>
    node<T>* node<T>::getNext()
    {
        return next;
    }
}

I must've cross referenced my textbook, and looked up online to see if somewhere along the way, I made a mistake. However, it does not seem to look like it. Any advice? Strangely enough, I tried this out with no templates but as a node for some int data, and it worked. soon as I tried to generalize it via templates, it seems to think that I've not defined my class's functions.
 

Slavik81

Member
Templates definitions must be available where they are used. You can't put them in the implementation file like with regular functions. They should go in the header.
 

Harpuia

Member
Templates definitions must be available where they are used. You can't put them in the implementation file like with regular functions. They should go in the header.

Ah, the one solution I overlooked! So I should nix the header file and just add it into my implementation file? Or the other way around?

I read that some compilers have issue with this; is there anyway to preserve abstraction? I mean, putting the declarations in the same file as their implementations sort of ruins the point.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
Wait.. don't you need to use stuCount-1 there? Maybe I'm missing something.

Try to change the method to this:
Code:
public String printStuNames() {
        //TODO: Define a way to print only student names
        System.out.println(stuObjects);
        return stuObjects[stuCount].getNme();
    }
And see in the console if the array is what you expect it to be.

Yep, this was my mistake. I was referencing an index that contained nothing because the count increased after creation in order to prepare for the next object.

Changed it to stuCount-1 like you suggested and it's all good now.
Now I just have to finish up the logic portion and I'll be finished.

I had a feeling this was going to end up being a silly mistake like that.

Thank you very much for the help!
 

Garcia

Member
Man, it feels sooo good to have those "Eureka!" moments once you overcome a problem and then translate it into an successful executable program.

This whole world is so exciting.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
Man, it feels sooo good to have those "Eureka!" moments once you overcome a problem and then translate it into an successful executable program.

This whole world is so exciting.

Yeah those are some of the best moments in my opinion.
 

Slavik81

Member
Ah, the one solution I overlooked! So I should nix the header file and just add it into my implementation file? Or the other way around?

I read that some compilers have issue with this; is there anyway to preserve abstraction? I mean, putting the declarations in the same file as their implementations sort of ruins the point.
It doesn't matter what you call the file you put them in. The only thing that matters is that file is #include'd wherever something wants to use a node<T>. I just call those files *.h, but some people like to call them *.hpp.

All compilers require the template definition to be visible where it's used. That's fundamentally part of the language. However, the biggest thing that putting them in separate files gets you is faster compilation speed and less frequent recompilation. It does not really affect the program itself.

glew symbols.

Hmm... All I can say is to double-check that the library is in your library path, and that you're specifying it to be linked into your application. Carefully reviewing the actual build commands being given to msvc / link or gcc / ld can help.

On Ubuntu or Fedora Linux, it's enough just to install glew and add '-lGLEW' to the gcc invocation. That might be all mingw needs, though it might not be (due to differences in where things get installed under Windows vs Linux).
 
Top Bottom