The "IT DOESN'T WORK!" thread

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

Moderators: phlip, Moderators General, Prelates

xkcd_n00bz
Posts: 134
Joined: Sat Jul 28, 2007 11:33 pm UTC
Location: Seattle, WA

Postby xkcd_n00bz » Tue Sep 11, 2007 9:00 pm UTC

Programming in C is for people who would rather sit at home and match up pairs of socks by the count of their elastic bands, than to just get dressed with mismatched shoes and take the lady out to dinner and nail her in the car on the way home.

Give me scripted languages dammit! To hell with micromanaging the microprocessor! Garbage collection should be left to garbagemen! Efficient use of memory? Strictly cast variables? Read the whole damn file into a scalar and mung it around with kludged-together pseudo-PERL regex statements gleened from comments on slashdot! Give me results, give me them now, and to hell with programatic elegance!


Christ, somebody give me a double shot of bourbon.

User avatar
taggedunion
Posts: 146
Joined: Fri Jul 06, 2007 6:20 am UTC
Location: BEHIND YOU

Postby taggedunion » Wed Sep 12, 2007 5:50 am UTC

*gives xkcd_n00bz a double of Maker's Mark on the rocks*

At least, that's how I like it. Except I prefer just having a single, but whatever.

It's very nice to code in C sometimes, to get that baremetal feel... but it's really something I should stay away from. The pain of using C is greatly softened with the use of libraries, like Boehm's GC and "Cords" (a rather fascinating implementation of a strings library), Paul Hseih's BString, UTHash, etc. Using Boehm's GC, especially, for me is such a relief when programming in C. I use GC_malloc and then worry no more. :)

I do enjoy scripting languages. My favorites are Python, Lua and Ruby, with Lua seriously contending for favorite with the incumbent Python. And Lua's C interface/API is sooo nice and easy to use and wonderful... *sigh*.

But, yeah, generally C is splitting hairs. And hell, the latter part of your first paragraph sounds a little too close to my life. ;)
Yo tengo un gato en mis pantelones.

User avatar
Pesto
Posts: 737
Joined: Wed Sep 05, 2007 5:33 pm UTC
Location: Berkeley, CA

Postby Pesto » Wed Sep 12, 2007 7:39 pm UTC

I HATE MS REPORTING SERVICES!

All these work.

Code: Select all

=RunningValue(1, Sum, datasource)
=RunningValue(iif(1 = 1, 1, 0), Sum, datasource)
=RunningValue(iif(Fields!Type.Value = "CC", 1, 0), Sum, datasource)
=RunningValue(Fields!Amt.Value, Sum, datasource)


But this breaks it.

Code: Select all

=RunningValue(iif(Fields!Type.Value = "CC", Fields!Amt.Value, 0), Sum, datasource)


GAH! FMUUUUUUUUUUUUUUUUUUUUUUUHHHHHHHHHHH!!!!!!!!!!!!

Agentlien
Posts: 31
Joined: Mon Sep 10, 2007 6:06 pm UTC
Location: Göteborg, Sweden

Postby Agentlien » Thu Sep 13, 2007 10:52 pm UTC

xkcd_n00bz wrote:Programming in C is for people who would rather sit at home and match up pairs of socks by the count of their elastic bands, than to just get dressed with mismatched shoes and take the lady out to dinner and nail her in the car on the way home.

Give me scripted languages dammit! To hell with micromanaging the microprocessor! Garbage collection should be left to garbagemen! Efficient use of memory? Strictly cast variables? Read the whole damn file into a scalar and mung it around with kludged-together pseudo-PERL regex statements gleened from comments on slashdot! Give me results, give me them now, and to hell with programatic elegance!


Christ, somebody give me a double shot of bourbon.


That really made me laugh. :D I never understood that attitude until I started programming Java, though. Suddenly I thought "Oh my dear, this is so nice.. All worries, all pointers, just gone!" But after a while I started missing it, and I never got over the strictness between types (especially the whole boolean business, I want to be able to use references and ints! And why isn't it just called bool? My lazy fingers hurt at the thought of all those extra characters. Well, not really. :p)

I guess all in all it really depends on what you need for the moment, but since I've mostly used C/C++ I've just learned to deal with the memory management and all. Whether it's often being unnecessarily picky or not, they are the languages I feel the most comfortable with and hence the ones I can be the most productive in.
You C, I aim to Assemble a PERL of knowledge, helpful FOR TRANsit to new languages.
___
When writing a report, always include valid references. You never know when the Garbage Collector may stop by.

User avatar
Aperfectring
Posts: 252
Joined: Fri Sep 07, 2007 3:47 am UTC
Location: Oregon (happily)

Postby Aperfectring » Sat Sep 15, 2007 1:21 am UTC

xkcd_n00bz wrote:Programming in C is for people who would rather sit at home and match up pairs of socks by the count of their elastic bands, than to just get dressed with mismatched shoes and take the lady out to dinner and nail her in the car on the way home.

Give me scripted languages dammit! To hell with micromanaging the microprocessor! Garbage collection should be left to garbagemen! Efficient use of memory? Strictly cast variables? Read the whole damn file into a scalar and mung it around with kludged-together pseudo-PERL regex statements gleened from comments on slashdot! Give me results, give me them now, and to hell with programatic elegance!


Christ, somebody give me a double shot of bourbon.


I'm sorry, but without those low level concepts it would be nearly impossible to do an OS. There are times and places for each of them. Garbage collection and typeless variable introduce large amounts of overhead which would bring an OS to it's knees.

However, I also love perl and shell scripting, because they can be used like duct tape to patch together almost anything. Every once in a while a person will be looking over my shoulder when I am working on something, and then I go and type a mini shell script out to do something, and I look back and they have this horrified look on their face. IMO, if you need more than a one line command to do something, you should create a script and put it into your own personal "bin" directory so it is always in your path.

Both concepts have their place. When in performance-critical places, it is best to take the programmer hit and just do it in a lower level language. Otherwise, hack it together with some combination of perl and shell scripts (make sure to use the fact that this:

Code: Select all

TEMP_VAR=a; echo `TEMP_VAR=b;` $TEMP_VAR;

Will output "a" when run. It really annoys people... Note, this is a simplified example, and purposely written to confuse people.
Odds are I did well on my probability exam.

User avatar
Rummy
Posts: 74
Joined: Sun Sep 23, 2007 8:15 pm UTC
Location: Clinton, MA
Contact:

Postby Rummy » Mon Sep 24, 2007 11:32 pm UTC

xkcd_n00bz wrote:Programming in C is for people who would rather sit at home and match up pairs of socks by the count of their elastic bands, than to just get dressed with mismatched shoes and take the lady out to dinner and nail her in the car on the way home.

Give me scripted languages dammit! To hell with micromanaging the microprocessor! Garbage collection should be left to garbagemen! Efficient use of memory? Strictly cast variables? Read the whole damn file into a scalar and mung it around with kludged-together pseudo-PERL regex statements gleened from comments on slashdot! Give me results, give me them now, and to hell with programatic elegance!


Christ, somebody give me a double shot of bourbon.


If the world were left to men like you, there would be no kernels. :)

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 » Tue Oct 02, 2007 7:45 am UTC

Grrr. I think the GDB maintainers must be masochistic.

I have temporary additions I make to LD_LIBRARY_PATH so that I can run programs with a specific shared library that I don't have normally registered. GDB sees fit to ignore the fact that I make changes and rereads your login scripts, meaning that it doesn't know where the library is. You can set GDB's search path from within GDB, but for some reason that's not working even though it "should". So I had to copy the libraries somewhere where it'll find it.

I want to hit someone on the GDB team over the head right now with a whiffle bat.

Edit:
Here's a fun excerpt from my GDB session.

Code: Select all

HorizontalBitBoard::operator() (this=0x7fbffff5b8, row=7, col=7) at Board.h:33
33          uint64_t mask = ((1 << col) << row*8) & data;
(gdb)
34          return mask;
(gdb) print mask
$9 = 34359738368
(gdb) print data
$10 = 34359738368
(gdb) print ((1 << col) << row*8)
$11 = 9223372036854775808
(gdb) print ((1 << col) << row*8) & data
$12 = 0

Now how I evaluate an expression in GDB that is the same as what executes in the program, and they produce different results.

User avatar
A'Tuin
Posts: 33
Joined: Tue Oct 02, 2007 2:30 pm UTC

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

Postby A'Tuin » Thu Oct 04, 2007 8:21 pm UTC

Right why does this not work(its a program for a petrol pump)

status=F means the pertol is Flowing

petrol=floating point varible =amount of petrol issued at the pump

no more that 100 litres can be issued, this code is run every 0.25 seconds

Code: Select all

if ((status='F')and(petrol<100)) then
petrol:=petrol+0.1;


some how i get 100.1 lites contantly be issued if i leave it to go as high as possible. i can sovle the problem by changing the code to

Code: Select all

if ((status='F')and(petrol<99.9)) then
petrol:=petrol+0.1;


But i should't have to it should nerver get to a 100.1 using the orginal code beasue of the petrol<100 I assume it has something to do with it being a floting point number, but could someone tell me what the problem is?

thanks

User avatar
Geekthras
3) What if it's delicious?
Posts: 529
Joined: Wed Oct 03, 2007 4:23 am UTC
Location: Around Boston, MA

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

