Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
If you're working on Enterprise Software you should call them accessors and mutators so you don't have trouble convincing anyone in management you're worth your absurd consulting rate.

Adbot
ADBOT LOVES YOU

Volmarias
Dec 31, 2002

EMAIL... THE INTERNET... SEARCH ENGINES...

Internet Janitor posted:

If you're working on Enterprise Software you should call them accessors and mutators so you don't have trouble convincing anyone in management you're worth your absurd consulting rate.

POJOs :yayclod:

1337JiveTurkey
Feb 17, 2005

Internet Janitor posted:

If you're working on Enterprise Software you should call them accessors and mutators so you don't have trouble convincing anyone in management you're worth your absurd consulting rate.

If you're telling anyone with the authority to sign checks anything more concrete than saying that they provide a value proposition to increase the IRR across the organization, you're doing it wrong.

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
Down with accessors! All fields are public final, and your class includes a builder subclass which can only be accessed by calling the public static builder() method.

Chas McGill
Oct 29, 2010

loves Fat Philippe
Is Swing worth checking out or is there a better alternative for simple UI stuff? I've been making a text based game as a project and I'd like to move beyond the console so I can have buttons to click on etc. I'm not planning on adding actual graphics or animation at the moment.

Alternatively, I'm also thinking of trying out Eclipse and the Android dev stuff, which I assume has its own UI bits that I could use.

Chas McGill fucked around with this message at 10:21 on Apr 8, 2014

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."
https://netbeans.org/‎ though. (I mean, yes, I recommend Swing.) New project -> new swing form -> text area and button -> right click on button -> events -> action -> action performed -> textArea.setText("This is an interactive program where you can click a button.\nAnd you did.\nHappy now?");

