As was foretold, we've added advertisements to the forums! If you have questions, or if you encounter any bugs, please visit this thread: https://forums.penny-arcade.com/discussion/240191/forum-advertisement-faq-and-reports-thread/
Options

PA Programming Thread - The Best Servers Are The Ones You Don't Use

The AnonymousThe Anonymous Uh, uh, uhhhhhh...Uh, uh.Registered User regular
10 PRINT "GOTO IS THE LIGHT."
20 GOTO 10
Alright, you know the drill. Discuss your favourite languages, programs, conundrums etc. etc.
YES I KNOW VB.NET, SHUT UP

The following was 100% shamelessly stolen from the last OP, because it's convenient and I'm too lazy to write my own from scratch. I make no apologies. Live with it.
Jasconius wrote:
Here's what I am working with these days in no important order:

Language: Python
Framework: Django
Purpose: Web Development++


Summary: Django is what PHP contributors wish for in their darkest dreams. Django provides intensely incredible functionality to generate small to medium data driven web applications in minutes. A pretty decent ORM provides a healthy layer of abstraction from database development and allows people who are most comfortable with a traditional scripting environment (read: me) to compete with that 14 year old from Slovenia who got a MySQL book for their birthday. I'm trying to close my first official Django development freelance contract this week.

Python is what it is. A simple, slick programming language with a light syntax and flexible rules that I think is a great language for new programmers. Python does everything including exploring Mars.

Other Links and Reading: http://djangobook.com/ && The Definitive Guide to Django, 2nd Edition

Language: Objective-C
Framework: Cocoa/UIKit
Purpose: iPhone/OS X development


Summary: Obj-C is a thin veneer over ANSI-C enabling OOP and other neat features. Cocoa is the framework upon which all depends when it comes to Mac development, much like Win32 for Windows. My feelings on Cocoa are mixed, the learning curve is steep. I am currently enjoying the tiny bit of abstraction it provides for OpenGL. I am developing an iPhone application for the retail chain I work in-house for, and I just got taken on as a contractor for an iPhone game developer.

Language: Actionscript 3
Framework: Flash
Purpose: Multimedia on the web


Summary: This got me a job, all my jobs really. Flash has evolved in the last decade from an annoying trend to an underground success in the world of RIA's thanks to Flex. ATG, the worlds leading eCommerce engine, just redid their entire commerce administration tool in Flex and I hear great things about it. Traditional Flash (what I do) is in steady decline as non-proprietary web technologies evolve and become mainstream, but with a high dollar creative team, nothing can compare for raw presentation value.

Other reading: GoToAndLearn.com
ASimPerson wrote: »
Language: C
Framework: Aahahahaha
Purpose: My job

Summary: C and its descendants (C++/Java/C#/etc.) are the most popular programming languages in the world. (As co-inventor Dennis Ritchie supposedly said, "C is quirky, flawed, and an enormous success.") The web browser you're using, the OS, most of your applications, most embedded software, the software on your router, the software on your ISP's router, the software on your game console, etc., were all written in C (well, or in C++).

For my job, I write in straight C. No libraries, no frameworks, no C++, no nothin'. C is a programming language for Real Men (tm), which means that there's no memory management and you're free to crash your program in various horrific ways. The trade-off for this is speed and size, attributes which give C its staying power - though proper C is losing favor as an application development language to C++, C#, and the like, it's found a second life in embedded applications and other small devices. I also think there's a certain elegance to the syntax - it's a language from an era when you didn't have a lot of memory, so statements are terse and lack the cruft of some more modern languages (*cough*C++*cough*). And best of all, no right minded C programmer would use LongVariableNamesLikeThis.

There's no shortage of manuals and documentation for the various incarnations of C, but the best reference is still from the source: The C Programming Language, by Kernighan and Ritchie. This book is so ubiquitous and standard that it's known simply as K&R in the field.
Language: Python
Framework: Pygame/PyOpenGL
Purpose: Game Development


Summary: Pygame is an extensive wrapper of the cross-platform SDL frameworks, specifically geared toward game development. Pygame takes care of loading assets, playing back sounds and music, drawing to the screen, handling keyboard and USB gamepad input, and can even capture live images from webcams on most platforms.

Pygame is also aware of PyOpenGL, the OpenGL binding for Python, and will gladly create a window complete with OpenGL context. Add 3 lines of code and suddenly you can make OpenGL drawing calls. No fuss.

Anyone with some knowledge of Python can create a working, playable 2D game demo in under a week. With minimal effort, this game will run on Windows, Mac OS X, or Linux, even the 3D bits, with no problems.

Other Links and Reading: http://www.pygame.org/news.html
Nightslyr wrote: »
Language: PHP
Framework: None (debating between CodeIgniter and Zend Framework)
Purpose: Web Development

PHP is probably the most ubiquitous server-side language around right now, although its been besieged by others on all sides. It's a simple, but bloated language, which suffers from a convoluted past and a stubborn refusal by the devs to trim the fat.

A lot of its popularity stems from how easy it is for newcomers to get results. This low barrier to entry, and PHP's ability to change from script blocks to blocks of HTML on the fly, means that there's a ton of shitty PHP code floating around out there.

Language: JavaScript
Framework: jQuery (looking for one a bit more complex to play with)
Purpose: Web Development

JavaScript is the most widely used programming language on the planet, and one of the most misunderstood. It doesn't behave like other languages, and this difference leads to confusion and frustration. It runs on the client (web browser), and can be turned off. Despite this, it's the driving force behind most of the interactive web apps out there today. Ever use Google Maps or GMail? Yeah, that's JavaScript.

When people talk about JavaScript development today, they tend to mean AJAX, which stands for Asynchronous JavaScript and XML. Essentially, this is a programming technique that allows portions of a web page to show new data without a complete page refresh. Again, look at Google's stuff for examples in action.

Language: C#
Framework: .NET 3.5
Purpose: Web Development (although it can be used for other purposes - see: XBOX 360 Indie Games)

C# is a managed OOP programming language. The managed part means that you don't need to worry about memory management (although you can still dabble with pointers and dynamic memory if you want). I like the language a lot, as it stresses readability (at least, more than PHP). When code is written correctly, its very easy to read, and seems almost self-evident. Beyond that, it just works.

The Anonymous on
«13456763

Posts

  • Options
    bowenbowen How you doin'? Registered User regular
    edited October 2010
    How dare you sully the programming thread with VB. You are unclean!

    bowen on
    not a doctor, not a lawyer, examples I use may not be fully researched so don't take out of context plz, don't @ me
  • Options
    Joe KJoe K Registered User regular
    edited October 2010
    with VB? I'm offended at the Hungarian Notation in the title . nyah. (hint: even msft reccomends against using it these days, and it was invented there)

    -- edit--
    JavaScript is the most widely used programming language on the planet

    you mean C. you definitely mean C.

    Joe K on
  • Options
    The AnonymousThe Anonymous Uh, uh, uhhhhhh... Uh, uh.Registered User regular
    edited October 2010
    bowen wrote: »
    How dare you sully the programming thread with VB. You are unclean!
    satan.jpg?1237491386

    The Anonymous on
  • Options
    JHunzJHunz Registered User regular
    edited October 2010
    I guess I sort of get what is being said, at least how exceptions relate to the basic routine where every failure point should simply end the whole thing and print an error message or something, since by using exceptions you can move as much error handling as possible out of the main path in much the same was as you would with a goto.

    However, what would you guys say if I have to call a bunch of methods that depend on each other, all of which throw the same kind of exception on failure, and I need to know exactly where the point of failure is so rollback actions may be taken? This pretty much forces exception handling or error checking on a line-by-line basis, which gets hella ugly using try catch for every little thing.
    Generally "rollback" tends to mean that you're doing things in a transaction and that you can just rollback that single transaction to get back to your starting point (which makes exception handling much easier. If you're just using it as a general term to describe getting back to your starting point, that's a little different (and uglier). You could still do something like store flags in some variable whenever you complete a step, and when an exception is encountered do your recovery based on what flags are set.
    Also, one big problem is the home-grown libraries I am working with don't report errors using exceptions, but by return value. So it forces you to very explicitly deal with the error when you write the method call.
    Yeah, but you can always throw your own exceptions if the return code indicates an error. That at least takes you to your common error handling code.
    On the other hand, sometimes you just want to do one thing and don't give a shit if it fails and writing a whole try/catch for that is just a huge PITA, and frequently it's unclear to me how much of the routine should be in the try block.
    The part of the routine that should be in the try block is the part from which you either want to handle or swallow the exceptions. If there won't be exceptions, you don't need a try block. If you want them to bubble up normally, you don't need a try block.

    JHunz on
    bunny.gif Gamertag: JHunz. R.I.P. Mygamercard.net bunny.gif
  • Options
    bowenbowen How you doin'? Registered User regular
    edited October 2010
    This is a completely retarded way to do this Igadzra, but, this may work for you in lieu of goto:
    int state = 0;
    boolean loop = true;
    boolean reversing = false;
    
    while(loop)
    {
        try
        {
            switch(state) {
                case 0:
                    //do 0
                    reversing == false ? state++ : state--;
                    break;
                case 1:
                    //do 1
                    reversing == false ? state++ : state--;
                    break;
                //etc, etc
                default:
                    loop = false;
                    break;       
            }
        } catch(exception ex) {
            //start going reverse
            reversing = true;
        }
    }
    
    

    That's about the only way I can think of to do anything similar to a goto statement. Pretty limited still, ugly as fuck, but, hopefully you get what I'm trying to do there.

    bowen on
    not a doctor, not a lawyer, examples I use may not be fully researched so don't take out of context plz, don't @ me
  • Options
    GnomeTankGnomeTank What the what? Portland, OregonRegistered User regular
    edited October 2010
    Answer from the last thread:
    I guess I sort of get what is being said, at least how exceptions relate to the basic routine where every failure point should simply end the whole thing and print an error message or something, since by using exceptions you can move as much error handling as possible out of the main path in much the same was as you would with a goto.

    However, what would you guys say if I have to call a bunch of methods that depend on each other, all of which throw the same kind of exception on failure, and I need to know exactly where the point of failure is so rollback actions may be taken? This pretty much forces exception handling or error checking on a line-by-line basis, which gets hella ugly using try catch for every little thing.

    Also, one big problem is the home-grown libraries I am working with don't report errors using exceptions, but by return value. So it forces you to very explicitly deal with the error when you write the method call.

    On the other hand, sometimes you just want to do one thing and don't give a shit if it fails and writing a whole try/catch for that is just a huge PITA, and frequently it's unclear to me how much of the routine should be in the try block.

    The answer is custom exceptions. You can create an exception class that takes that return value code, and throws something like a ThirdPartyLibraryException, which takes that code and passes it up the stack.

    You can also create custom exceptions for each section of code that needs to report unique error conditions. Or you can use built in exceptions that correctly describe the problem. I'm not super keen on Java exceptions, but in .NET we have exceptions like IOException, InvalidArgumentException, OutOfMemoryException and many more built in to the system.

    With try, you can chain catch's together with different exception names, like:
    try {
        // do stuff
    }
    catch(InvalidArgumentException iae) {
    }
    catch(OutOfMemoryException oome) {
    }
    catch(Exception ex) {
    }
    

    If the exception is an InvalidArgumentException, the first catch block will handle it. If it's an OutOfMemoryException, the second catch block handles it. All other exceptions that sub-class from Exception (which is everything in the Java/.NET world) will hit the third and final catch block.

    GnomeTank on
    Sagroth wrote: »
    Oh c'mon FyreWulff, no one's gonna pay to visit Uranus.
    Steam: Brainling, XBL / PSN: GnomeTank, NintendoID: Brainling, FF14: Zillius Rosh SFV: Brainling
  • Options
    bowenbowen How you doin'? Registered User regular
    edited October 2010
    Probably slightly less stupid than my way.

    bowen on
    not a doctor, not a lawyer, examples I use may not be fully researched so don't take out of context plz, don't @ me
  • Options
    urahonkyurahonky Registered User regular
    edited October 2010
    Alright gents I have a question. As usual.

    Now I'm given some .java files and a .jsp file. I need to edit these to create a .war file. Then I need to use this .war file in Eclipse to run against Tomcat to produce a servlet. Does this sound correct?

    How do I create a .war file? Do I use Apache Ant?

    urahonky on
  • Options
    bowenbowen How you doin'? Registered User regular
    edited October 2010
    urahonky wrote: »
    Alright gents I have a question. As usual.

    Now I'm given some .java files and a .jsp file. I need to edit these to create a .war file. Then I need to use this .war file in Eclipse to run against Tomcat to produce a servlet. Does this sound correct?

    How do I create a .war file? Do I use Apache Ant?

    http://www.java-tips.org/other-api-tips/eclipse/how-to-make-war-file-in-eclipse.html

    maybe that'll help.

    bowen on
    not a doctor, not a lawyer, examples I use may not be fully researched so don't take out of context plz, don't @ me
  • Options
    LoneIgadzraLoneIgadzra Registered User regular
    edited October 2010
    Holy jesus that link is outdated.

    What you will need is the Eclipse for Java EE developers and a dynamic web project with your source in it. Then right click on the project and Export > War File.
    urahonky wrote: »
    Alright gents I have a question. As usual.

    Now I'm given some .java files and a .jsp file. I need to edit these to create a .war file. Then I need to use this .war file in Eclipse to run against Tomcat to produce a servlet. Does this sound correct?

    How do I create a .war file? Do I use Apache Ant?

    No. A servlet is a class that handles an HTTP request in java. (JSP files get compiled into servlets behind the scenes.)

    A war file is literally just a jar file with a different suffix and a specific structure, which can be deployed on tomcat. (Creating a war to deploy to tomcat is not required though - in fact tomcat just immediately unarchives it anyway.) If you have your source code in an Eclipse dynamic web project you can then easily create a war file, but doing so from the command line is another valid and easy method if you have ever used the jar command or anything like it (e.g. tar).

    Web development with java is frustratingly complex and badly documented for a newcomer, so have patience and consider buying a book if you will need to do a lot of it.

    JSP may well be the worst template language conceived by man.

    LoneIgadzra on
  • Options
    LoneIgadzraLoneIgadzra Registered User regular
    edited October 2010
    And guys, thanks for going to all the trouble to explain exception syntax and semantics. Sadly I already understood that though. I have been working with Java and .NET for years now (much prefer .NET, too bad about the windows-only) and passed comp sci exams on the subject before that.

    My problem when using exceptions is just stylistic. Sometimes parts of a routine will throw lots of exceptions, sometimes a large part will be relatively safe - sometimes both will have to appear together in a routine and use the same variables so you are stuck either putting the whole thing in one try/catch block or separating them and using lots of checks and "progress" variables to determine what has been initialized further down the line. I just never really got what I was supposed to do - my instinct is to keep as much of the routine as possible outside of the try block so I can know exactly what threw the exception (as well as just plain keep the indent level low) but it just seems so cumbersome a lot of the time.

    Sometimes you need to separate try/catch blocks simply because you don't want any early exceptions killing execution of the whole routine by exiting into a catch block.

    If you ask me the whole idea is insanely messy, though maybe slightly better than goto for the specific situation where each line depends on the last and each could fail. (And yes I know about rollbacks in a transactional database.)

    LoneIgadzra on
  • Options
    bowenbowen How you doin'? Registered User regular
    edited October 2010
    I prefer the old "Figure out all possible cases of why this data could be bad before trying to do anything with it" route rather than exceptions. I find myself, as terrible as it is, just catching the general exception and saying "Something happened." and clean up what happens. Though, I've never had to rely on a finally or really critical information so I've probably been shielded from the giant pitfalls.

    bowen on
    not a doctor, not a lawyer, examples I use may not be fully researched so don't take out of context plz, don't @ me
  • Options
    urahonkyurahonky Registered User regular
    edited October 2010
    Holy jesus that link is outdated.

    What you will need is the Eclipse for Java EE developers and a dynamic web project with your source in it. Then right click on the project and Export > War File.
    urahonky wrote: »
    Alright gents I have a question. As usual.

    Now I'm given some .java files and a .jsp file. I need to edit these to create a .war file. Then I need to use this .war file in Eclipse to run against Tomcat to produce a servlet. Does this sound correct?

    How do I create a .war file? Do I use Apache Ant?

    No. A servlet is a class that handles an HTTP request in java. (JSP files get compiled into servlets behind the scenes.)

    A war file is literally just a jar file with a different suffix and a specific structure, which can be deployed on tomcat. (Creating a war to deploy to tomcat is not required though - in fact tomcat just immediately unarchives it anyway.) If you have your source code in an Eclipse dynamic web project you can then easily create a war file, but doing so from the command line is another valid and easy method if you have ever used the jar command or anything like it (e.g. tar).

    Web development with java is frustratingly complex and badly documented for a newcomer, so have patience and consider buying a book if you will need to do a lot of it.

    JSP may well be the worst template language conceived by man.

    Ahh okay. See I'm taking a Web Information Systems course and they didn't really explain it all that well. Their examples are easy and obvious.

    So basically what I need to do is use a java project to create some .java code and some .jsp code. Then from there I need to right click and export the java code to a war file. Then using this war file I run it on the Tomcat server? That sounds about right.

    urahonky on
  • Options
    InfidelInfidel Heretic Registered User regular
    edited October 2010
    I approve (yet again) of the topical thread.

    Infidel on
    OrokosPA.png
  • Options
    NightslyrNightslyr Registered User regular
    edited October 2010
    Can someone update my quote in the OP to .NET 4.0?

    Nightslyr on
  • Options
    Xenocide GeekXenocide Geek Registered User regular
    edited October 2010
    halp, good sirs! haaalp!

    i'm working on another java assignment, but this time it's dealing with a ShoppingCart application. the program consists of six files - an Item class, ItemOrder class, Catalog class, ShoppingCart class, ShoppingMain class, and ShoppingFrame class.

    now, last night i designed the item, itemorder, and catalog class all perfectly - i had the original program, and as i swapped my classes in for the originals, the program worked fine! but the ShoppingCart class is giving me some serious trouble, and i can't seem to wrap my head around what's goin' wrong

    i think the problem lay in my constructor creation, but for the life of me, i can't get it to work

    edit: i left the constructor in my shoppingcart class blank, i had something else there that wasn't functioning before

    shoppingcart.class
    import java.util.*;
    
    public class ShoppingCart {
        //instance variables
        
        private ItemOrder itemO;
        private double totalCost;
        ArrayList<ItemOrder> shoppingCart = new ArrayList<ItemOrder>();
        
        //constructors
        
        
        
        //methods
        public void add(ItemOrder o) {
              shoppingCart.add(o);
            
        }
        
        public void setDiscount(boolean value) {
               if (value == true) {
                    totalCost = itemO.getPrice() * .10 - itemO.getPrice();
                   
                } else if (value == false) {
                    totalCost = itemO.getPrice();
                    
                }
                   
                
        }
    
        public double getTotal() {
            return totalCost;
            
        }
    }
    
    

    for reference, here are the other files
    public class Item {
        //instance variables
        private String name;
        private double price;
        private int bulkQuantity;
        private double bulkPrice;
        
        //constructors
        
        public Item(String x, double y) {
            if (price < 0) {
                throw new IllegalArgumentException();
            } else {
                this.name = x;
                this.price = y;              
            }        
        }
        
        public Item(String x, double y, int q, double bp) {
            
            if  ((y < 0) || (q < 0) || (bp < 0)) {
                throw new IllegalArgumentException();
            } else {
                name = x;
                price = y;
                bulkQuantity = q;
                bulkPrice = bp;
            }
                
        
        }
    
        //methods
        
        public double priceFor(int bulkQuantity) {
            if (bulkQuantity < 0) {
                throw new IllegalArgumentException();
            } else if (bulkQuantity >= 10) {
                price = price * .5;
                return price * bulkQuantity;
                
            } else {
                return price * bulkQuantity;
            
        }
      }
        public String toString() {
            return name + "," + " " + price;
            
        }
      
    
    }
    
    public class ItemOrder
    {
        // instance variables
        private Item item;
        private int quantity;
        
        //constructors
        
        public ItemOrder(Item a, int b) {
            item = a;
            quantity = b;
            
        }
       
    
        public double getPrice() {
           return item.priceFor(quantity);
           
        }
    
        public Item getItem() {
            return item;
        }
        
    }
    
    
    import java.util.*;
    
    public class Catalog {
        
        //instance variables
        private String name;    
        private ArrayList<Item> catalog = new ArrayList<Item>();
        
        //constructors
       public Catalog(String a) {
           name = a;      
           
        }
        
        //methods
        public void add(Item item) { 
            catalog.add(item);
            
        }
    
        public int size() {
            return catalog.size();
            
        }
    
        public Item get(int index) {
            return catalog.get(index);      
            
        }
    
        public String getName() {
            return name;
     
        }
    }
    
    
    // Sets up the "discount" checkbox for the frame
        private JPanel makeCheckBoxPanel() {
            JPanel p = new JPanel();
            p.setBackground(Color.blue);
            final JCheckBox cb = new JCheckBox("qualify for discount");
            p.add(cb);
            cb.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    items.setDiscount(cb.isSelected());
                    updateTotal();
                }
            });
            return p;
        }
    
        // adds a product to the panel, including a textfield for user input of
        // the quantity
        private void addItem(final Item product, JPanel p) {
            JPanel sub = new JPanel(new FlowLayout(FlowLayout.LEFT));
            sub.setBackground(new Color(0, 180, 0));
            final JTextField quantity = new JTextField(3);
            quantity.setHorizontalAlignment(SwingConstants.CENTER);
            quantity.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    updateItem(product, quantity);
                    quantity.transferFocus();
                }
            });
            quantity.addFocusListener(new FocusAdapter() {
                public void focusLost(FocusEvent e) {
                    updateItem(product, quantity);
                }
            });
            sub.add(quantity);
            JLabel l = new JLabel("" + product);
            l.setForeground(Color.white);
            sub.add(l);
            p.add(sub);
        }
    
        // When the user types a new value into one of the quantity fields,
        // parse the input and update the ShoppingCart.  Display an error
        // message if text is not a number or is negative.
        private void updateItem(Item product, JTextField quantity) {
            int number;
            String text = quantity.getText().trim();
            try {
                number = Integer.parseInt(text);
            } catch (NumberFormatException error) {
                number = 0;
            }
            if (number <= 0 && text.length() > 0) {
                Toolkit.getDefaultToolkit().beep();
                quantity.setText("");
                number = 0;
            }
            items.add(new ItemOrder(product, number));
            updateTotal();
        }
    
        // reset the text field for order total
        private void updateTotal() {
            double amount = items.getTotal();
            total.setText(NumberFormat.getCurrencyInstance().format(amount));
        }
    }
    
    
    
    // ShoppingMain provides method main for a simple shopping program.
    
    public class ShoppingMain {
        public static void main() {
            Catalog list = new Catalog("CS Gift Catalog");
            list.add(new Item("silly putty", 3.95, 10, 19.99));
            list.add(new Item("silly string", 3.50, 10, 14.95));
            list.add(new Item("bottle o bubbles", 0.99));
            list.add(new Item("Nintendo Wii system", 389.99));
            list.add(new Item("Mario Computer Science Party 2 (Wii)", 49.99));
            list.add(new Item("Don Knuth Code Jam Challenge (Wii)", 49.99));
            list.add(new Item("Computer Science pen", 3.40));
            list.add(new Item("Rubik's cube", 9.10));
            list.add(new Item("Computer Science Barbie", 19.99));
            list.add(new Item("'Java Rules!' button", 0.99, 10, 5.0));
            list.add(new Item("'Java Rules!' bumper sticker", 0.99, 20, 8.95));
    
            ShoppingFrame f = new ShoppingFrame(list);
            f.setVisible(true);
        }
    }
    
    

    Xenocide Geek on
    i wanted love, i needed love
    most of all, most of all
    someone said true love was dead
    but i'm bound to fall
    bound to fall for you
    oh what can i do
  • Options
    Joe KJoe K Registered User regular
    edited October 2010
    what does the public and private interface to ShoppingCartClass look like? The original one, i mean. Have you implemented the API correctly?

    Joe K on
  • Options
    JHunzJHunz Registered User regular
    edited October 2010
    Perhaps you could actually tell us what's going wrong so we don't have to stick all that in a compiler to figure out what we're looking for?

    From just looking at it, you're determining pricing from the itemO variable, but never actually initializing it because you're actually adding the orders to your ArrayList. Also, even if that was working you'd be returning negative prices.

    JHunz on
    bunny.gif Gamertag: JHunz. R.I.P. Mygamercard.net bunny.gif
  • Options
    Monkey Ball WarriorMonkey Ball Warrior A collection of mediocre hats Seattle, WARegistered User regular
    edited October 2010
    halp, good sirs! haaalp!

    i'm working on another java assignment, but this time it's dealing with a ShoppingCart application. the program consists of six files - an Item class, ItemOrder class, Catalog class, ShoppingCart class, ShoppingMain class, and ShoppingFrame class.

    now, last night i designed the item, itemorder, and catalog class all perfectly - i had the original program, and as i swapped my classes in for the originals, the program worked fine! but the ShoppingCart class is giving me some serious trouble, and i can't seem to wrap my head around what's goin' wrong

    i think the problem lay in my constructor creation, but for the life of me, i can't get it to work

    edit: i left the constructor in my shoppingcart class blank, i had something else there that wasn't functioning before

    shoppingcart.class
    import java.util.*;
    
    public class ShoppingCart {
        //instance variables
        
        private ItemOrder itemO;
        private double totalCost;
        ArrayList<ItemOrder> shoppingCart = new ArrayList<ItemOrder>();
        
        //constructors
        
        
        
        //methods
        public void add(ItemOrder o) {
              shoppingCart.add(o);
            
        }
        
        public void setDiscount(boolean value) {
               if (value == true) {
                    totalCost = itemO.getPrice() * .10 - itemO.getPrice();
                   
                } else if (value == false) {
                    totalCost = itemO.getPrice();
                    
                }
                   
                
        }
    
        public double getTotal() {
            return totalCost;
            
        }
    }
    
    

    for reference, here are the other files
    public class Item {
        //instance variables
        private String name;
        private double price;
        private int bulkQuantity;
        private double bulkPrice;
        
        //constructors
        
        public Item(String x, double y) {
            if (price < 0) {
                throw new IllegalArgumentException();
            } else {
                this.name = x;
                this.price = y;              
            }        
        }
        
        public Item(String x, double y, int q, double bp) {
            
            if  ((y < 0) || (q < 0) || (bp < 0)) {
                throw new IllegalArgumentException();
            } else {
                name = x;
                price = y;
                bulkQuantity = q;
                bulkPrice = bp;
            }
                
        
        }
    
        //methods
        
        public double priceFor(int bulkQuantity) {
            if (bulkQuantity < 0) {
                throw new IllegalArgumentException();
            } else if (bulkQuantity >= 10) {
                price = price * .5;
                return price * bulkQuantity;
                
            } else {
                return price * bulkQuantity;
            
        }
      }
        public String toString() {
            return name + "," + " " + price;
            
        }
      
    
    }
    
    public class ItemOrder
    {
        // instance variables
        private Item item;
        private int quantity;
        
        //constructors
        
        public ItemOrder(Item a, int b) {
            item = a;
            quantity = b;
            
        }
       
    
        public double getPrice() {
           return item.priceFor(quantity);
           
        }
    
        public Item getItem() {
            return item;
        }
        
    }
    
    
    import java.util.*;
    
    public class Catalog {
        
        //instance variables
        private String name;    
        private ArrayList<Item> catalog = new ArrayList<Item>();
        
        //constructors
       public Catalog(String a) {
           name = a;      
           
        }
        
        //methods
        public void add(Item item) { 
            catalog.add(item);
            
        }
    
        public int size() {
            return catalog.size();
            
        }
    
        public Item get(int index) {
            return catalog.get(index);      
            
        }
    
        public String getName() {
            return name;
     
        }
    }
    
    
    // Sets up the "discount" checkbox for the frame
        private JPanel makeCheckBoxPanel() {
            JPanel p = new JPanel();
            p.setBackground(Color.blue);
            final JCheckBox cb = new JCheckBox("qualify for discount");
            p.add(cb);
            cb.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    items.setDiscount(cb.isSelected());
                    updateTotal();
                }
            });
            return p;
        }
    
        // adds a product to the panel, including a textfield for user input of
        // the quantity
        private void addItem(final Item product, JPanel p) {
            JPanel sub = new JPanel(new FlowLayout(FlowLayout.LEFT));
            sub.setBackground(new Color(0, 180, 0));
            final JTextField quantity = new JTextField(3);
            quantity.setHorizontalAlignment(SwingConstants.CENTER);
            quantity.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    updateItem(product, quantity);
                    quantity.transferFocus();
                }
            });
            quantity.addFocusListener(new FocusAdapter() {
                public void focusLost(FocusEvent e) {
                    updateItem(product, quantity);
                }
            });
            sub.add(quantity);
            JLabel l = new JLabel("" + product);
            l.setForeground(Color.white);
            sub.add(l);
            p.add(sub);
        }
    
        // When the user types a new value into one of the quantity fields,
        // parse the input and update the ShoppingCart.  Display an error
        // message if text is not a number or is negative.
        private void updateItem(Item product, JTextField quantity) {
            int number;
            String text = quantity.getText().trim();
            try {
                number = Integer.parseInt(text);
            } catch (NumberFormatException error) {
                number = 0;
            }
            if (number <= 0 && text.length() > 0) {
                Toolkit.getDefaultToolkit().beep();
                quantity.setText("");
                number = 0;
            }
            items.add(new ItemOrder(product, number));
            updateTotal();
        }
    
        // reset the text field for order total
        private void updateTotal() {
            double amount = items.getTotal();
            total.setText(NumberFormat.getCurrencyInstance().format(amount));
        }
    }
    
    
    
    // ShoppingMain provides method main for a simple shopping program.
    
    public class ShoppingMain {
        public static void main() {
            Catalog list = new Catalog("CS Gift Catalog");
            list.add(new Item("silly putty", 3.95, 10, 19.99));
            list.add(new Item("silly string", 3.50, 10, 14.95));
            list.add(new Item("bottle o bubbles", 0.99));
            list.add(new Item("Nintendo Wii system", 389.99));
            list.add(new Item("Mario Computer Science Party 2 (Wii)", 49.99));
            list.add(new Item("Don Knuth Code Jam Challenge (Wii)", 49.99));
            list.add(new Item("Computer Science pen", 3.40));
            list.add(new Item("Rubik's cube", 9.10));
            list.add(new Item("Computer Science Barbie", 19.99));
            list.add(new Item("'Java Rules!' button", 0.99, 10, 5.0));
            list.add(new Item("'Java Rules!' bumper sticker", 0.99, 20, 8.95));
    
            ShoppingFrame f = new ShoppingFrame(list);
            f.setVisible(true);
        }
    }
    
    

    I'm in that course, except I'm at the UW-Tacoma, and I think you're probably at the UW proper. Programming Practicum (CSS305)?

    Also mine was simpler, we were only responsible for Item, ItemOrder, and ShoppingCart. Which is upsetting because I was under the impression they taught exactly the same things here and there.

    Also we have plugins out the ass complaining about "magic numbers" like .10 (which should be a constant) and making references to implementations instead of interfaces, such that we would have to write:
    private final List<ItemOrder> cartContents = new ArrayList<ItemOrder>();
    

    Remember that final doesn't mean the contents can't change, just that you can't reassign it. My professor has a mancrush on final.

    It's generally a bad idea to call a variable something that is also a class, especially if it's not even an instance of that class.

    Why do you have an itemOrder field in ShoppingCart? You only use it in setDiscount, so you should just have it as a local variable.

    Do you know about enhanced for loops? Anything that implements the Iterable interface (like Lists and Sets) can be used like this:
    double price = 0.0;
    for (ItemOrder order : cartContents) {
        price += order.getPrice();
    }
    

    I also assume your professor mentioned that, generally, using doubles for currency is a horrible idea. We did it anyway in this assignment, but that disclaimer is very important. I ended up having to use Math.round() a lot because my unit test tested values and they were often off by $0.000000000001. Annoyances!

    Monkey Ball Warrior on
    "I resent the entire notion of a body as an ante and then raise you a generalized dissatisfaction with physicality itself" -- Tycho
  • Options
    urahonkyurahonky Registered User regular
    edited October 2010
    Okay... So does anyone know why my "Export -> WAR file" doesn't work anymore? It worked last night. I closed Eclipse, now when I open it and click on the export to WAR everything on the next window is blank.

    Nothing is showing up under Web Project or Project Destination. Adding anything to it does nothing but tells me the module name is wrong.

    Fucking Eclipse.

    urahonky on
  • Options
    urahonkyurahonky Registered User regular
    edited October 2010
    So apparently it won't export to a WAR file unless there is an open Web Project in your workbench? Then I am running into another issue... My class gave me a skeleton of the project... But it's not loading as a Web Project. It's loading as a normal Java Project, which means it won't let me export it or something.

    Jesus Christ..... I don't know what I'm doing.

    urahonky on
  • Options
    Joe KJoe K Registered User regular
    edited October 2010
    urahonky wrote: »
    So apparently it won't export to a WAR file unless there is an open Web Project in your workbench? Then I am running into another issue... My class gave me a skeleton of the project... But it's not loading as a Web Project. It's loading as a normal Java Project, which means it won't let me export it or something.

    Jesus Christ..... I don't know what I'm doing.

    that's, why your taking the class mang....

    Joe K on
  • Options
    urahonkyurahonky Registered User regular
    edited October 2010
    Joe K wrote: »
    urahonky wrote: »
    So apparently it won't export to a WAR file unless there is an open Web Project in your workbench? Then I am running into another issue... My class gave me a skeleton of the project... But it's not loading as a Web Project. It's loading as a normal Java Project, which means it won't let me export it or something.

    Jesus Christ..... I don't know what I'm doing.

    that's, why your taking the class mang....

    That's the thing. He hasn't taught us how to do this kind of stuff. He demoed it but it was basically all loaded up and running already beforehand. Never from scratch.

    Oh well. Seems like I'm not the only one having issues as my inbox was flooded with emails this morning.

    urahonky on
  • Options
    urahonkyurahonky Registered User regular
    edited October 2010
    Though I guess I can't complain. I'm sure when I get a job this situation will exist and I'll have to figure it out on my own... It's just I don't feel my skills are quite up to par for that sort of thing.

    urahonky on
  • Options
    kdrudykdrudy Registered User regular
    edited October 2010
    urahonky wrote: »
    Though I guess I can't complain. I'm sure when I get a job this situation will exist and I'll have to figure it out on my own... It's just I don't feel my skills are quite up to par for that sort of thing.

    Well, you'll have to figure it out if you're the only one doing it, otherwise you figure out the best person to ask and have them show ya, but it never hurts learning the best way to figure that kind of stuff out. Google is very much your friend.

    kdrudy on
    tvsfrank.jpg
  • Options
    Joe KJoe K Registered User regular
    edited October 2010
    urahonky wrote: »
    Though I guess I can't complain. I'm sure when I get a job this situation will exist and I'll have to figure it out on my own... It's just I don't feel my skills are quite up to par for that sort of thing.

    a company that i worked at, we used to joke that you would go away for lunch, and there would be a new piece of hardware, or a new software package to make work with our base product. hey - quick learn XXX and then fix the driver for this.... or quick learn this odd scripting language for this ancient emulator. the weirdest was the airline ticket printer that appeared one day. typed the part number into google and found NOTHING. knew that was going to be good times. Or the old token ring. Or the 10BASE2 for the US Navy. and this was in modern times :-)

    i'm betting that everything for eclipse and WAR files creation and integration is fairly google'able...

    Joe K on
  • Options
    bowenbowen How you doin'? Registered User regular
    edited October 2010
    That sounds like my old job Joe K. My boss literally had mountains of equipment dating back to the 80s that he kept laying around Just in Case!. We used a stick of ram to restore an old server that weighed probably close to 200 lbs. Once.

    And then a new guy started working there and went to go fix a router wire in that back room and the whole fucking junk pile fell on him and he had to get stitches. I'm surprised he didn't die. There was probably roughly 2000 lbs of equipment in that pile.

    bowen on
    not a doctor, not a lawyer, examples I use may not be fully researched so don't take out of context plz, don't @ me
  • Options
    Jimmy KingJimmy King Registered User regular
    edited October 2010
    Referring back to http://forums.penny-arcade.com/showpost.php?p=16910828&postcount=2454 about the Critter interface, are you sure your teacher does not want you to just create an Interface called Critter and then create classes for each animal which implement the Critter interface? This is more true to OO code and design and far less ass backwards than a solitary class with a bunch of if/then stuff for each animal.

    Jimmy King on
  • Options
    LoneIgadzraLoneIgadzra Registered User regular
    edited October 2010
    urahonky wrote: »
    Joe K wrote: »
    urahonky wrote: »
    So apparently it won't export to a WAR file unless there is an open Web Project in your workbench? Then I am running into another issue... My class gave me a skeleton of the project... But it's not loading as a Web Project. It's loading as a normal Java Project, which means it won't let me export it or something.

    Jesus Christ..... I don't know what I'm doing.

    that's, why your taking the class mang....

    That's the thing. He hasn't taught us how to do this kind of stuff. He demoed it but it was basically all loaded up and running already beforehand. Never from scratch.

    Oh well. Seems like I'm not the only one having issues as my inbox was flooded with emails this morning.

    For the former, duh. You export a web project as a war file, which tomcat loads as an application.

    For the latter, what you want to do is create an empty dynamic web project and import the pre-written source into it. Of course getting eclipse to import in exactly the way you want is such a huge pain it's probably easier to manually copy the source into the appropriate project sub-directory using Explorer and right click project > refresh in eclipse.

    Let me see if I can enlighten you a little bit (you could figure this out on your own from messing around for five seconds and just taking a deep breath and looking at what's going on with a little more patience, less panic - java web is a bitch):

    When you create a dynamic web project using default settings in Eclipse, two folders are created in the project directory: "src" and "WebContent".

    "src" contains the source code for your java classes. "WebContent" contains everything else and is, quite literally, the underlying folder structure of your web site. One folder is of particular interest to you: WEB-INF. Hopefully your course has covered the contents of this folder as they are critical. Basically what you need to know is, when you export the war file, Eclipse just copies your compiled classes into WEB-INF/classes and bundles the contents of WebContent into a jar (except with .war on the end).

    This can also be done easily from the command line.

    LoneIgadzra on
  • Options
    JasconiusJasconius sword criminal mad onlineRegistered User regular
    edited October 2010
    hahahaha


    java

    Jasconius on
  • Options
    urahonkyurahonky Registered User regular
    edited October 2010
    You're right LoneIgadzra, I just needed to take a minute to collect myself. Supposedly I'm doing it right now.

    Use Eclipse to modify the .java and .jsp file. Then I use Ant to convert the project to a .WAR file, then use Tomcat to display everything I need.

    If he had written that into the assignment directions I would have not wasted many hours of my life trying to figure out what he wants.

    urahonky on
  • Options
    KakodaimonosKakodaimonos Code fondler Helping the 1% get richerRegistered User regular
    edited October 2010
    But then you'll be ready for dealing with the customers. Vague and conflicting directions are part of the fun when you're working with real end users.

    Kakodaimonos on
  • Options
    EndEnd Registered User regular
    edited October 2010
    Yeah, often enough, clients actually don't really know what they want.

    End on
    I wish that someway, somehow, that I could save every one of us
    zaleiria-by-lexxy-sig.jpg
  • Options
    urahonkyurahonky Registered User regular
    edited October 2010
    Okay, true. HOWEVER. At least you are getting paid to do it. :)

    urahonky on
  • Options
    bowenbowen How you doin'? Registered User regular
    edited October 2010
    urahonky wrote: »
    Okay, true. HOWEVER. At least you are getting paid to do it. :)

    How much work have you done in the field?

    Customers will fight tooth and nail against paying for updates. Or changes. They think because bugfixes are included that "Oh this isn't how I wanted it" is a bug or "Yeah I want to expand upon this" is a bug because that's not how they originally detailed it and it's not how it should work.

    This is also why you should always take 50% of the project funds up front before working on anything. They're more reluctant to be geese turds about it.

    bowen on
    not a doctor, not a lawyer, examples I use may not be fully researched so don't take out of context plz, don't @ me
  • Options
    urahonkyurahonky Registered User regular
    edited October 2010
    bowen wrote: »
    urahonky wrote: »
    Okay, true. HOWEVER. At least you are getting paid to do it. :)

    How much work have you done in the field?

    Customers will fight tooth and nail against paying for updates. Or changes. They think because bugfixes are included that "Oh this isn't how I wanted it" is a bug or "Yeah I want to expand upon this" is a bug because that's not how they originally detailed it and it's not how it should work.

    This is also why you should always take 50% of the project funds up front before working on anything. They're more reluctant to be geese turds about it.

    I suppose I mean I wouldn't be the one talking with customers. I'd be the one that works on the project after the boss figures out the money.

    And I have zero experience in the field, which is why I feel really bad about my skills.

    urahonky on
  • Options
    Lux782Lux782 Registered User regular
    edited October 2010
    urahonky wrote: »
    bowen wrote: »
    urahonky wrote: »
    Okay, true. HOWEVER. At least you are getting paid to do it. :)

    How much work have you done in the field?

    Customers will fight tooth and nail against paying for updates. Or changes. They think because bugfixes are included that "Oh this isn't how I wanted it" is a bug or "Yeah I want to expand upon this" is a bug because that's not how they originally detailed it and it's not how it should work.

    This is also why you should always take 50% of the project funds up front before working on anything. They're more reluctant to be geese turds about it.

    I suppose I mean I wouldn't be the one talking with customers. I'd be the one that works on the project after the boss figures out the money.

    And I have zero experience in the field, which is why I feel really bad about my skills.

    The great thing about programming is there are a ton of resources out there that detail issues people have. Most people don't bother to read them and have to re-invent the wheel however if you take the time to understand how to create a good design, what the pitfalls of each design pattern are and how to avoid them, then you are in a good position. Then its all about sticking with it no matter how long it takes or how your boss pressures you.

    The truth is you will regret rushing the project and just throwing it together. It will bite you in the ass and the best way to avoid that is thinking. Come up with high level ideas of how the software will interact with other pieces or software (or other sections of the same piece of software) and just work your way down. If you do code make sure not to tell your boss because they will think a prototype is something that can be sold. Writing code is like writing a book, slow and under constant revision.

    Lux782 on
  • Options
    KakodaimonosKakodaimonos Code fondler Helping the 1% get richerRegistered User regular
    edited October 2010
    urahonky wrote: »
    bowen wrote: »
    urahonky wrote: »
    Okay, true. HOWEVER. At least you are getting paid to do it. :)

    How much work have you done in the field?

    Customers will fight tooth and nail against paying for updates. Or changes. They think because bugfixes are included that "Oh this isn't how I wanted it" is a bug or "Yeah I want to expand upon this" is a bug because that's not how they originally detailed it and it's not how it should work.

    This is also why you should always take 50% of the project funds up front before working on anything. They're more reluctant to be geese turds about it.

    I suppose I mean I wouldn't be the one talking with customers. I'd be the one that works on the project after the boss figures out the money.

    And I have zero experience in the field, which is why I feel really bad about my skills.

    Hah. Once there's an issue, you'll be talking to the customers. My favorite was watching one of our guys working with the desk trader to fix something.

    Trader: "This isn't right."
    Dev: "Well, what's wrong with it?"
    T: "Look at it, it isn't right."
    Dev: "Right, what's the problem."
    T: "It's not right."
    Dev: "I know it's not right, why is it not right?"
    T: "Just look at it. Those numbers aren't right."
    Dev: "Why are the numbers not right?"
    T: "The values are wrong."
    Dev: "Why are the values wrong?"
    T: "The class delta isn't right."

    and so on. Until they finally figured out that it was an incorrect option value. But it took the junior dev 15 minutes sitting with the trader to find out why the trader didn't like the values.

    And your boss won't know what to do, he'll just agree to whatever gets the company the contract and money.

    Kakodaimonos on
  • Options
    bowenbowen How you doin'? Registered User regular
    edited October 2010
    Yeah it comes back to you when you're asked to quote how long a project will take though. If you're good at quoting out, then, you're golden.

    My advice to you is always quote in some "workflow resolution" time into your quote so you and the client can sit down and hash out the beat product and how they think it should be. Oh yeah, when you make your quotes, give yourself at least 25% more time than you think.

    I don't think I've really seen your coding honky, but I doubt you're as bad as you think you are. I've seen some really terrible coders. And I doubt you're one of them. My ultimate advice to you is be confident in your skills. And be confident in your expertise. Also I'd rather have a new guy ask how we do something than try to figure it out on their own and screw something up.

    You probably didn't need to hear any of that but I thought maybe a little prep talk would help you.

    bowen on
    not a doctor, not a lawyer, examples I use may not be fully researched so don't take out of context plz, don't @ me
  • Options
    bowenbowen How you doin'? Registered User regular
    edited October 2010
    What's that you say? Your file based database program locked up because 20 people were all writing at the same time? You don't say.

    What the fuck do you want me to do about it? Watch it?

    bowen on
    not a doctor, not a lawyer, examples I use may not be fully researched so don't take out of context plz, don't @ me
This discussion has been closed.