Postby Geekthras » Thu Oct 04, 2007 10:09 pm UTC

My biggest programming disaster was when I was starting CLISP and tested myself by making a prime tester, which would load a list of primes from a file, then test the number you entered with the sieve of Eratsosothsothoneonsonsesbssnetothenes. However, I didn't realize that all variables are global. I use the same variable multiple times, compile it and BAM Stack Overflow error. Took me days to figure it out.


I prefer Java and Lisp over C. I'm learning it so I can program in the FIRST robotics competition.
Wait. With a SPOON?!

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

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

Postby Karrion » Thu Oct 04, 2007 11:12 pm UTC

A'Tuin wrote:I assume it has something to do with it being a floting point number, but could someone tell me what the problem is?


Floating point numbers don't have infinite precision - they have to be stored in a limited number of bits, after all. So not every number can actually be represented by a float. This means that every time you do an operation, the result is rounded off to the nearest number that actually can be repesented. Over the course of your thousand-odd additions, these rounding errors add up, so when you expect petrol to be 100.0, it's really, maybe, 100.00000152587890056566 or some such.

I'd suggest you redefine petrol in, say, millilitres and use integer maths.

jeffpc
Posts: 15
Joined: Fri Oct 05, 2007 4:04 am UTC
Location: Stony Brook, NY

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

Postby jeffpc » Fri Oct 05, 2007 5:17 am UTC

One note about getting most of the credit for something that mostly doesn't work...I was a TA for one course where the students were supposed to write a series of C programs. (Not a bad course, if you ask me...) Well, at one point, I came across one students submission, and _unfortunately_ I had to give the student ~85% of full credit because technically, his code, although utterly broken and nasty (something that should get the author tried for crimes against humanity), did enough that the things tested by the grading criteria were mostly there.

Sometimes, it just isn't possible to check everything without having hundreds of conditions that need to be checked.

I tried my best to deduct points to make the grade more realistic, but I just could not find anything :-/

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 Oct 05, 2007 5:44 am UTC

Karrion wrote:Floating point numbers don't have infinite precision - they have to be stored in a limited number of bits, after all. So not every number can actually be represented by a float. This means that every time you do an operation, the result is rounded off to the nearest number that actually can be repesented. Over the course of your thousand-odd additions, these rounding errors add up, so when you expect petrol to be 100.0, it's really, maybe, 100.00000152587890056566 or some such.

Or, more to the point, the sum of one thousand 0.1s might be 99.99999973665303289, which, as we all can see, is under 100.

Some languages don't define = for floats for this reason; 0.3 + 0.3 isn't guaranteed to be equal to 0.6, so using floating point equal is very often wrong, so they make it hard/impossible to do. (What you usually want is to take the difference and see if the absolute difference is less than some epsilon whose value depends on your program's needs.)

Depending on your speed requirements and whether you're doing non-basic operations like square root, you may be able to use a rational number library instead of floats which would give you infinite precision. (This is especially viable in a language like C++ or C# that gives you operator overloading; it would be quite painful in C or Java.)

User avatar
A'Tuin
Posts: 33
Joined: Tue Oct 02, 2007 2:30 pm UTC

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

Postby A'Tuin » Fri Oct 05, 2007 8:10 am UTC

EvanED & Karrion thanks guys, I know that pointing point numbers work like that, thats why i though it was probally was that, but just want some to look it over and check it was't somthing more simple i was't seeing raher than going and changing all that code for nothing. thanks for the idea about using milllitres that would be a good way around it.

Thanks *cookies all around* :D

User avatar
Hench
Porn, hence, Man
Posts: 498
Joined: Wed Mar 28, 2007 4:16 pm UTC
Location: Right between my eyes
Contact:

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

Postby Hench » Mon Oct 08, 2007 5:30 am UTC

This floating point number imprecision thing really hit me in the head this past summer at my place of work - made it nearly impossible to complete the task as the whole thing depended on being able to properly compare real numbers with 5ish decimals. Solved that problem by using the built-in Java class java.math.BigDecimal which specifies a precision value and somehow (I have no idea how it does it...) is able to properly and consistently compare floating point numbers (Java's double primitive, really). Until I implemented that, the thing was terribly unreliable.
Spoiler:
Your perceptions will not change reality, but simply color it.

TV4Fun
Posts: 106
Joined: Mon Oct 01, 2007 5:45 am UTC
Location: Certifiable C++ Programmer

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

Postby TV4Fun » Thu Oct 11, 2007 5:27 am UTC

Spot the flaw:

Code: Select all

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
  double factorial[101];
  factorial[0] = 1.0;
  double omegaAll = 0.0;
  int i;
  for (i = 0; i < 100; ++i);
  {
    factorial[i + 1] = factorial[i] * (i + 1);
  }

  ofstream outfile("table.txt");

  double omegaA, omegaB;

  for (i = 0; i <= 80; ++i);
  {
    omegaA = factorial[100] / factorial[i] / factorial[100 - i];
    omegaB = factorial[100] / factorial[80 - i] / factorial[20 + i];
    outfile << i << ' ' << omegaA << ' ' << 80 - i << ' ' << omegaB << ' ' << omegaA * omegaB << endl;
    omegaAll += omegaA * omegaB;
  }

  outfile << omegaAll << endl;
  outfile.close();

  return 0;
}
$_[0] wrote:rule 2:
Once a relationship ends, physical access to all relevant machinery is denied.

User avatar
Geekthras
3) What if it's delicious?
Posts: 529
Joined: Wed Oct 03, 2007 4:23 am UTC
Location: Around Boston, MA

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

Postby Geekthras » Thu Oct 11, 2007 5:35 am UTC

Here's some Java code I was working on for a physic sim:

Code: Select all

import java.awt.*;
import javax.swing.*;
public class Compiler extends JApplet {
     public static void main(String[] args) {
          for(ever) {
               do(stuff;)
           }
     }
}
Wait. With a SPOON?!

Crazy Eddie
Posts: 18
Joined: Wed Oct 10, 2007 10:45 pm UTC

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

Postby Crazy Eddie » Sat Oct 13, 2007 4:17 am UTC

I was working on a class that's supposed to "mark" a position in a text document and update an offset as text is inserted and removed. It went something like this...

Code: Select all

class LPPosition implements Position
{
  private int m_offset;

  public LPPosition(int offset)
  {
    m_offset = offset;
  }

  public void updatePosition(int insertPosition, int insertLength)
  {
    // Code to calculate the new offset that I kept fiddling with for
    // hours and wondering why the code that used my class kept getting confused
    // and asking my rendering piece for the text between offsets zero and zero.
    ...
  }

  public int getOffset()
  {
    // Gee, you think it might have something to do with this, genius?
    return 0;
  }
}

User avatar
Cosmologicon
Posts: 1806
Joined: Sat Nov 25, 2006 9:47 am UTC
Location: Cambridge MA USA
Contact:

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

Postby Cosmologicon » Sun Oct 14, 2007 2:17 am UTC

TV4Fun wrote:Spot the flaw:

Code: Select all

  for (i = 0; i < 100; ++i);
  {
    factorial[i + 1] = factorial[i] * (i + 1);
  }

Oh, excellent. Now I have a good reason to dislike that style besides esthetics. Thanks!

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 Oct 14, 2007 3:47 am UTC

Huh?

User avatar
Strilanc
Posts: 646
Joined: Fri Dec 08, 2006 7:18 am UTC

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

Postby Strilanc » Sun Oct 14, 2007 5:19 am UTC

EvanED wrote:Huh?


There's a semicolon ending the for loop before the block starts, but it looks like the block is the contents of the for loop.

He's referring to bracket-on-the-same-line vs bracket-after-the-line style.
Don't pay attention to this signature, it's contradictory.

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 Oct 14, 2007 6:05 am UTC

Alky wrote:There's a semicolon ending the for loop before the block starts, but it looks like the block is the contents of the for loop.

He's referring to bracket-on-the-same-line vs bracket-after-the-line style.

Ohhh, I missed that semicolon. Nasty. I still don't think I would have known what he was talking about though. ;-)

Even as someone who now uses K&R style, I'm not sure how bracket-at-end-of-line would really help here.

I'm also disappointed that I could get NONE of the compilers I tried (GCC with -W -Wall -Wextra, ICC with -wall -wcheck, Sun CC with +w +w2, and MSVC with /W4) to warn about that loop. Even lint didn't warn by default; you have to pass -Nlevel=# (for # in 1 to 4).

User avatar
Strilanc
Posts: 646
Joined: Fri Dec 08, 2006 7:18 am UTC

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

Postby Strilanc » Sun Oct 14, 2007 3:35 pm UTC

EvanED wrote:
Alky wrote:There's a semicolon ending the for loop before the block starts, but it looks like the block is the contents of the for loop.

He's referring to bracket-on-the-same-line vs bracket-after-the-line style.

Ohhh, I missed that semicolon. Nasty. I still don't think I would have known what he was talking about though. ;-)

Even as someone who now uses K&R style, I'm not sure how bracket-at-end-of-line would really help here.

I'm also disappointed that I could get NONE of the compilers I tried (GCC with -W -Wall -Wextra, ICC with -wall -wcheck, Sun CC with +w +w2, and MSVC with /W4) to warn about that loop. Even lint didn't warn by default; you have to pass -Nlevel=# (for # in 1 to 4).


If you uses the bracket-at-end-of-line style it would look a lot more obvious because semicolons a rarely right before a bracket. I prefer bracket-at-end-of-line because it has the whole "if (x) then" style and cuts out an extra line I think is unnecessary.
Don't pay attention to this signature, it's contradictory.

TV4Fun
Posts: 106
Joined: Mon Oct 01, 2007 5:45 am UTC
Location: Certifiable C++ Programmer

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

Postby TV4Fun » Mon Oct 15, 2007 12:35 pm UTC

I was convinved that it must've been a problem with my compiler. I tried 3 different compilers on 2 different machines before I noticed those extra semicolons. I was questioning my sanity for a little while, wondering why such a simple program refused to behave the way it was supposed to.
$_[0] wrote:rule 2:
Once a relationship ends, physical access to all relevant machinery is denied.

User avatar
Strilanc
Posts: 646
Joined: Fri Dec 08, 2006 7:18 am UTC

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

Postby Strilanc » Mon Oct 15, 2007 5:21 pm UTC

TV4Fun wrote:I was convinved that it must've been a problem with my compiler. I tried 3 different compilers on 2 different machines before I noticed those extra semicolons. I was questioning my sanity for a little while, wondering why such a simple program refused to behave the way it was supposed to.