Edit: And what I actually came here to ask is, is there a way to add that nice menu big programs in Windows 7 have, where you can right-click it in the task bar and it gives custom actions? (And also the name of the program; mine just shows "Close window" :()

supermikhail fucked around with this message at 11:34 on Apr 8, 2014

Volguus
Mar 3, 2009

Chas McGill posted:

Is Swing worth checking out or is there a better alternative for simple UI stuff? I've been making a text based game as a project and I'd like to move beyond the console so I can have buttons to click on etc. I'm not planning on adding actual graphics or animation at the moment.

Alternatively, I'm also thinking of trying out Eclipse and the Android dev stuff, which I assume has its own UI bits that I could use.

They kinda let Swing rot. JavaFX is the "new" shiny UI library for java. Included in jdk 1.8.

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."
Oh, well. Back to school, I guess.

Jose Cuervo
Aug 25, 2004

JingleBells posted:

Pure code style - there's no difference as there's no other ID variable in scope.

If you have a class like this:

Java code:
public class Junction {

	private int ID;	

	public int getID() {
		return ID;
	}
	public void setID(int ID) {
		this.ID = ID;
	}
}
Then in the setID method ID refers to the parameter being passed in while this.ID refers to the private variable which the Junction object owns. Note I've had to change the case of the setID parameter as variable are case sensitive - in your example setID could easily just be:

Java code:
public void setID(int id) {
    ID = id;
}

Thanks for the clarification (to you and everyone else that answered). I will stick to using 'this' because it helps me distinguish when I use a class variable.

As far as Volmarias comments - I am not working on Enterprise software, just trying to modify / build on someone else's code for the first time, and doesn't the code already use getters and setters?

WHERE MY HAT IS AT
Jan 7, 2011

supermikhail posted:

https://netbeans.org/‎ though. (I mean, yes, I recommend Swing.) New project -> new swing form -> text area and button -> right click on button -> events -> action -> action performed -> textArea.setText("This is an interactive program where you can click a button.\nAnd you did.\nHappy now?");

Edit: And what I actually came here to ask is, is there a way to add that nice menu big programs in Windows 7 have, where you can right-click it in the task bar and it gives custom actions? (And also the name of the program; mine just shows "Close window" :()

The term you're looking for is jump-list, looks like there's maybe a library for it? I don't know, I'm not a java programmer.
http://stackoverflow.com/questions/3782282/making-a-windows-7-jump-list-in-java

Edit: looks like that lib costs money, but at least now you know what to search for, I guess

Volmarias
Dec 31, 2002

EMAIL... THE INTERNET... SEARCH ENGINES...

Jose Cuervo posted:

Thanks for the clarification (to you and everyone else that answered). I will stick to using 'this' because it helps me distinguish when I use a class variable.

As far as Volmarias comments - I am not working on Enterprise software, just trying to modify / build on someone else's code for the first time, and doesn't the code already use getters and setters?

I was just pointing out that the style depends on your environment and the established convention. If the convention in the codebase is to directly access member variables, go for it.

Chas McGill
Oct 29, 2010

loves Fat Philippe

supermikhail posted:

https://netbeans.org/‎ though. (I mean, yes, I recommend Swing.) New project -> new swing form -> text area and button -> right click on button -> events -> action -> action performed -> textArea.setText("This is an interactive program where you can click a button.\nAnd you did.\nHappy now?");

Edit: And what I actually came here to ask is, is there a way to add that nice menu big programs in Windows 7 have, where you can right-click it in the task bar and it gives custom actions? (And also the name of the program; mine just shows "Close window" :()

rhag posted:

They kinda let Swing rot. JavaFX is the "new" shiny UI library for java. Included in jdk 1.8.

Cheers. I'll have a look at both and go with whatever seems easier. My needs are extremely basic.

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."

WHERE MY HAT IS AT posted:

The term you're looking for is jump-list, looks like there's maybe a library for it? I don't know, I'm not a java programmer.
http://stackoverflow.com/questions/3782282/making-a-windows-7-jump-list-in-java

Edit: looks like that lib costs money, but at least now you know what to search for, I guess

Yep. I also just realized that since I work both in windows and linux, this single-platform functionality might not be the best idea, but thanks for the info.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Anybody using Vagrant in their Java development? How do you get code from the IDE on the host machine to the app server on the VM? I tried adding a run configuration for a remote tomcat server in IntelliJ but it looks like you also have to have tomcat installed locally and configured the same way as the remote? What kind of poo poo is that?

Or should I be using the maven tomcat plugin? Ideally shouldn't the compiling happen on the Vagrant box to ensure java version and whatnot?

fletcher fucked around with this message at 23:15 on Apr 10, 2014

BirdOfPlay
Feb 19, 2012

THUNDERDOME LOSER
Pike and Janitor, wanted to say thanks for the tips. I'm only now just getting around to putting code to page and focused on getting the file reading done first. After some minor bugs (like getting the mapfiles in the right place) it worked like a champ.

What's a good resource on learning how exceptions are to be used and added? I'm going to read through Oracle's lessons about them but am thinking that something meatier would be helpful to.

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."
I've got a timer program, and under windows it sometimes decides to blink as if calling attention to itself, but nothing is happening except the continuing countdown. I wonder what could be triggering that, because it's a tad annoying... I kind of suspect it's out of my control, though, because windows seems to decide on its own when to show these notifications.

Chas McGill
Oct 29, 2010

loves Fat Philippe

BirdOfPlay posted:

What's a good resource on learning how exceptions are to be used and added? I'm going to read through Oracle's lessons about them but am thinking that something meatier would be helpful to.
Seconding this. There's something about exception handling that just causes my brain to switch off when I'm trying to learn about it. I get confused by the exceptions hierarchy and when to use them instead of 'defensive programming'.

M31
Jun 12, 2012

fletcher posted:

Anybody using Vagrant in their Java development? How do you get code from the IDE on the host machine to the app server on the VM? I tried adding a run configuration for a remote tomcat server in IntelliJ but it looks like you also have to have tomcat installed locally and configured the same way as the remote? What kind of poo poo is that?

Or should I be using the maven tomcat plugin? Ideally shouldn't the compiling happen on the Vagrant box to ensure java version and whatnot?

I'm currently busy switching our develop environment to Vagrant and wondering the same thing. I decided to just compile on the vagrant box using a provisioning shell script, which seemed like the easiest way. It also does not require installing anything on the host (except Vagrant of course) in case you just need a simple testing environment or are a designer.

It does not really solve the development problem though. That is currently done by running a local tomcat server and just connecting to the resources on the VM, but there has to be some better way.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

M31 posted:

I'm currently busy switching our develop environment to Vagrant and wondering the same thing. I decided to just compile on the vagrant box using a provisioning shell script, which seemed like the easiest way. It also does not require installing anything on the host (except Vagrant of course) in case you just need a simple testing environment or are a designer.

It does not really solve the development problem though. That is currently done by running a local tomcat server and just connecting to the resources on the VM, but there has to be some better way.

Interesting, I thought for sure somebody would have come up with a nice solution for this. After reading the links below though, doesn't seem like there's a good way to go about it.

http://stackoverflow.com/questions/17625421/vagrant-for-a-java-project-should-you-compile-in-the-vm-or-on-the-host
http://stackoverflow.com/questions/16364563/is-it-possible-to-use-vagrant-with-intellij
http://stackoverflow.com/questions/14904590/is-vagrant-useful-for-java-javaee-developers
https://groups.google.com/forum/#!topic/vagrant-up/sVRMvAmhwAA

I guess the best bet is to just install the IDE inside the VM? I already do that anyways but I can see other team members groaning about it already. =\

FAT32 SHAMER
Aug 16, 2012



Okay, I am supposed to convert the heap.java program so the heap is an ascending, rather than a descending, heap. (That is, the node at the root is the smallest rather than the largest.) Is there going to be an easy way to do this, i.e. switching the > and <'s, or am I going to have to completely rewrite my professor's really unhelpful spaghetticode?

Heap.java:
Java code:
package lab5;


public class Heap
{
    private Node[] heapArray;
    private int maxSize;           // size of array
    private int currentSize;       // number of nodes in array
// -------------------------------------------------------------
   public Heap(int mx)            // constructor
      {
      maxSize = mx;
      currentSize = 0;
      heapArray = new Node[maxSize];  // create array
      }
// -------------------------------------------------------------
   public boolean isEmpty()
      { return currentSize==0; }
// -------------------------------------------------------------
   public boolean insert(int key)
      {
      if(currentSize==maxSize)
         return false;
      Node newNode = new Node(key);
      heapArray[currentSize] = newNode;
      trickleUp(currentSize++);
      return true;
      }  // end insert()
// -------------------------------------------------------------
   public void trickleUp(int index)
      {
      int parent = (index-1) / 2;
      Node bottom = heapArray[index];

      while( index > 0 &&
             heapArray[parent].getKey() < bottom.getKey() )
         {
         heapArray[index] = heapArray[parent];  // move it down
         index = parent;
         parent = (parent-1) / 2;
         }  // end while
      heapArray[index] = bottom;
      }  // end trickleUp()
// -------------------------------------------------------------
   public Node remove()           // delete item with max key
      {                           // (assumes non-empty list)
      Node root = heapArray[0];
      heapArray[0] = heapArray[--currentSize];
      trickleDown(0);
      return root;
      }  // end remove()
// -------------------------------------------------------------
   public void trickleDown(int index)
      {
      int largerChild;
      Node top = heapArray[index];       // save root
      while(index < currentSize/2)       // while node has at
         {                               //    least one child,
         int leftChild = 2*index+1;
         int rightChild = leftChild+1;
                                         // find larger child
         if(rightChild < currentSize &&  // (rightChild exists?)
                             heapArray[leftChild].getKey() <
                             heapArray[rightChild].getKey())
            largerChild = rightChild;
         else
            largerChild = leftChild;
                                         // top >= largerChild?
         if( top.getKey() >= heapArray[largerChild].getKey() )
            break;
                                         // shift child up
         heapArray[index] = heapArray[largerChild];
         index = largerChild;            // go down
         }  // end while
      heapArray[index] = top;            // root to index
      }  // end trickleDown()
// -------------------------------------------------------------
   public boolean change(int index, int newValue)
      {
      if(index<0 || index>=currentSize)
         return false;
      int oldValue = heapArray[index].getKey(); // remember old
      heapArray[index].setKey(newValue);  // change to new

      if(oldValue < newValue)             // if raised,
         trickleUp(index);                // trickle it up
      else                                // if lowered,
         trickleDown(index);              // trickle it down
      return true;
      }  // end change()
// -------------------------------------------------------------
   public void displayHeap()
      {
      System.out.print("heapArray: ");    // array format
      for(int m=0; m<currentSize; m++)
         if(heapArray[m] != null)
            System.out.print( heapArray[m].getKey() + " ");
         else
            System.out.print( "-- ");
      System.out.println();
                                          // heap format
      int nBlanks = 32;
      int itemsPerRow = 1;
      int column = 0;
      int j = 0;                          // current item
      String dots = "...............................";
      System.out.println(dots+dots);      // dotted top line

      while(currentSize > 0)              // for each heap item
         {
         if(column == 0)                  // first item in row?
            for(int k=0; k<nBlanks; k++)  // preceding blanks
               System.out.print(' ');
                                          // display item
         System.out.print(heapArray[j].getKey());

         if(++j == currentSize)           // done?
            break;

         if(++column==itemsPerRow)        // end of row?
            {
            nBlanks /= 2;                 // half the blanks
            itemsPerRow *= 2;             // twice the items
            column = 0;                   // start over on
            System.out.println();         //    new row
            }
         else                             // next item on row
            for(int k=0; k<nBlanks*2-2; k++)
               System.out.print(' ');     // interim blanks
         }  // end for
      System.out.println("\n"+dots+dots); // dotted bottom line
      }  // end displayHeap()
// -------------------------------------------------------------
 
   
}

Node.java:
Java code:

package lab5;


public class Node 
{

   
       
   
   private int iData;             // data item (key)
// -------------------------------------------------------------
   public Node(int key)           // constructor
      { iData = key; }
// -------------------------------------------------------------
   public int getKey()
      { return iData; }
// -------------------------------------------------------------
   public void setKey(int key)
      { iData = key; }
// -------------------------------------------------------------
}  // end class Node
    

Client code:
Java code:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package lab5;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class HeapApp {
  public static void main(String[] args) throws IOException
      {
      int value, value2;
      Heap theHeap = new Heap(31);  // make a Heap; max size 31
      boolean success;

      theHeap.insert(70);           // insert 10 items
      theHeap.insert(40);
      theHeap.insert(50);
      theHeap.insert(20);
      theHeap.insert(60);
      theHeap.insert(100);
      theHeap.insert(80);
      theHeap.insert(30);
      theHeap.insert(10);
      theHeap.insert(90);

      while(true)                   // until [Ctrl]-[C]
         {
         System.out.print("Enter first letter of ");
         System.out.print("show, insert, remove, change: ");
         int choice = getChar();
         switch(choice)
            {
            case 's':                        // show
               theHeap.displayHeap();
               break;
            case 'i':                        // insert
               System.out.print("Enter value to insert: ");
               value = getInt();
               success = theHeap.insert(value);
               if( !success )
                  System.out.println("Can't insert; heap full");
               break;
            case 'r':                        // remove
               if( !theHeap.isEmpty() )
                  theHeap.remove();
               else
                  System.out.println("Can't remove; heap empty");
               break;
            case 'c':                        // change
               System.out.print("Enter index of item: ");
               value = getInt();
               System.out.print("Enter new priority: ");
               value2 = getInt();
               success = theHeap.change(value, value2);
               if( !success )
                  System.out.println("Invalid index");
               break;
            default:
               System.out.println("Invalid entry\n");
            }  // end switch
         }  // end while
      }  // end main()
//-------------------------------------------------------------
   public static String getString() throws IOException
      {
      InputStreamReader isr = new InputStreamReader(System.in);
      BufferedReader br = new BufferedReader(isr);
      String s = br.readLine();
      return s;
      }
//-------------------------------------------------------------
   public static char getChar() throws IOException
      {
      String s = getString();
      return s.charAt(0);
      }
//-------------------------------------------------------------
   public static int getInt() throws IOException
      {
      String s = getString();
      return Integer.parseInt(s);
      }
//-------------------------------------------------------------
    
}

My initial reaction was to only alter method displayHeap() but I don't really think that will do what I need it to do. Then I tried switching trickleUp() and trickleDown() and all that did was gently caress up the structure of the tree itself. I'm playing around with the insert() method right now to see if I can figure it out :v:

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I dunno but I'm definitely gonna start putting //------------------------------------------------------------- everywhere in my code

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

BirdOfPlay posted:

Pike and Janitor, wanted to say thanks for the tips. I'm only now just getting around to putting code to page and focused on getting the file reading done first. After some minor bugs (like getting the mapfiles in the right place) it worked like a champ.

What's a good resource on learning how exceptions are to be used and added? I'm going to read through Oracle's lessons about them but am thinking that something meatier would be helpful to.

Chas McGill posted:

Seconding this. There's something about exception handling that just causes my brain to switch off when I'm trying to learn about it. I get confused by the exceptions hierarchy and when to use them instead of 'defensive programming'.

Exceptions are a "something wrong!" signaling method in Java. When an exception is thrown, the current scope of code is indicating that it can't or shouldn't proceed. When write code in a try block, and catch exceptions in your catch block, you're acknowledging that something might go wrong, and that you know how to recover if it does.

There are two kinds of exceptions: Checked Exceptions (classes that extend Exception, but do not extend RuntimeException) and UncheckedExceptions (classes that extend RuntimeException). If a method throws a checked exception, it must advertise the fact in its signature. This is your method acknowledging that, under certain circumstances, it's not going to be able to complete its "contract." Checked exceptions allow a caller to anticipate and recover from the ways in which your method might fail to complete. Unchecked exceptions do not need to be advertised in a method's signature. Throwing an unchecked exception is your code signaling that something went wrong in a way that it's incredibly unlikely that the caller will be able to recover from. Unchecked exceptions can be caught by try/catch blocks, if you know what to look for.

If your method is capable of recovering from an error on its own, and it makes sense within the context, don't throw an exception and make someone else deal with your issue. Easy peasy.

If your method is not capable of dealing with an error, but you think that someone else up the chain might reasonably be able to recover, you should throw a checked exception. The name of the exception should indicate what went wrong, and it should be in a descriptive class hierarchy. If you're communicating with a remote service and you receive half of a message, it makes sense to throw something that extends IOException. If you can't find an exception class that describes the kind of problem you're having, make up your own. Never throw new Exception("A description of the problem." ); The type system is how Java describes the exception, and how someone knows whether they can recover from it. The exception's message is only there to get logged, so that someone reading logs can have a clue of what specifically went wrong. If your method throws multiple kinds of exceptions that might be recovered from separately, advertise each. public void myMethod() throws Exception { is worthless as an advertisement of what might go wrong in your method.

If you run into an error condition that you don't think anyone could reasonably predict or recover from, it's fine to throw an unchecked exception, as long as you reasonably expect that, somewhere up the stack, a caller will be catching and recovering from all unchecked exceptions. Defensive programming is making sure that, if your program performs work in logical units, an exception in one does not disrupt work in another without cause. (For example, a user requesting a corrupted resource shouldn't shut down a webserver.) If a method you call throws an exception that you can't recover from, and you don't think that anyone up the stack will be able to recover from, you can "wrap" it in a runtime exception: try { difficultMaths(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } Be conservative in your use of RuntimeExceptions in this manner. It's incredibly frustrating to write a catch block that catches RuntimeExceptions and then has to "unwrap" them to determine if they can actually be recovered from.

When you catch exceptions, only catch the types of exceptions that you're capable of recovering from. Never swallow errors that are going to prevent code up the stack from functioning properly. Never swallow exceptions or make things RuntimeExceptions just because you don't want to bother with them, or you think it's unlikely that they'll be thrown.

Both checked and unchecked exceptions in java extend Throwable. Never catch Throwables, only catch exceptions. Errors also extend Throwable. Errors are generally things that are utterly unrecoverable, and indicate that the throwing application should be shut down. Something that causes an Error is likely to prevent any recovery mechanism from working properly - for example VirtualMachineError. Do not implement anything that extends Error.

BirdOfPlay
Feb 19, 2012

THUNDERDOME LOSER
Okay, cool. That's about what I assumed and remembered.

quote:

Never throw new Exception("A description of the problem." );

This hits on my specific question that made me ask about exceptions: how do you communicate different application specific exceptions?

For example, my mapmaker can read in mapfiles. When it does so, it could throw various file I/O exceptions with a FileNotFoundException being the chief one. I also want it to throw an exception if there's a bad map file, which can occur an several ways. In this case I would want to throw an exception of type BadMapFileException (which extends IOException), correct?

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

fletcher posted:

I dunno but I'm definitely gonna start putting //------------------------------------------------------------- everywhere in my code

My data structures textbook had code that looked like this. I'm starting to think this was just what early Java "well structured" code was supposed to look like.

Volmarias
Dec 31, 2002

EMAIL... THE INTERNET... SEARCH ENGINES...

carry on then posted:

My data structures textbook had code that looked like this. I'm starting to think this was just what early Java "well structured" code was supposed to look like.

I think it's more that people using Java weren't particularly used to it or the style yet, and so they carried their C/C++ style notions over, not that it was a "good style."

Also, that professor's code looks like a war crime. Jesus Christ. In TYOOL 2014 no one's code should look like that.

BirdOfPlay
Feb 19, 2012

THUNDERDOME LOSER
Also, I thought heaps were dynamic structures. Why is it stored in a basic array? Why do the nodes not know who their children are? :psypop:

Takk, changing how displayHeap() works is a low-down, dirty hack. Trace a call through insert and figure out how the tree percolates nodes after an insert. It should become quickly self-evident where you need to make the changes.

Quick hint: The whole (index-1)/2 is meant to confuse you and obfuscates the problem.

If you need direct help, you have to give some examples of the code changes that you've attempted. Your question is far to open-ended, and I can think of one solution and one dirty hack that would both work just fine.

Volmarias
Dec 31, 2002

EMAIL... THE INTERNET... SEARCH ENGINES...

BirdOfPlay posted:

Quick hint: The whole (index-1)/2 is meant to confuse you and obfuscates the problem.

I don't think that any of this was intentionally written to confuse undergrads :gonk:

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

BirdOfPlay posted:

Okay, cool. That's about what I assumed and remembered.


This hits on my specific question that made me ask about exceptions: how do you communicate different application specific exceptions?

For example, my mapmaker can read in mapfiles. When it does so, it could throw various file I/O exceptions with a FileNotFoundException being the chief one. I also want it to throw an exception if there's a bad map file, which can occur an several ways. In this case I would want to throw an exception of type BadMapFileException (which extends IOException), correct?

Throwing BadMapFileException here is a good instinct. That seems like it's going to communicate the right level of information upwards. As for the class hierarchy: be pragmatic. Your program is likely the only one that's going to be catching BadMapFileException. Do you ever want to handle invalid map files the same way that you'd handle an inability to read map files from disk? I'd guess not: one of them should be handled by telling the user to make sure that they typed the path correctly, and the other would be to tell the user to make sure that they passed in a valid map file. Feel free to make BadMapFileExtension extend Exception, rather than IOException. If, on the other hand, you find yourself writing two catch blocks with the same logic handling two different types of exceptions, this is a strong hint that maybe they should share a common superclass.

You have plenty of room to be flexible here. It's not difficult to go back and refactor the class hierarchy if you guessed wrong the first time.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

BirdOfPlay posted:

Also, I thought heaps were dynamic structures. Why is it stored in a basic array? Why do the nodes not know who their children are? :psypop:

Using an array is often the best way to implement a (binary) heap, in much the same way that an arraylist is generally more performant than a linked list. If you have the key for a node (the index in the array), it's very straightforward to find its children. Of course, you'd usually write getLeftChild()/getRightChild()/getParent() functions instead of inlining those operations every time you need to use them...

FAT32 SHAMER
Aug 16, 2012



Jabor posted:

Using an array is often the best way to implement a (binary) heap, in much the same way that an arraylist is generally more performant than a linked list. If you have the key for a node (the index in the array), it's very straightforward to find its children. Of course, you'd usually write getLeftChild()/getRightChild()/getParent() functions instead of inlining those operations every time you need to use them...

So would this be my best course of action for converting it to an ascending tree? That code is a complete clusterfuck and this professor is normally pretty good, so maybe we're supposed to see this and be like "uhh yeah this needs a lot of work"

RichardA
Sep 1, 2006
.
Dinosaur Gum

Tusen Takk posted:

So would this be my best course of action for converting it to an ascending tree? That code is a complete clusterfuck and this professor is normally pretty good, so maybe we're supposed to see this and be like "uhh yeah this needs a lot of work"

If you think it would help you understand the code feel free to do so - although you may wish to ask if the professor wants the minimal changes just in case. Glancing through it looks like you can just swap some <'s and >'s in the appropriate places once you understand what the code is doing.

FAT32 SHAMER
Aug 16, 2012



RichardA posted:

If you think it would help you understand the code feel free to do so - although you may wish to ask if the professor wants the minimal changes just in case. Glancing through it looks like you can just swap some <'s and >'s in the appropriate places once you understand what the code is doing.

Haha looks like I have my work cut out for me, then!

BirdOfPlay
Feb 19, 2012

THUNDERDOME LOSER

Gravity Pike posted:

Throwing BadMapFileException here is a good instinct. That seems like it's going to communicate the right level of information upwards. As for the class hierarchy: be pragmatic. Your program is likely the only one that's going to be catching BadMapFileException. Do you ever want to handle invalid map files the same way that you'd handle an inability to read map files from disk? I'd guess not: one of them should be handled by telling the user to make sure that they typed the path correctly, and the other would be to tell the user to make sure that they passed in a valid map file. Feel free to make BadMapFileExtension extend Exception, rather than IOException. If, on the other hand, you find yourself writing two catch blocks with the same logic handling two different types of exceptions, this is a strong hint that maybe they should share a common superclass.

You have plenty of room to be flexible here. It's not difficult to go back and refactor the class hierarchy if you guessed wrong the first time.

I assumed IO. Partly it was because the method declared that it threw IO's for file actions itself, but also because it was from a file read and seemed sensible to keep things as high on the hierarchy as possible.

Volmarias posted:

I don't think that any of this was intentionally written to confuse undergrads :gonk:

I just assumed where a cause of the confusion was. The problem is focused more on tracing the program flow than anything else.

Tusen Takk posted:

Haha looks like I have my work cut out for me, then!

Its not that bad, just be like the constipated mathematician.

Work it out with a pencil!

Drunkenboxer
Oct 3, 2007

eh?
Hey guys, So i am building a program to save some data using Linked Lists.

The program needs to take a title, 3 cast members, and a rating.

Everything is working perfectly except the 3 cast members part.

I am using an ArrayList to store the 3 cast members, then breaking it down and adding it to a string. This method works, but it will carry over all cast members entered and add it to every movie, the output looks something like this:

CastAway
Tom Hanks
Wilson
Big Boat
Will Smith
Bill Paxton
Aliens
5

Independence Day
Tom Hanks
Wilson Big Boat
Will Smith
Bill Paxton
Aliens
4

I cannot for the life of me figure out why it is carrying over and showing all cast member entries but not carrying over the rating or Movie name.

Here is the Movie class where I set the values:
code:
public class Movie
{
	private String name;
	private ArrayList<String> cast;
	private int rate;
	private String temp;
	private String aString;
	private int listCount;
	private int prevCount;
	
	
	
	public Movie (String aName, ArrayList<String> aCast, int aRate )
	{
		aString = "";
		
		name = aName;
		cast = aCast;
		rate = aRate;
	}
	
	
	public ArrayList getCast()
	{
		return(cast);
	}
	
	
	
	public String getName()
	{
		return(name);
	}
	
	
	public int getRate()
	{
		return(rate);
	}
	
	
	public void setName(String aName)
	{
		name = aName;
	}
	
	
	public String toString()
	{
		
		if (cast != null)
			for(listCount = prevCount; listCount < cast.size(); listCount++)
				{
					aString = aString + "\n" + cast.get(listCount);
					
				}
		prevCount = listCount;
		if (name != null)
		{
			temp = name + "\n" + aString +"\n" + rate;
			
		}
		else 
		{
			temp = "No Movie exists";
			
		}
		return(temp);
		
	}
}
Here is the code I add the inputted data:
code:
public void add()
	{
		Movie newMovie;
		MovieNode newNode;
		
		title = null;
		System.out.print("Please enter the title of the movie: ");
		title = in.nextLine();
		
		System.out.println();
		castingCall();
		rateMe();
		newMovie = new Movie(title, cast, rate);
		newNode = new MovieNode(newMovie, null);
		
		if (head == null)
			{
				head = newNode;
			}
			
		else 
			{
				MovieNode current = head;
				MovieNode previous = null;
				
				while (current != null)
				{
					previous = current;
					current = current.getNext();
				}
				previous.setNext(newNode);
			}
	}
	
and here is where i display it:
code:
public void display()
	{
		int count = 1;
		MovieNode temp = head;
		System.out.println("Here is your Movie Collection: ");
		for (int i = 0; i < 12; i++)
			System.out.print("*");
		System.out.println();
		
		if (temp == null)
			System.out.println("The List is Empty");
			System.out.println();
		
		while (temp != null)
			{
				System.out.println();
				System.out.println("#" + count + ": " + temp);
				temp = temp.getNext();
				count = count + 1;
				for (int i = 0; i < 12; i++)
					System.out.print("*");
			}
		System.out.println();
	}
	
and here is where i add all the data to the temp to be displayed ( IN the movie class above, but just for readability:
code:
public String toString()
	{
		
		if (cast != null)
			for(listCount = 0; listCount < cast.size(); listCount++)
				{
					aString = aString + "\n" + cast.get(listCount);
					
				}
		
		if (name != null)
		{
			temp = name + "\n" + aString +"\n" + rate;
			
		}
		else 
		{
			temp = "No Movie exists";
			
		}
		return(temp);
}
This has had me stumped for 3 days, any ideas would be helpful, my main problem is the logic behind the movie and rating display working but not the ArrayList.

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

Post your main class, where you are actually populating the data with specific values. You're probably just passing the same arraylist in to each movie without changing, but I can't tell without seeing where each Movie object is created.

Drunkenboxer
Oct 3, 2007

eh?
Here ya go,

code:
public class Manager
{
	private MovieNode head;
	private String title;
	private ArrayList<String> cast;
	
	private String addCast;
    Scanner in = new Scanner(System.in);
	private int match;
	private int rate;
	private int length;
	

	
	public Manager()
	{
		MovieNode head = null;
		title = null;
		addCast = "";
	    cast = new ArrayList<String>(3);
		match = 0;
		rate = 0;
		length = 0;
		
		
	}
	
	public void add()
	{
		Movie newMovie;
		MovieNode newNode;
		
		title = null;
		System.out.print("Please enter the title of the movie: ");
		title = in.nextLine();
		
		System.out.println();
		castingCall();
		rateMe();
		newMovie = new Movie(title, cast, rate);
		newNode = new MovieNode(newMovie, null);
		
		if (head == null)
			{
				head = newNode;
			}
			
		else 
			{
				MovieNode current = head;
				MovieNode previous = null;
				
				while (current != null)
				{
					previous = current;
					current = current.getNext();
				}
				previous.setNext(newNode);
			}
	}
	
	
	public void display()
	{
		int count = 1;
		MovieNode temp = head;
		System.out.println("Here is your Movie Collection: ");
		for (int i = 0; i < 12; i++)
			System.out.print("*");
		System.out.println();
		
		if (temp == null)
			System.out.println("The List is Empty");
			System.out.println();
		
		while (temp != null)
			{
				System.out.println();
				System.out.println("#" + count + ": " + temp);
				temp = temp.getNext();
				count = count + 1;
				for (int i = 0; i < 12; i++)
					System.out.print("*");
			}
		System.out.println();
	}
	
	
	public void remove()
	{
		if (head == null)
		{
			System.out.println("The movie list is already empty");
		}
		else
		{
			removeEmpty();
		}
	}
	
	
	public void removeEmpty()
	{
	
		MovieNode previous = null;
		MovieNode current = head;
		String searchName = null;
		boolean isFound = false;
		String currentName;
		Scanner in = new Scanner(System.in);
		System.out.print("Enter the name of the movie you wish to remove: ");
		searchName = in.nextLine();
		
		while ((current != null) && (isFound == false))
		{
			currentName = current.getData().getName();
			if (searchName.compareToIgnoreCase(currentName) == match)
				isFound = true;
			else 
			{
				previous = current;
				current = current.getNext();
			}
		}
		
		if (isFound == true)
		{
			System.out.println("Removing movie called " + searchName);
			if (previous == null)
			{
				head = head.getNext();
			}
			else
			{
				previous.setNext(current.getNext());
			}
		}
		else 
		{
			System.out.println("No movie called " + searchName + "in the movie list");
		}
	}
	
	public void castingCall()
	{
		int count = 1;
		
		for (int i = 0; i < 3; i++)
			{
			System.out.print("Enter the name of cast member # " + count + " : ");
			addCast = in.nextLine();
		
			count++;
			cast.add(addCast);
			}
			
	}
	
	public void rateMe()
	{
		System.out.print("Rate the movie from 0 to 5: ");
		rate = in.nextInt();
		in.nextLine();
		if ((rate < 0) || (rate >5))
			{
			System.out.println("Oopsie, that is not a valid rating! PLease try again!");
			rateMe();
			}
		
	}	
}
Thanks for taking a look

BirdOfPlay
Feb 19, 2012

THUNDERDOME LOSER
First off, you're initializing a Scanner outside of a code block. private Scanner in = new Scanner(); is not a good practice. You should initialize it in the constructor for this class. Granted, I've been hitting a low average on these things. I guess I could be wrong, but that kinda of thing will always look like rear end to me.

castingCall() is screwing the pooch on this one. cast is the ArrayList that is passing the cast to the new MovieNode and each time you call castingCall() it adds three people to the list.

You're also not copying the list but just passing a reference. This means that all movies will point to the same cast list each time.

For instance, if you added three movies in a row and then displayed them all, you should see all three casts smushed together like that. If you, instead, displayed the movies after each addition, the cast lists would slowly grow.

I'm tired and there's a mess of things going wrong with the code, but that should be enough to get you started on the cure.

BirdOfPlay fucked around with this message at 09:19 on Apr 13, 2014

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."
I'm fresh!

Drunkenboxer, why do you have temporary variables such as "temp"... as class members? It will at least improve readability if you move them to the method they belong. Also, nitpicking, but rate, n., means relative speed of change, when it would be more intuitive to have "rating".

Movie's toString is pretty dumb, too. Why would it be legal to create a movie without a name at least, in the first place?

In casting call replace counter with i+1.

Why does rateMe consume a line of input?

Oh, yeah, in removeEmpty, you should replace == for comparisons of strings with equals (and anywhere else appropriate when you want to compare the content of strings/everywhere). Also, why is it called "removeEmpty" when it's clearly removing not empty?

Where is the MovieNode class? Or at least why is it created with a null?

As BirdOfPlay said, castingCall should return an array list and rateMe should return an integer. Some methods should return something besides void. For example, in official Java collections add and remove methods return boolean to indicated if the operation was successful.

FateFree
Nov 14, 2003


Do you have your MovieNode class available? I'm bored at work and I'm going to go through and clean up your code with some pointers.

Adbot
ADBOT LOVES YOU

Chas McGill
Oct 29, 2010

loves Fat Philippe

Gravity Pike posted:

Exceptions are a "something wrong!" ...
Thanks very much for this, it's a much better explanation than the whole section in the textbook.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply