The "IT DOESN'T WORK!" thread

A place to discuss the implementation and style of computer programs.

Moderators: phlip, Moderators General, Prelates

User avatar
Rook
Posts: 179
Joined: Thu Nov 15, 2007 1:55 pm UTC
Location: The Madness Place

Re: The "IT DOESN'T WORK!" thread

Postby Rook » Tue Dec 04, 2007 10:21 pm UTC

I'm doing some Assembly programming with a PIC16F876 on a small buggy, and I've having a general (yet highly annoying and ambiguous) problem making it work.

Basically, there are two IR sensors on the front, made for obstacle detection. The idea of my program is that the buggy should 'roam'; essentially, go forwards unless a wall is encountered, and when one is, back up, turn away from it and go straight again. The problem I'm having is that when I run the code on the buggy, it seems to get stuck in one of the movement loops. If I set it going with neither sensor covered, the wheels just run straight. If I cover one of the sensors, then start it, they run backwards... ad infinitum.

The loop in question (where I think it's getting stuck; I can't step test because there are some damn big delays in there for mechanical reasons) looks like this:

Code: Select all

fwd   movlw   H'006C'      ;just one of the step codes
   movwf   PORTC      ;two 200 step stepper motors on the upper and lower 4 bits of PORTC
   call   sdelay      ;mechanical delay to let the motors turn
****************************
The above section is basically repeated here for the other 3 step codes
****************************
   decfsz   COUNT,f      ;COUNT = 6; the loop should exit after 24 steps
   goto   fwd
   movlw   H'0006'
   movwf   COUNT
   goto   checkL      ;checkL is the Left sensor

The mechanical delay lasts for FF*A cycles, so I can't step through it, and I don't know if you can skip sections in MPLAB. I can probably use breaks to get near the end, then single step up to the problem point, but I don't have access to the lab right now.

I anyone with any knowledge of Assembly language can see any glaring mistakes in that, or anything obvious/newbish (I've only been doing this 8 weeks), please point it out. I'll have to fix it myself anyway, I just thought I'd ask, since it's driving me nuts that as far as I can see, it should work, but doesn't.
You scratch my lion, and I'll scratch yours.

mattmacf wrote:Action precedes motivation.

This is very, very important.

User avatar
Cass
Posts: 28
Joined: Thu Oct 04, 2007 3:04 am UTC
Location: BC, Canada

Re: The "IT DOESN'T WORK!" thread

Postby Cass » Wed Dec 05, 2007 2:37 am UTC

Do you know if you have the watch dog timer set on or off? Without seeing the rest of the code I cant say for sure that there is not anything wrong at all but it doesn't have any glaring mistakes. And at the end of what you are calling did you remember to add?

Code: Select all

 retlw     0x00
"I reject your reality and substitute it with my own"

spelunker
Posts: 102
Joined: Wed Dec 05, 2007 7:07 am UTC

Re: The "IT DOESN'T WORK!" thread

Postby spelunker » Wed Dec 05, 2007 7:29 am UTC

Hey everyone!

I saw this thread and I felt the urge to contribute, so here we go:

My first foray into PHP was a few weeks ago, and one early morning I was pulling my hair out over an issue because some XML output for a function was working great, but the database I was using wasn't showing any of the updates I needed.

I couldn't understand it. I tried hardcoding some constants, and they worked, but as soon as I put the variables back in the whole thing broke again. I was near the end of my rope when I suddenly realized something:

Code: Select all

// now update the info
$matchInfo = $unmatchedMen[$outer]->match_info;

$unmatchedMen[ $id ]->match_info = $unmatchedMen[ $outer ]->student_id;
mssql_query( "UPDATE applications SET match_info = '$id' WHERE studentid = '$matchInfo'");


$unmatchedMen[ $outer ]->match_info = $unmatchedMen[ $id ]->student_id;
mssql_query( "UPDATE applications SET match_info = '$matchInfo' WHERE studentid = '$id'");

break;


I was querying the database with an unset variable :-\. I could not believe I had them in the wrong order the whole time and that it took me hours to figure out.

I'm not usually that bad, I swear.

Oh, and that first line is there because at one point I thought PHP might be having problems evaluating that statement while in the query strings or something.

There was another time when I was attempting to use foreach() to modify objects in an array, which was driving me nuts because nothing was changing. Turned out in PHP4 foreach() passed by value, by reference, which made it utterly useless for me. That one took a while to figure out.

PHP seems pretty cool/useful, though.

User avatar
Rook
Posts: 179
Joined: Thu Nov 15, 2007 1:55 pm UTC
Location: The Madness Place

Re: The "IT DOESN'T WORK!" thread

Postby Rook » Wed Dec 05, 2007 1:21 pm UTC

Cass wrote:Do you know if you have the watch dog timer set on or off? Without seeing the rest of the code I cant say for sure that there is not anything wrong at all but it doesn't have any glaring mistakes. And at the end of what you are calling did you remember to add?

Code: Select all

 retlw     0x00

Well, I have it working to a slightly higher degree; the main problem was a bunch of buggered up gotos with the wrong labels, meaning I jumped to a counter reset or a call for a function I just left, which put me in an infintie loop :oops:

However, it still only works if I run it breakwise; that is, if I put a break in so that the buggy only moves one step forwards at a time, or backs away, per button press. If I try to run the code continously, it simlpy doesn't detect the wall and tries to keep going.

I'm not really asking for help on this one; it's something simple like check frequency, it'll just take me a while to figure out. Just thought I'd let you know.
You scratch my lion, and I'll scratch yours.

mattmacf wrote:Action precedes motivation.

This is very, very important.

bannahammock
Posts: 28
Joined: Wed Dec 05, 2007 1:24 pm UTC

Re: The "IT DOESN'T WORK!" thread

Postby bannahammock » Wed Dec 05, 2007 1:58 pm UTC

could some one help me with a code im writing for class.. its spose to have ask i fu want a stock report.. ... type in bussines.. give basic reply (using random genrated numbers, then switching numbers to txt.
ask if u want fortune (same thing )
and ask if u want to have another fourtune /stock and then end if the user doesn't want

if i post it could some one help me
i cant get the damn thing to close lol

User avatar
Hammer
Because all of you look like nails.
Posts: 5491
Joined: Thu May 03, 2007 7:32 pm UTC
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby Hammer » Wed Dec 05, 2007 2:06 pm UTC

bannahammock wrote:could some one help me with a code im writing for class

It would help if you specified what programming language this program is meant to be in.

Honestly, it would also help if you made some attempt to state your requirements in sentences that had some correctly spelled words and some punctuation and stuff so we could figure out what you are asking for.

Please also post in the INTRO thread and read the Rules threads.
"What's wrong with you mathematicians? Cake is never a problem."

User avatar
Cass
Posts: 28
Joined: Thu Oct 04, 2007 3:04 am UTC
Location: BC, Canada

Re: The "IT DOESN'T WORK!" thread

Postby Cass » Wed Dec 05, 2007 11:50 pm UTC

Rook wrote:
Cass wrote:Do you know if you have the watch dog timer set on or off? Without seeing the rest of the code I cant say for sure that there is not anything wrong at all but it doesn't have any glaring mistakes. And at the end of what you are calling did you remember to add?

Code: Select all

 retlw     0x00

Well, I have it working to a slightly higher degree; the main problem was a bunch of buggered up gotos with the wrong labels, meaning I jumped to a counter reset or a call for a function I just left, which put me in an infintie loop :oops:

However, it still only works if I run it breakwise; that is, if I put a break in so that the buggy only moves one step forwards at a time, or backs away, per button press. If I try to run the code continously, it simlpy doesn't detect the wall and tries to keep going.

I'm not really asking for help on this one; it's something simple like check frequency, it'll just take me a while to figure out. Just thought I'd let you know.


Would you be able to test the input pin in the middle of your forward part, the 2uS delay from the added instructions should not be to noticeable while running, I have not played around with motors for a while. Thank you for getting me interested in them again.
"I reject your reality and substitute it with my own"

User avatar
'; DROP DATABASE;--
Posts: 3284
Joined: Thu Nov 22, 2007 9:38 am UTC
Location: Midwest Alberta, where it's STILL snowy
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby '; DROP DATABASE;-- » Thu Dec 06, 2007 1:11 am UTC

spelunker wrote:My first foray into PHP was a few weeks ago, and one early morning I was pulling my hair out over an issue because some XML output for a function was working great, but the database I was using wasn't showing any of the updates I needed.

I couldn't understand it. I tried hardcoding some constants, and they worked, but as soon as I put the variables back in the whole thing broke again. I was near the end of my rope when I suddenly realized something:
[...]
I was querying the database with an unset variable :-\. I could not believe I had them in the wrong order the whole time and that it took me hours to figure out.
That reminds me of a script I wrote that was pulling info from a database. It kept reporting there were no rows in the table. I added a number of checks and debug outputs before I realized I had neglected to ever put any rows in the table. :oops:
poxic wrote:You suck. And simultaneously rock. I think you've invented a new state of being.

User avatar
headprogrammingczar
Posts: 3072
Joined: Mon Oct 22, 2007 5:28 pm UTC
Location: Beaming you up

Re: The "IT DOESN'T WORK!" thread

Postby headprogrammingczar » Fri Dec 14, 2007 1:07 am UTC

Here is some fun code I am working on for my IB Dossier. We are required to have a file I/O system, GUI, and an abstract data structure, all in Java. I'm already light-years ahead of the class, so I decide to integrate my IO system with my data structure (custom container classes that facilitate nested arrays, linked lists, and any other sort of sinister magic). My IO system outputs data in the format of getClass().getName() "toString()"delimiter. Reading in, I first create objects of every type that I predict to be in the array. These are not used by the program in the traditional sense, but tracing back the constructors to the common superClass, they add themselves to a hash table inside my IO classes, so the reader can find that object's parse(String) method. My Entire DataReader class is static, but is constructed to work like a global object.
And that's just the introduction to the problem.
Whenever I tried to add support for unfound datatypes, I would end up getting strange compiler errors that traced back to the line "class MyString extends MyDatatype{" with the error (paraphrased) "a problem occured <init>". After a month of searching though about 200 lines of hardcore über-dense code, I managed to trace the error back to a 0 that should have been a 1, a 1 that should have been a 0, and a 0 that should have been a -1. Each of these methods had 3 degrees of separation from each other.
I wish I could post code, but then IBO could accuse me of cheating. :cry:
<quintopia> You're not crazy. you're the goddamn headprogrammingspock!
<Weeks> You're the goddamn headprogrammingspock!
<Cheese> I love you

User avatar
The Hyphenator
Posts: 791
Joined: Mon Nov 19, 2007 2:16 am UTC
Location: The Shades, Ankh-Morpork

Re: The "IT DOESN'T WORK!" thread

Postby The Hyphenator » Thu Dec 20, 2007 2:07 am UTC

I am so pissed off at this program right now. It's a tetris game written in C++ using SDL, and I've been working on one problem for a few days, and have run clean out of ideas. I think it's a problem with the color key of the background. Basically, if I use a color key, then in the row deletion algorithm(the one that deletes a row after the user fills it up), it deletes the row it's supposed to AND ALL THE BLOCKS ABOVE IT. And if I don't use a color key, then the program somehow thinks that a COMPLETELY UNRELATED VARIABLE has some crazy memory address(I think it was 0x000000cc), and returns a memory access error. I've read the documentation on pretty much every function related to SDL and have tried EVERYTHING, believe me, EVERYTHING, all to no avail. So, yeah, I've pretty much given up. Maybe after taking a break from coding for a few days, I'll want to try again, but right now, screw this.

Rysto
Posts: 1460
Joined: Wed Mar 21, 2007 4:07 am UTC

Re: The "IT DOESN'T WORK!" thread

Postby Rysto » Thu Dec 20, 2007 2:34 am UTC

You have a memory corruption issue somewhere. Some possible causes:

-delete'ing memory before you're done with it
-going out of bounds of an array or vector
-using an uninitialized pointer

Ain't C++ grand?

Anyway, you're consistently seeing that a certain variable is getting set to some bogus value? Load your program in a debugger and set a watchpoint on that variable. Make sure that it's a hardware watchpoint. Whenever the variable is modified the debugger should stop and tell you what's modifying the variable.

Now, in my experience debuggers don't always catch all accesses(which is nuts, because I know that it's possible -- the wonderful IDA debugger can do it, but IDA is ridiculously expensive).

User avatar
The Hyphenator
Posts: 791
Joined: Mon Nov 19, 2007 2:16 am UTC
Location: The Shades, Ankh-Morpork

Re: The "IT DOESN'T WORK!" thread

Postby The Hyphenator » Fri Dec 21, 2007 12:18 am UTC

Rysto wrote:You have a memory corruption issue somewhere. Some possible causes:

-delete'ing memory before you're done with it
-going out of bounds of an array or vector
-using an uninitialized pointer


I don't think it's the second or third. It might be the first, although the more I look at it, the more confused I get. If I set a breakpoint right before the offending function, then examine the variable, everything looks perfectly fine. Then as soon as it calls the function and executes the first instruction, it fails.

User avatar
phlip
Restorer of Worlds
Posts: 7573
Joined: Sat Sep 23, 2006 3:56 am UTC
Location: Australia
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby phlip » Fri Dec 21, 2007 1:00 am UTC

The Hyphenator wrote:Then as soon as it calls the function and executes the first instruction, it fails.

Smells like stack corruption...

The way that generally happens goes like this:
  • Function a() has a local variable/array/object on the stack, and returns a pointer to it.
  • Caller reads object and sees that it looks OK... but it's reading from unallocated memory above the head of the stack.
  • Caller calls function b(), which overlaps with a()'s former stack frame, and clobbers the memory. Reading from the pointer now does something strange, depending on the workings of b(), and the compiler.

Code: Select all

enum ಠ_ಠ {°□°╰=1, °Д°╰, ಠ益ಠ╰};
void ┻━┻︵​╰(ಠ_ಠ ⚠) {exit((int)⚠);}
[he/him/his]

EvanED
Posts: 4331
Joined: Mon Aug 07, 2006 6:28 am UTC
Location: Madison, WI
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby EvanED » Fri Dec 21, 2007 1:41 am UTC

I love how GDB rereads your login files when it starts. This way, if you set in your shell an additional library path you need to run a program, run the program, see it not work somehow, then open it in GDB, you now have to tell GDB where to look for it's libraries. Even though you already call the shell. And each time you start GDB unless you put it in a startup script.

Wait, did I say "love"? I meant "hate," or perhaps "please make sure the person or people who made this decision don't touch a keyboard again".

(Yes, I am spiteful.)

User avatar
The Hyphenator
Posts: 791
Joined: Mon Nov 19, 2007 2:16 am UTC
Location: The Shades, Ankh-Morpork

Re: The "IT DOESN'T WORK!" thread

Postby The Hyphenator » Sun Dec 23, 2007 2:10 am UTC

Thanks a bunch for all your help, but I think I'll just redesign the game using different data types. See, I usually don't use things like arrays and SDL_Surface*s openly; I usually hide them in a class or struct so they're less prone to errors. I can't imagine why I thought it was a good idea here.

OFF-TOPIC: This is the 1st post I've written using the Dvorak keyboard layout, and it has taken AGES to write. Anyone else here use this layout? Is it that much better?
The image link changes whenever I find a new cool website.
Spoiler:
Image

EvanED
Posts: 4331
Joined: Mon Aug 07, 2006 6:28 am UTC
Location: Madison, WI
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby EvanED » Sun Dec 23, 2007 2:17 am UTC

The Hyphenator wrote:Anyone else here use this layout? Is it that much better?

Yes, a few of us. ;-)