Small hint: when it goes wrong like that, rewrite the lines. You'll overwrite any unnoticeables.
Don't pay attention to this signature, it's contradictory.

boss_mc
Posts: 47
Joined: Thu Oct 04, 2007 12:03 am UTC

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

Postby boss_mc » Sat Oct 20, 2007 12:03 am UTC

During converting some old javascript code to safeperl (MD5 Hashing), I managed to write this code:

Code: Select all

# Convert a string to an array of little-endian words
sub str2binl
{
  my $str = $_[0];
  my @hex_string = ();
  for ($i = 0; ($i*4) < length($str);$i++)
  {
    push(@hex_string,0);
    for ($j = 0; $j < 4 ;$j++)
    {
      $current_char = substr($str,($i*4)+$j,1);
      $hex_string[$i] |= (ord($current_char) & 0xFFFF) << [$j * 8];
    }
  }
  return @hex_string;
}


The answers returned were unexpected to say the least and, to add to the confusion, adding in print statements, newlines, comments etc actually changed the output. If you see the mistake and can explain how the 'shape' of the program could effect the changing of the output (go Randall) please do. I found the error eventually [Clue: _____ ] but still don't understand how it could have such an effect.

P.S. The array initialization and push statements were added to try and fix the problem, I'm sure they are not needed (I was thinking in C mode for a bit and was worried about memory mangling)