(The first and the third link are the best. The first is newer, and probably where you want to turn for further discussion. ;-))

EDIT: looking again, it's hard to see that each word in "Yes, a few of us" is a separate link. Oops.

Rysto
Posts: 1460
Joined: Wed Mar 21, 2007 4:07 am UTC

Re: The "IT DOESN'T WORK!" thread

Postby Rysto » Thu Jan 03, 2008 4:20 am UTC

Spot the bug in the following code(it attempts to send a single byte to another process):

Code: Select all

//process 1(sender)
char buf[10];
snprintf(buf, sizeof(buf), "%c", byte);
SendBufferToReceiver(buf);

Code: Select all

//process 2(receiver)
char buf[10];
ReceiveMessage(buf);
char byte;
sscanf(buf, "%c", &byte);

User avatar
GrawSith
Posts: 91
Joined: Fri Dec 28, 2007 2:46 pm UTC
Location: Down-frickin'-under.
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby GrawSith » Thu Jan 03, 2008 7:42 am UTC

There's probably some simple solution to this (but it's midnight, so w/e):

I'm writing a Python program that will download the latest issue of a webcomic, and I'm using urrlib to do it. The problem piece is this:

Code: Select all

try:
         print ">> Download: Pending..."
         urllib.urlretrieve(def_target,def_dest,)
         finished = 1
      except HTTPError:
         print ">> Download: Failed. Will check again in five (5) seconds."
         finished = 0
         time.sleep(5)


This returns: "global name 'HTTPError' is not defined". Basically, I need HTTPError to tell me when it breaks, so I can code it to try again later.

(PS: This is one of my first python programs, so it's probably full of holes. The full thing is here:http://pastebin.com/m281a045a)
(PPS: Yes, I enjoy formatting my posts. Can you tell?)

Format if you wish, within reason, but please avoid reds. Red is for mod edits. Thanks!

User avatar
Dropzone
Posts: 405
Joined: Sun Dec 30, 2007 10:12 pm UTC
Location: North Lincs., UK

Re: The "IT DOESN'T WORK!" thread

Postby Dropzone » Fri Jan 04, 2008 12:03 am UTC

HTTPError is part of the urllib2 module, so in order to use it you would need to add "import urllib2" to the top of the program, and use "except urllib2.HTTPError:". But, the more important problem is: are you sure that urllib.urlretrieve actually uses HTTPError to report errors? From reading the documentation, it doesn't look to me like it does - I think it just uses IOError. So the actual fix would probably be to replace "except HTTPError:" with "except IOError:".

Some general comments about the code (none of these are actually errors, just style issues):

If you only want to give one argument to the string % operator (lines 9 and 27), there's no need to create a singleton tuple, you can just pass the argument itself. So, for example, you could change line 9 from

Code: Select all

URL_target = "http://www.questionablecontent.net/comics/%s.png" % (comicnum,)
to

Code: Select all

URL_target = "http://www.questionablecontent.net/comics/%s.png" % comicnum
, which looks neater (to me at least).

There's no need to escape the single quotes in lines 12 and 27: you only need to do that if you're using single quotes to delimit the string. That's the good thing about Python having two different kinds of quotes - you very rarely need to escape quotes in strings, because you can just use the opposite kind of quote to delimit the string (the exception is if you need to have both single and double quotes in the same string, then you're obviously going to have to escape one of them).

You seem to have a few superfluous commas floating around (the last comma on lines 8, 12, 19, 30). They're not doing any harm, but they look strange - I never realised until now that Python would accept that, so it had me confused for a moment.



edit: I suppose I could contribute a couple of my own "it-doesn't-work!" stories. The first one relates to a program I was writing in C... I can't even remember what the program was now, but I remember what I managed to do while writing it. After I added a new bit of code, the program started crashing with a segfault whenever I ran it. The bit of code I added involved allocating some memory with malloc and then accessing it - I knew that it was easy to screw that kind of thing up, so I started carefully checking the code.

Did I calculate the amount of memory to allocate correctly? Yep.
Did I declare the pointer correctly? Yep.
Did I use the correct pointer to access the memory? Yep.
Did I calculate the index to use when accessing the memory correctly? Yep.
Did I free the memory at the correct place? Yep.

Eventually, after checking just about everything else, I figured out what the bug was: I never actually called malloc. I have no idea how I managed to do that, or how it took me so long to notice it.

The second story involves another C program that, as part of its output, wrote a large number of floats to a text file using fprintf. The program was, at this point, working perfectly. I decided that a certain bit of the code would be more readable if I changed a couple of the hardcoded integer literals to hex (they were currently written in decimal). I did so, and compiled and ran the program just to check that I hadn't broken anything. It turns out that I had - about half of the floats in the output were now coming out as "0.000000" rather than their correct values. Bear in mind that what I changed couldn't possibly have affected the program's behaviour - the literals still had exactly the same value, just written in a different base - yet it was affecting the program's behaviour. To cut a long story short, I discovered that the change had somehow triggered a bug in GCC's optimiser - adding -fno-optimize-sibling-calls to the command line restored the correct behaviour. Finding that the bug you've been trying to fix isn't even in your own code is rather annoying.