EDIT: Spelling
Last edited by boss_mc on Tue Oct 23, 2007 10:32 pm UTC, edited 1 time in total.
while ((*(iterator++) != (LExpression*)next) && (iterator != m_vector.end()){}

TV4Fun
Posts: 106
Joined: Mon Oct 01, 2007 5:45 am UTC
Location: Certifiable C++ Programmer

Re:

Postby TV4Fun » Tue Oct 23, 2007 4:04 am UTC

xkcd_n00bz wrote:Programming in C is for people who would rather sit at home and match up pairs of socks by the count of their elastic bands, than to just get dressed with mismatched shoes and take the lady out to dinner and nail her in the car on the way home.
Ok, that's going into my sig.
$_[0] wrote:rule 2:
Once a relationship ends, physical access to all relevant machinery is denied.

User avatar
Pesto
Posts: 737
Joined: Wed Sep 05, 2007 5:33 pm UTC
Location: Berkeley, CA

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

Postby Pesto » Wed Oct 24, 2007 5:27 pm UTC

Stupid query tool. GRR.

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

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

Postby Rysto » Fri Oct 26, 2007 10:12 pm UTC

Note to self: No kernel logging facility should ever, ever, trigger a context switch. At least not in this kernel.

Christ, I've spent days trying to track this down. And I can't even yell at somebody for it because I'm the idiot who knowingly had the logging code trigger the context switch.

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

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

Postby Berengal » Sat Oct 27, 2007 8:41 pm UTC

What the.... what?

Code: Select all

      System.out.print("Do you want to exit? (y/n)\n: ");
      keyboard.nextLine();
      char ans = keyboard.next().toLowerCase().charAt(0);
      while (ans != 'y'||ans!='n'){
         System.out.printf("Try again...(%d)(%d)(%d)\n: ",(int)ans,(int)'y',(int)'n');
         keyboard.nextLine();
         ans = keyboard.next().toLowerCase().charAt(0);
      }


This never exits the loop. As you can see I've used printf to try to debug. A sample run is as follows:
Do you want to exit? (y/n)
: y
Try again...(121)(121)(110)
: y
Try again...(121)(121)(110)
: n
Try again...(110)(121)(110)
: wtf
Try again...(119)(121)(110)
: argh!
Try again...(97)(121)(110)
:

I really hope this is caused by my own ignorance, because if it's some arcane workings of java I'm taking an axe to someone's skull.
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

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 » Sat Oct 27, 2007 8:47 pm UTC

Berengal, look at the condition in the loop. You have it wrong.

For a related problem, read this.

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

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

Postby Berengal » Sat Oct 27, 2007 9:10 pm UTC

D'oh!

The worst part about it is that I just solved this problem in a friend's program two days ago. I spent 10 minutes forcing the notion that !a or !b = a and b. So much for thinking through one's conditionals...
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

The Joe
Posts: 2
Joined: Fri Sep 14, 2007 10:17 pm UTC

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

Postby The Joe » Mon Oct 29, 2007 1:26 am UTC

Hey, I'm pretty new to java, and I was experimenting around, seeing what I could make. I was working on a little space invaders like game, except I could not get the keyboard events working.

link

The source, with all the class files are there. I didn't comment it out, but it seems self-explanatory.

Also, if I'm doing anything else wrong, with the basic structure, advice would be appreciated.

User avatar
Pesto
Posts: 737
Joined: Wed Sep 05, 2007 5:33 pm UTC
Location: Berkeley, CA

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

Postby Pesto » Tue Oct 30, 2007 7:16 pm UTC

Grr, I hate Access.

I have a query like this

Code: Select all

SELECT *
FROM (SELECT * FROM SomeTable) dtTable LEFT JOIN
AnotherTable ON dtTable.field = AnotherTable.field

Any time I do anything outside of the SQL view, Access changes the query to this.

Code: Select all

SELECT *
FROM [SELECT * FROM SomeTable]. dtTable LEFT JOIN
AnotherTable ON dtTable.field = AnotherTable.field

Then it says the syntax is wrong. THE VERY SYNTAX IT GENERATED ITSELF.

grr.

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

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

Postby mabufo » Thu Nov 01, 2007 11:02 pm UTC

Could someone help me figure out the logic problems in my homework assignment? I've been staring at this for a good long while now and for the life of me I can't figure it out. The thing compiles and runs, but it hangs. Could someone help me find the root of the trouble so I can fix it? I'm pretty sure the problem is in the 'night' method. I'm about an inch away from rewriting the method.

Spoiler tags to save space.
Spoiler:

Code: Select all

/**
 * Simulates a drunk man on a bridge.
 * The drunk guy starts in the middle of a 10 foot bridge and randomly moves left or right (with a maximum of 100 steps).
 * There will be 5 trials(nights), each returning the number of steps, and the direction of his exit.
 *
 * @author Matt young
 * @version 1
 */
import java.io.*; // for file IO
import java.util.Random; // for our random numbers

public class drunkFellow
{
    //variable declarations
    private String drunkName;
   
    //variables to do with our guy and the bridge
    private int night = 1;
    private int bridgePosition = 0;
    private int direction;
   
    /**
     * Constructor for objects of class drunkFellow
     * @param name The name of our drunk guy.
     */
    public drunkFellow(String name)
    {
        drunkName = name;
    }

    /**
     * Method to return the name of our drunk Friend.
     * @return drunkName
     */
    public String getDrunkName()
    {
        return drunkName;
    }
   
    /**
     * This method runs our simulation.
     *
     * @param night Must be 5 or less, because we only run 5 trials
     * @param bridgePosition This is where we start on the bridge, for our purposes, we start in the middle, which is 0.
     *
     * @return number of steps
     * @return (sets the direction variable, to indirectly return a second item)
     */
    public int night(int night, int bridgePosition)
    {
        int steps = 0;
     
            while (steps <= 99){               
                while ((bridgePosition != 5) || (bridgePosition != -5))
                {
                    //generate random number from (0 to 1) to see which way we move
                    //left is 0, and right is 1
                    Random generator = new Random();
                    int direction = generator.nextInt(2);
                   
                    //checks our direction, and updates the appropriate variables
                    //specifically, the number os steps, and our drunkard's position on the bridge.
                    if (direction == 0){
                        bridgePosition--;
                        steps++;
                    }
                    else{
                        bridgePosition++;
                        steps++;
                    };
                     
                }
               
                //block of code to figure out what we need to return
                if (bridgePosition == 5){
                    direction = 1;
                    return steps;
                }
                else{
                    direction = -1;
                    return steps;
                }
               
            }
            if (steps == 99){
                //the length of direction will be checked. Output will be based on the result of the length().
                direction = 0;
               
                //we need to return 100 steps so we can correctly figure the average.
                steps++;
               
            };
       
      return steps;
    }
   
    /**
     * Tests our class.
     */
    public static void main(String args[])
    {
        drunkFellow drunkGuy = new drunkFellow("Fredrick McDrunkpants");
        int totalSteps = 0;
       
       
        int night = 1;
        while (night <=5)
        {
            int steps = drunkGuy.night(night, 0);
           
            if (drunkGuy.direction == 0){
                System.out.println("Our drunk failed to cross the bridge on night number " + night + ".");
                totalSteps += steps;
            }
            else if (drunkGuy.direction == 1){
                System.out.println("Our drunk got to the Right side on night number " + night + " in only " + steps + " steps.");
                totalSteps += steps;
            }
            System.out.println("Our drunk got to the Left side on night number " + night + " in only " + steps + " steps.");
            totalSteps += steps;
           
        }
       
        System.out.println(drunkGuy.getDrunkName() + " took an average of " + (totalSteps / night) + " steps.");
       
    }
       
       
   
}



Thank you.

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

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

Postby Rysto » Fri Nov 02, 2007 12:00 am UTC

You never increment nights in your while loop in main().

Edit: And you shouldn't create a new Random() object in each iteration of the loop in your night() method. The best thing to do is create it once(as a static variable) and keep using it, next best is to create it in main() and pass it to your night() method, next best is to create it once in each call to night(). This won't cause an infinite loop but creating a new Random() object each time makes your random numbers non-random.

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

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

Postby Berengal » Fri Nov 02, 2007 3:55 am UTC

You also never use the "night" argument in the night method for anything. Maybe you thought it was supposed to increment here but forgot to implement it? If so, that won't work. Even if you change the value inside the method, this won't be reflected outside the method.

while (steps <= 99) won't exit until steps > 99, which means if (steps == 99) will never run.

System.out.println("Our drunk got to the Left side on night number " + night + " in only " + steps + " steps."); will always print, I think you may have forgotten an "else".

To fix the infinite loop, you could go either

Code: Select all

int night = ;
        while (night++ <5)

or

Code: Select all

for (int night = 1; night <= 5; night++)

or you could put a night++; on the end of the while block.
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

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

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

Postby Rysto » Fri Nov 02, 2007 2:56 pm UTC

"and" isn't a keyword in Java. Use &&

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

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

Postby Berengal » Fri Nov 02, 2007 4:40 pm UTC

And "&&" isn't a keyword in python... confusion abound.

I'm so pissed of at this stupid java assignement I've got right now. Using heaps of objects and junk, poor sorting methods etc. to do what I just did in less than 50 lines using only built-in methods (including comments). The worst part is it's just "$grep -r [profession]$ [filename] | sort -k 2 -o [output]" in the terminal. If they want us to do complex stuff, they should make complex tasks, not make us do this roundabout awkward way of doing something incredibly easy.
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

User avatar
Pesto
Posts: 737
Joined: Wed Sep 05, 2007 5:33 pm UTC
Location: Berkeley, CA

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

Postby Pesto » Fri Nov 02, 2007 5:46 pm UTC

Include all that in your code comments.

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

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

Postby Berengal » Sat Nov 03, 2007 4:04 am UTC

I did, sort of. I made a short program, the first few being:

Code: Select all

/**
 * Quick Regex Hack
 *
 * This is how I would've solved the assignement if there were no
 * ridiculous spesifications to how it should be done.
 *
 * This program does basically the same as
 * $grep -r [yrke]$ [filnamn] | sort -k 2 -o [utfil]
 *
 * I bet you I can do this in less than 50 lines of code and still
 * make it look nice.
 *
 * @author Berengal
 */
public class QRH {

For the record, it's 55 lines without the doc comment, 7 of which is the help string to be printed if the arguements are wrong, and it's all propperly formatted. Only funky thing I did was a labeled continue, but it's only 8 lines below the label anyway.
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.


Return to “Coding”

Who is online

Users browsing this forum: No registered users and 7 guests