User avatar
GrawSith
Posts: 91
Joined: Fri Dec 28, 2007 2:46 pm UTC
Location: Down-frickin'-under.
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby GrawSith » Fri Jan 04, 2008 4:08 am UTC

Dropzone: Thanks for the tips, it seems to be working quite well now.

But about this:
Dropzone wrote:You seem to have a few superfluous commas floating around (the last comma on lines 8, 12, 19, 30). They're not doing any harm, but they look strange - I never realised until now that Python would accept that, so it had me confused for a moment.


I don't know why, but I like having bracketed stuff ending with commas. It seems more neat / readable. To me, at least.

User avatar
headprogrammingczar
Posts: 3072
Joined: Mon Oct 22, 2007 5:28 pm UTC
Location: Beaming you up

Re: The "IT DOESN'T WORK!" thread

Postby headprogrammingczar » Sat Jan 05, 2008 4:04 pm UTC

Here is a fun one. I have been trying to learn [url=en.wikipedia.org/wiki/aspectj]AspectJ[/url], which compiles into Java bytecode and is supposedly easier to modularize. I downloaded the runtime (1.5.4) from eclipse.org, and installed the AspectJ module to Eclipse (v. 3.2.2 if it matters).
I wrote a little HelloAspects program, with the main class of

Code: Select all

package tests;     // <------

public aspect HelloWorld {
   public static void main(String args[]) {
      stuff();
   }
        // When the code below is not visible, the output for this program is
        // Hello world!
   public static void stuff() {
                System.out.println("Hello world!");
   }
}

Saved in a folder aptly named 'tests'.
I then make an aspect:

Code: Select all

package botherBother;        // <-----

public aspect AnnoyingAspect {
   pointcut annoying():call(* stuff());
        // When this code is visible to the main class, the output should be
        // before
        // Hello world!
        // after
   before():annoying(){
      System.out.println("before");
   }

   after():annoying(){
      System.out.println("after");
   }
}

Saved in the folder 'botherBother' so that both folders share a common super-folder. This encapsulates the two files until I import one from the other, and this rule applies to any language I decide to write this in. However, without an import, AnnoyingAspect is completely visible to HelloWorld! I am beginning to doubt the legitimacy of this language.
<quintopia> You're not crazy. you're the goddamn headprogrammingspock!
<Weeks> You're the goddamn headprogrammingspock!
<Cheese> I love you

Rysto
Posts: 1460
Joined: Wed Mar 21, 2007 4:07 am UTC

Re: The "IT DOESN'T WORK!" thread

Postby Rysto » Thu Jan 10, 2008 3:04 am UTC

Rysto wrote:Spot the bug in the following code(it attempts to send a single byte to another process):

Code: Select all

//process 1(sender)
char buf[10];
snprintf(buf, sizeof(buf), "%c", byte);
SendBufferToReceiver(buf);

Code: Select all

//process 2(receiver)
char buf[10];
ReceiveMessage(buf);
char byte;
sscanf(buf, "%c", &byte);

No guesses?

User avatar
phlip
Restorer of Worlds
Posts: 7573
Joined: Sat Sep 23, 2006 3:56 am UTC
Location: Australia
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby phlip » Thu Jan 10, 2008 3:21 am UTC

I want to shoot you for using sscanf when "char byte = buf[0]" would do (or, indeed, at all... scanf makes me sad in my pants)... snprintf is unnecessary too... but other than that, no, nothing glaring...

Unless maybe you're using some header that defines "typedef unsigned char byte;" or something...

Code: Select all

enum ಠ_ಠ {°□°╰=1, °Д°╰, ಠ益ಠ╰};
void ┻━┻︵​╰(ಠ_ಠ ⚠) {exit((int)⚠);}
[he/him/his]

Rysto
Posts: 1460
Joined: Wed Mar 21, 2007 4:07 am UTC

Re: The "IT DOESN'T WORK!" thread

Postby Rysto » Thu Jan 10, 2008 4:02 am UTC

I didn't write the code. And here's a hint: doing char byte = buf[0]; eliminates the bug.

User avatar
phlip
Restorer of Worlds
Posts: 7573
Joined: Sat Sep 23, 2006 3:56 am UTC
Location: Australia
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby phlip » Thu Jan 10, 2008 4:17 am UTC

Wait... can byte be 0? Are they trying to send binary data as a null-terminated string?

For anything else, I think it'll work...

Anyways, if that's the case, then obviously the solution is to make the receiver "char byte = 0; sscanf(eww);"... or maybe "char byte; if (sscanf(eww) < 1) byte = 0;"...

Code: Select all

enum ಠ_ಠ {°□°╰=1, °Д°╰, ಠ益ಠ╰};
void ┻━┻︵​╰(ಠ_ಠ ⚠) {exit((int)⚠);}
[he/him/his]

Rysto
Posts: 1460
Joined: Wed Mar 21, 2007 4:07 am UTC

Re: The "IT DOESN'T WORK!" thread

Postby Rysto » Thu Jan 10, 2008 4:36 am UTC

phlip wrote:Wait... can byte be 0? Are they trying to send binary data as a null-terminated string?

Yes. Yes we were. And to make things work, most of the bytes we were sending were 0, but by some perversion of fate most of the time the stack position of the receiver's byte variable did contain 0 anyway. I was tearing my hair out for a week trying to track down the seemingly random corruption. The worst part was how, if I enabled the GUI the corruption would pretty much always happen, but as soon as I turned the GUI off the stack position would remain "0" and the problem would disappear, so I thought the problem was in the GUI. And then if I enabled logging with the GUI on the corruption also wouldn't exhibit itself. The absolute topper, though, was the fact that these bytes were coming from a hardware device, and every once in a while the hardware would go completely haywire and send us bogus data. So I could figure out if this was a hardware problem, a software problem or if our software was sending some kind of invalid message to the hardware that could cause it to go into a bad state.

User avatar
mabufo
Posts: 105
Joined: Sun Sep 09, 2007 11:17 pm UTC

Re: The "IT DOESN'T WORK!" thread

Postby mabufo » Thu Jan 17, 2008 4:05 pm UTC

I need some help! For some reason my main method won't execute my one line statement that accesses a method in another class that I have. This is for my Computer Science class, but I need to figure out why this is happening before I can continue. When I try to run my Stats class, which contains the main method, nothing happens(visibly). Could someone help me figure out why I'm not seeing anything happen?

My main method:

Code: Select all


public class Stats
{
   public static void main(String args[]){
      
      System.out.println(ArrayOperations.getLength());

   }//end of main method

}//end of stats class



My getLength() method in my 'ArrayOperations' class:
Spoiler:

Code: Select all

public class ArrayOperations {
   /**
    * Finds the length of our mystery array
    * @return length
    */
   public static int getLength(){
      int length = 0;
      int input = 0;
      try {
         FileReader filename = new FileReader("H:/numbers.txt");
         Scanner in = new Scanner(filename);
         while (in.hasNextInt()) {
            input = in.nextInt();
            length++;
         }
      //closes try statement to our input file
      }
      //prints a stack trace upon failure
      catch (IOException e) {
         e.printStackTrace();
      }
      //closes input file
      System.out.close();
      
      return length;

   }//end of getlength()

User avatar
Duck
Posts: 29
Joined: Wed Apr 11, 2007 1:53 pm UTC
Location: Somerset, UK
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby Duck » Thu Jan 17, 2008 4:16 pm UTC

spelunker wrote:There was another time when I was attempting to use foreach() to modify objects in an array, which was driving me nuts because nothing was changing. Turned out in PHP4 foreach() passed by value, by reference, which made it utterly useless for me.


FWIW, php can do this using the '&' symbol. Instead of:

Code: Select all

foreach ($items as $item)

Use:

Code: Select all

foreach ($items as &item)

'$item' will then be a reference to the original item in the array rather than a copy.

User avatar
und3rdark
Posts: 27
Joined: Mon Jan 14, 2008 7:25 pm UTC
Location: Canton, Michigan

Re: The "IT DOESN'T WORK!" thread

Postby und3rdark » Thu Jan 17, 2008 7:12 pm UTC

try

Code: Select all

System.out.println("L:"ArrayOperations.getLength());

If you get an "L:", then getLength() is returning null (I think).

If you still get nothing: main() isn't being run. If this is the case, I need more info to help (IDE name & version, JKD version, etc.)
"The impulse to discriminate is a feature of our brains. We look for patterns and make decisions based on them. Sometimes the patterns are illusions, and we come to irrational conclusions."
-Scott Adams

User avatar
wr3cktangle
Posts: 75
Joined: Tue Aug 01, 2006 5:03 pm UTC

Re: The "IT DOESN'T WORK!" thread

Postby wr3cktangle » Thu Jan 17, 2008 8:13 pm UTC

mabufo wrote:I need some help! For some reason my main method won't execute my one line statement that accesses a method in another class that I have. This is for my Computer Science class, but I need to figure out why this is happening before I can continue. When I try to run my Stats class, which contains the main method, nothing happens(visibly). Could someone help me figure out why I'm not seeing anything happen?
Spoiler:
My main method:

Code: Select all


public class Stats
{
   public static void main(String args[]){
      
      System.out.println(ArrayOperations.getLength());

   }//end of main method

}//end of stats class



My getLength() method in my 'ArrayOperations' class:

Code: Select all

public class ArrayOperations {
   /**
    * Finds the length of our mystery array
    * @return length
    */
   public static int getLength(){
      int length = 0;
      int input = 0;
      try {
         FileReader filename = new FileReader("H:/numbers.txt");
         Scanner in = new Scanner(filename);
         while (in.hasNextInt()) {
            input = in.nextInt();
            length++;
         }
      //closes try statement to our input file
      }
      //prints a stack trace upon failure
      catch (IOException e) {
         e.printStackTrace();
      }
      //closes input file
      System.out.close();
      
      return length;

   }//end of getlength()


either ArrayOperations needs to be a static class (i think that's how they're done) meaning it doesn't need to be instantiated to use, like the Math class as compared to the String class, or you need to instantiate an ArrayOperations object and also maybe add a constructor for one in that class, though a default constructor may be assumed if not given.

you may be able to get away with

Code: Select all

System.out.println(new ArrayOperations.getLength());

which will create a new ArrayOperations object but not keep reference to it.

it's been a little bit since i've done java, so i may be wrong on any or all of what i've just said.

I haven't really considered bugs in your ArrayOperations class though to see if that's where the failure is occuring..
the simplest way to find where you're code is failing is to throw in a bunch of System.out.println("Made it to x, trying y");
into the code and then just remove or comment them out afterwards.
this will at least tell you where it's failing, but not why.
Maxim 33. When faced with the unusual, self-destruct.
My blog

Rysto
Posts: 1460
Joined: Wed Mar 21, 2007 4:07 am UTC

Re: The "IT DOESN'T WORK!" thread

Postby Rysto » Thu Jan 17, 2008 9:41 pm UTC

The previous answers are all wrong. Your problem is this:

Code: Select all

      //closes input file
      System.out.close()


You close System.out, which means that you can't write to System.out anymore. You meant to say filename.close();

User avatar
Dropzone
Posts: 405
Joined: Sun Dec 30, 2007 10:12 pm UTC
Location: North Lincs., UK

Re: The "IT DOESN'T WORK!" thread

Postby Dropzone » Thu Jan 17, 2008 10:10 pm UTC

Rysto beat me to posting the answer, so here's an elaboration on what was wrong with the answers before his:

und3rdark wrote:try

Code: Select all

System.out.println("L:"ArrayOperations.getLength());
If you get an "L:", then getLength() is returning null (I think).
getLength() can't possibly return null, because its return type is int (a primitive type). Only functions with reference return types can return null. In any case, System.out.println(null) actually prints the string "null", rather than doing nothing. Also, you're missing a + after the closing quotes, but I assume that was just a typo.

wr3cktangle wrote:either ArrayOperations needs to be a static class (i think that's how they're done) meaning it doesn't need to be instantiated to use, like the Math class as compared to the String class, or you need to instantiate an ArrayOperations object and also maybe add a constructor for one in that class, though a default constructor may be assumed if not given.
The code's actually fine in that respect. For a start, static classes are a C# thing (IIRC) - they don't exist in Java*. Static methods can be called without instantiating the class they're declared in, and getLength() is declared as a static method, so that's okay.

*nested classes can be static, but in that context "static" means something different

you may be able to get away with

Code: Select all

System.out.println(new ArrayOperations.getLength());
which will create a new ArrayOperations object but not keep reference to it.
If getLength() weren't static, that would be the correct way of doing it (except that there's a () missing after ArrayOperations).

User avatar
mabufo
Posts: 105
Joined: Sun Sep 09, 2007 11:17 pm UTC

Re: The "IT DOESN'T WORK!" thread

Postby mabufo » Fri Jan 18, 2008 3:22 am UTC

Thanks for helping me track down the issue guys. I feel embarrassed for having missed it. However, I have a new problem now, Eclipse is telling me that filename cannot be resolved. Is this because filename is created inside of the try statement in the getLength() method? Is this a scope problem? I haven't done much work with files so I'm a little confused with all of this try and catch business.

User avatar
phlip
Restorer of Worlds
Posts: 7573
Joined: Sat Sep 23, 2006 3:56 am UTC
Location: Australia
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby phlip » Fri Jan 18, 2008 3:31 am UTC

Yes, it sounds like a scoping problem... you're defining filename inside the try{} and trying to use it outside.

The options are: (a) Put "FileReader filename;" outside the try{} block, or (b) Move "filename.close()" into the try{} block. I think (b) is the right answer in this case... it should probably be in there anyway (I've never heard of closing a file to throw an exception, but it never hurts to be thorough).

Code: Select all

enum ಠ_ಠ {°□°╰=1, °Д°╰, ಠ益ಠ╰};
void ┻━┻︵​╰(ಠ_ಠ ⚠) {exit((int)⚠);}
[he/him/his]

Karrion
Posts: 92
Joined: Fri Jun 22, 2007 12:14 am UTC
Location: Melbourne, AU

Re: The "IT DOESN'T WORK!" thread

Postby Karrion » Fri Jan 18, 2008 4:09 am UTC

phlip wrote:I've never heard of closing a file to throw an exception, but it never hurts to be thorough.


Java API wrote:public abstract void close() throws IOException


You definitely need to have Reader.close() inside the try{} block to avoid a compiler error. Although in practise I don't think a FileReader can throw an exception on close(), there are other Reader types that can.

User avatar
b.i.o
Green is the loneliest number
Posts: 2519
Joined: Fri Jul 27, 2007 4:38 pm UTC
Location: Hong Kong

Re: The "IT DOESN'T WORK!" thread

Postby b.i.o » Sat Jan 19, 2008 7:33 pm UTC

Java makes me want to kill things sometimes.

Anyone have any idea why why java -Xms<size> and java -Xmx<size> seem to have the same effect as typing java -help when legal values are put in for <size>? (And seem to have no effect on the available memory at all.) The max seems to be set at about 64mb (66650112 bytes) by default, which is a problem when the program I'm trying to run needs more like 70.

(I'm using JDK 1.5.0_12 if that matters at all)

User avatar
Dropzone
Posts: 405
Joined: Sun Dec 30, 2007 10:12 pm UTC
Location: North Lincs., UK

Re: The "IT DOESN'T WORK!" thread

Postby Dropzone » Sat Jan 19, 2008 8:02 pm UTC

Silver2Falcon wrote:Anyone have any idea why why java -Xms<size> and java -Xmx<size> seem to have the same effect as typing java -help when legal values are put in for <size>?

Can you post the exact command line that you're using? It sounds like you're getting the syntax wrong somehow, but it's hard to tell without knowing exactly what you're typing.

User avatar
b.i.o
Green is the loneliest number
Posts: 2519
Joined: Fri Jul 27, 2007 4:38 pm UTC
Location: Hong Kong

Re: The "IT DOESN'T WORK!" thread

Postby b.i.o » Sun Jan 20, 2008 2:32 am UTC

All right, I'm officially an idiot.

While getting the syntax wrong I completely ignored the message at the top of the help thing that popped up that showed me the correct syntax. It works now, thanks for the help :P.

*edit* Well it turns out I needed almost 256mb of memory, not 70mb. Dealing with 60mb+ String arrays gets really ugly, really fast on the memory front.

User avatar
mabufo
Posts: 105
Joined: Sun Sep 09, 2007 11:17 pm UTC

Re: The "IT DOESN'T WORK!" thread

Postby mabufo » Thu Jan 31, 2008 10:07 pm UTC

I feel like sort of a jerk asking for help with my classwork and all that, so I hope you guys don't mind giving me a hand and helping me work through my code trouble.

We need to count the frequency of each letter in Hamlet. Here's what I have:
Spoiler:
letterCounter.java:

Code: Select all

/**
 * Collection of methods to help count the frequency
 *  of each letter in Hamlet
 *
 * @author Matthew Young
 *
 */

import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class letterCounter {
   
   
   /**
    * have one array hold all the characters, have an
    * empty array of the same length hold zeroesread
    * in each char from file, change to lowercase and
    * compare to what's in the array, and then increment
    *  the proper spot in our second,empty array, to hold
    *  a count
    *
    * @return letterFrequency
    */
   public static int[] frequency(){
      //our alphabet, IE what we're looking for
      char[] alphabet = {'a','b','c','d','e','f',
                         'g','h','i','j','k','l',
                         'm','n','o','p','q','r',
                         's','t','u','v','w','x',
                         'y','z'};
      //parallel array to hold our frequency
      int[] letterFrequency = new int[alphabet.length];
      
      //opens our file to start reading:
      String input;
      try {
         FileReader filename = new FileReader("K:/hamlet.txt");
         Scanner in = new Scanner(filename);
         while (in.hasNextInt()) {
            input = in.next();
            //cleans/splits our string and counts the letters
            input = input.toLowerCase();
            //counts the letters and updates our frequency array
            for(int i = 0; i < input.length(); i++){
               char character = input.charAt(i);
               for(int j = 0; j < alphabet.length; j++){
                  if(character == alphabet[j]){
                     letterFrequency[j] += 1;
                  }//end if
               }//end inside for
            }//end outside for
            
            
         }//end while   
      
      filename.close();//closes input file
      }//closes try statement to our input file
      //prints a stack trace upon failure
      catch (IOException e) {
         e.printStackTrace();
      }
      
      
   return letterFrequency;
   
   }//end method
   

}


Spoiler:
hamlet.java (MAIN METHOD HERE):

Code: Select all


public class hamlet {
   public static void main(String args[]){
      int[] frequencies = letterCounter.frequency();
      
      //prints our frequencies
      for(int i = 0; i < frequencies.length; i++){
         System.out.println("There are " + frequencies[i] + " " + (char)(i+(int)'a') + "\'s");
      }//end for
   }//end main

}//end method


How the code works is that I have one array hold all the characters, have an empty array of the same length hold zeros read in each string(broken into characters) from our hamlet file, change to lowercase and compare to what's in the array(the alphabet(#0-25)), and then increment the proper spot in our second, empty array, to hold the frequency of that corresponding letter. My output shows that my frequencies array created in the main body returns all zeros. Where am I wrong?

EDIT: clearly there's some huge logic error that I can't spot. Could you help me find it ?

User avatar
phlip
Restorer of Worlds
Posts: 7573
Joined: Sat Sep 23, 2006 3:56 am UTC
Location: Australia
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby phlip » Thu Jan 31, 2008 10:36 pm UTC

Java API doc for java.util.Scanner wrote:public boolean hasNextInt()

Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input.
I think that's not quite what you're after. Try hasNext().

Code: Select all

enum ಠ_ಠ {°□°╰=1, °Д°╰, ಠ益ಠ╰};
void ┻━┻︵​╰(ಠ_ಠ ⚠) {exit((int)⚠);}
[he/him/his]


Return to “Coding”

Who is online

Users browsing this forum: No registered users and 8 guests