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
Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
Is there a simple way to create a list of references to objects? A rough sketch of what I'm trying to do...
code:
public class Goon {
   public Integer neckbeards;
   public String name = new String();
   public Boolean hasAClue;
   public Vector<Object> thingsICareAbout = new Vector<Object>(); 
  
   public static void main() {
   neckbeards = 1;
   name = "Gravity Pike";
   thingsICareAbout.add(neckbeards);
   neckbeards = 0;
   
   System.out.println(neckbeards.toString()+" vs "+thingsICareAbout.elementAt(0).toString());
   }
}
My output's going to be "1 vs 0", when I want it to be "0 vs 0" - I want the list to contain a reference to the variable, not the value of the variable. Is there a simple way to do this, without, say, creating a new class ThingsIMightCareAbout<U>, and having all of my variables be of this type? I'm a bit new to Java, and am perhaps thinking a bit too much as if I were coding in C++...

Adbot
ADBOT LOVES YOU

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

rhag posted:

So in order to achieve your goal you should have your own object, with a setNeckbeards() method. Create one instance of that object, add it to the vector, set the neckbeards value to something else, and see it change everywhere that object is referenced.

So, basically I need to...

code:
public class Goon {
   public Thing<Integer> neckbeards;
   public Thing<String> name;
   public Thing<Boolean> hasAClue;
   public Vector<Thing> thingsICareAbout = new Vector<Thing>(); 
   
   class Thing<U extends Object> {
      U contents;
      public void set(U newval) {contents = newval;}
      public U get() {return contents; }
      public String toString() {return contents.toString();}
   }
   
   public static void main() {
   neckbeards.set(1);
   name.set("Gravity Pike");
   thingsICareAbout.add(neckbeards);
   neckbeards.set(0);
   
   System.out.println(neckbeards.toString()+" vs "+thingsICareAbout.elementAt(0).toString());
   }
}
And making sure that every variable I might care about is of type Thing. The get/set syntax is inconvenient, and I figured there might be an easier way built into the language. (Like in C, I could pass &argument, and get it's value with *argument.)

Am I going to run into problems with failing to initialize "contents" if it's not a blocked primative?

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
I've got a question about creating new objects within generics. What I'm trying to do can be boiled down to this:
code:
public class Environment<U extends Agent, V extends Agent> {
   U agt1;
   V agt2;
   public void reset() {
      agt1 = new U();
      agt2 = new V();
   }
}
This doesn't work. I've been looking at The Java Tutorials, but I'm having trouble with something in this one, or am looking at the wrong thing entirely. I have tried this:
code:
public class Environment<U extends Agent, V extends Agent> {
   U agt1;
   V agt2;
   public void reset() {
      agt1 = agt1.getClass().newInstance();
      agt2 = agt2.getClass().newInstance();
   }
}
but it didn't work. Can anyone point out what I'm doing wrong?

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
I'm running out of heap space. To be fair, I'm throwing around a whole lot of aHugeFuckinArrayDeque.clone()'s, but I try to make sure I call aHugeFuckinArrayDeque.clear() before I do that, so I shouldn't have any more than two copies at a time (which I have more than enough RAM for).

Without looking at my rats' nest of code, would you suspect that I'm failing to clear out something somewhere, or is it just Java failing to do garbage collection appropriately? Java's tutorial just says something like "The garbage collector does its job automatically when it determines that the time is right," which isn't really helping me understand what's going on.

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

rjmccall posted:

1. You have a memory leak. In a GCed environment, this means that you're preventing something from getting collected by holding a reference to it when you don't mean to. We can't help you debug this without looking at your "rats' nest of code", which I assure you no-one wants to do. Try a memory profiler.

2. You're actually doing something which requires a larger resident set than you've configured Java with. I think the default on many platforms is something dinky like 64MB. You can bump this up from the command line (or by configuring your IDE, if you're using one).

3. There's a bug in the garbage collector. This is almost certainly not the problem — not that there aren't bugs in the collector, just that you are very unlikely to be running into one.

Okay, that's about what I figured. I'm going to start sifting through the code - someone else wrote an extension to my class, and we're both blaming each other for the fuckup. (Of course. :rolleyes:) Thanks.

Ninja Edit: He forgot to set an upper bound to turn on infinite-loop detection, and I failed to pick up on it till now. :doh:

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
I'm trying to create a class that keeps track of different types of costs that a system might incur. (Examples might be time taken, money spent, and incorrect solution penalties.) I'm writing the abstract/template class, and my users need to be able to define their own cost categories at (their) compile time. I thought a good solution would be to have them create an Enum of different cost types, as it would save both time and memory over having cost types represented as strings. I'd like to create my class using generics, but I'm a bit unsure how to proceed.

code:
class CostTracker<E extends Enum> {
   private EnumMap<E,Float> costs = new EnumMap<E,Float>;
   public void set(E type, Number cost) {
      costs.put(E, cost.toFloat());
   }
   public float sum() {
      float retval = 0;
      for (E type : costs.keySet()) {
         retval+=costs.get(type);
      }
      return retval;
   }
}
And the user would do something like:
code:
enum MyCostTypes {
   TIME,MONEY
}
CostTracker<MyCostTypes> = new CostTracker<MyCostTypes>();
Is this correct? Is this a bad way of doing things?

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
Are there any good guides/articles/tutorials about how the JVM is using RAM? I'm trying to compare the memory usage characteristics of a program written in Java with one written in Tcl, and I'm calling "ps h -p [PID] -o vsz" from within each at certain intervals to try to observe how much RAM each is using. Tcl grows more or less linearly with the number of "states" that I'm trying to keep track of, but Java just sits at/around 685 Mb the whole time, regardless of how much information I think I'm tracking.

(Please be kind, as this post probably reveals how little I know about Java, Linux, and Physical/Virtual Memory, all in one go.)

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

Gabbo posted:

Hey! This did the trick!

That is unbelievably frustrating; I don't know if this is a feature of vista or what, but when I type in "C:\Users\Scott\Documents\Classwork 2009\CSE 142\Programs\Test programs\tas.txt" into an explorer window, it opens the file. But, when I delete the ".txt" at the end of the file and put the filepath in again, it still opens. After deleting the ".txt" at the end of it, the program compiles and runs successfully.

Hooray for not displaying the full filename in windows explorer. Really, that's cool. Makes my life a lot easier.

Tools->Folder Options->View->Uncheck "Hide extensions for known file types". (You might also want to "Show hidden files and folders," but that one's up to you.) This is always the first thing I do when I'm working in a new account on Windows - I've had way too many problems due to not knowing what my extension actually is.

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
Shameful double post. :(

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
Does anyone have any decent resources for explaining to me how Java works? I mean, I'm solid with syntax, object-oriented-ness, various patterns, concurrance/threading, etc, but I have no idea what the ClassLoader is or does, other than "It's a tool I can use to get files from /src/main/resources". My knowledge of Java is purely from being dropped into the middle of it and figuring things out, rather than any formal education I've ever received. I feel like I'm a pretty solid developer, but I've just got some embarrassing holes in my background knowledge that I really should get around to filling in.

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

Horse Cock Johnson posted:

Can anyone recommend some good books or other resources for a long time C# developer looking to gain a deeper understanding of Java?

I've been a .NET programmer for >5 years and am pretty comfortable with Java at a high level. I've recently started a new job where I'll need to get up to speed with Java and am looking to expand my knowledge. I don't need anything that starts off with "Hello world!" or "What is a class?" but I've never really done anything with Java outside of a classroom either. I'm looking for stuff similar to CLR via C# but for Java and the JVM - something that explores some more advanced topics like threading, concurrency, performance, what's going on under the hood, etc.

Everything I find on Amazon is either a basic intro to Java or seems pretty outdated. For example: Java Concurrency in Practice - this sounds like it would be useful but it's 7 years old. Is it still relevant?

Concurrency in Practice is a very good java book. I'm also a fan of Effective Java. Despite being 7 and 5 years old, they're still pretty relevant. The latest Java Version is Java SE 7, out in 2011, which... doesn't really contain a lot that's super interesting. Just some convenience stuff - Strings in switch statements, ways to represent binary literal integers, etc. Java 6, out in 2006, was the last big change, and Java 8 (2014?) is going to have a lot of convenience stuff for lamdas and functional-ish programming, which will be great to work with.

It has been my experience, starting out with Java about a year ago, that familiarizing myself with the Apache Commons and Google Guava libraries has been incredibly useful. They contain the things that should be in core Java but aren't.

Gravity Pike fucked around with this message at 21:44 on Jul 29, 2013

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

Amarkov posted:

code:
try {
    ...
} catch (Throwable t) {
    //nop
}

Generally, you're going to want to catch Exception instead of Throwable, unless you're able to handle things like OutOfMemoryError or StackOverflowError. Errors are generally unrecoverable, and your best bet is to let your program bail.

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

Brain Candy posted:

Java code:
private static void sleep(long millis) {
  long end = System.getCurrentTimeMillis() + millis;  
  long remaining;
  while ( (remaining = end - System.getCurrentTimeMillis()) > 0) {
    try
    {
      Thread.sleep(remaining); //This is sloppy because sleep generally isn't that accurate
    }
    catch (InterruptedException ie){} //Juggernaught, etc.
  }
}

... and at this point, I'm just going to use Uninterruptibles.sleepUninterruptibly(), because Guava includes all much of the functionality that really ought to be there in the first place. (Does anyone know if this has the same issues with time that Thread.sleep() does? It's always been Good Enough™ for me.)

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
So, simplified, you have

Java code:
class Cage<T extends Animal>  {
  private Map <String, T> map = new HashMap<String, T>();
  
  public void put(String name, T animal) {
    map.put(name, animal);
  }

  public T get(String name) {
    return map.get(name);
  }
}
And instantiate it:

Java code:
 
Cage<Tiger> tigerCage = new Cage<Tiger>();
Now, lets looks at how you use use it. When you're getting, you're correct, T is the upper bound. It's perfectly valid to say:

code:
Animal dumbBeast = tigerCage.get("Khan");
However, when you're putting, T is the lower bound. You can't have:

code:
Animal sparky = new Dog();
tigerCage.put("Sparky", sparky);
because then you have a Dog in the tigerCage, and furthermore, when you try to retrieve Sparky, you're trying to retrieve him as a Tiger. However, you can put a more specific kind of Tiger in the tiger cage; you just can't to expect to get it out as the same type.

code:
BengalTiger stripes = new BengalTiger();
tigerCage.put("Stripes", stripes);

BengalTiger whatsHisName = tigerCage.get("Stripes"); //Nope, the tigerCage advertises that it contains Tigers. You can't assume what kind of tiger.
Tiger tStripes = tigerCage.get("Stripes"); //Perfectly valid
Animal aStripes = tigerCage.get("Stripes"); //Also ok.

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
So, I guess I discovered something worth sharing with the class. In an attempt to write a kind-of-gross introspective "Bean Converter" :

code:
public <K> convertBean(Object base, Class<K> outputClass) {
 // for every `public <T> T getSomething()` in base with a corresponding `public <U extends T> void setSomething(U something)` in outputClass, 
 // create an instance of outputClass where outputClass.something = base.something
}
I ran into an issue with primitives and typecasting. It turns out:
code:
Collection.class.isAssignableFrom(List.class); // true
int.class.isAssignableFrom(Integer.class); // false
Integer.class.isAssignableFrom(int.class); // also false
But Guava Primitives can help you figure out if something is really safe to cast:
code:
Primitives.wrap(int.class).equals(Primitives.wrap(Integer.class)); //true
Primitives.wrap(Collection.class).isAssignableFrom(Primitives.wrap(List.class)); //also true
Primitives.wrap and Primitives.unwrap return the input class if it's not actually a primitive or it's wrapper.

For my utility function, type erasure is still a significant headache, but luckily I'm able to make some assumptions about instances of K extending an interface which exposes a map of <CollectionFieldName, CollectionFieldType>.


Speaking of type erasure, boy is that inconvenient! I know it's not being addressed in any way in Java 8, but do any of you know if there are murmurings about ever resolving it? To my understanding, it's an artifact of not wanting to change Java Bytecode between 4 & 5, where Generics were introduced. Is this still a concern? Might we see somehthing in Java 9?

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

Adventure Pigeon posted:

I'm still pretty new to Java and have run into an issue. I'm working on writing a program that will determine the mean value for about 100000 datapoints by performing about 100 random simulations on each datapoint. I decided to mess around and see if I could multithread it to speed things up, so I tried to divide the datapoints up and pass them to separate threads, then perform the simulations for each batch of datapoints. I figured there'd be concurrency issues, and I want a separate instance of the variables for each thread, so I tried using ThreadLocal, but can't seem to make it work. The datapoints are stored in an ArrayList<String> and for the simulations, I've been randomizing the order by shuffling them. Apparently ThreadLocal doesn't like that. Anyways, if anyone has any ideas I'd appreciate them.

It might be simpler to set things up to there just aren't any concurrency issues than it is to duplicate things among threads. The very best thing you can do if you're worried about concurrency issues is not write to a variable that might be under contention. Functions that don't mutate state are always thread-safe. (So List.get is safe, but List.set, List.add, and List.remove are not.)

It's going to be hard to troubleshoot your problem without seeing any code. I'm not really sure what's going on from your description. It sounds like the datapoints are being partitioned out to different threads (so if ThreadA is working on the 3rd datapoint, that means that no other thread will be working on the 3rd datapoint), but then you're trying to create a copy of all of the datapoints and shuffle them within each thread?

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

Adventure Pigeon posted:

This is the primary class. It works aside from the method where I try to split things into threads using ExecutorService
http://pastebin.com/3b69ZGd1


This is the class I'm trying to multithread. I've left it without any of the modifications I've tried since none have worked and they'd just make it more confusing.
http://pastebin.com/it8ne45a

Not horrors; you're new, and still learning.

I'd implement makeThreads as follows:
Java code:
public void makeThreads(Integer threads, ArrayList<String> windows, ArrayList<String> predictions, double stat, Integer simulations) {
  int subSegmentSize = Math.ceil((double)windows.size()/threads); //we'd rather have the last thread work on fewer windows than miss up to (threads-1) windows at the end
  ExecutorService executor = Executors.newFixedThreadPool(theads);
  for (int i=0; i< threads; i++) {
    int start = i * subSegmentSize;
    int end = Math.min( (i + 1) * subSegmentSize, windows.size());
    List<String> subSegment = new ArrayList(windows.subList(start, end));
    List<String> predictionsCopy = new ArrayList(preditions);
    Runnable worker = new RunThreads(subSegment, predictionsCopy, stat, simulations);
    executor.execute(worker);
  }
  executor.shutdown();
}
Since I'm not going to presume that threads/windows.size is always going to be an integer, I put in some logic to guard against dropping your last few windows on the floor. I'm casting windows.size() to a double so that the result is a double; an int divided by an int is an int. (7/3 = 2, but 7.0/3 = 2.3333)

However, the main difference is that we're creating a new copy of things for each thread. new ArrayList(sourceList) creates an entirely separate list in memory, and changing this list doesn't cause the order or contents of any of the other lists to change. One of your bugs is that windowSegment always refers to the same list. When you passed it to a thread, you were almost immediately clearing that list's contents, and overwriting it with new contents.

Java code:
Collections.shuffle(readArray, new Random(seedValue));
This was also causing you a lot of problems. readArray is the same List as predictions and predictions1 in RunThreads, which is the same list as predictions in MakeThreads. This means that whenever any thread shuffled it's preditions list, it also shuffled the predictions list of every other thread, regardless which part of code the other threads were currently running. You might get two threads shuffling the same list at the same time, or you might get a list that's shuffled while you're using it. This is also solved by creating a new copy of the predictions list before handing it off to each thread.

Within each RunThreads instance, I'd consider creating a Random() in the constructor, and using the same Random object for each Collections.shuffle call. (Or just allow shuffle to use the default source of randomness.)

Java code:
try {
  predictionsUnformattedArray = measureSlope.loadFile(predictedFile);
  statsUnformattedArray = measureSlope.loadFile(statsFile);
} catch(Exception e) {
  if(e instanceof IOException) {
    System.out.println("YOU GOOFED");
  }
}
would more commonly be written as:

Java code:
try {
  predictionsUnformattedArray = measureSlope.loadFile(predictedFile);
  statsUnformattedArray = measureSlope.loadFile(statsFile);
} catch(IOException e) {
  System.out.println("YOU GOOFED");
  throw new RuntimeException(e);
}
I'm re-throwing the exception here because it doesn't look like your program can recover from not being able to read the input files. A RuntimeException is a "unchecked" exception. They can be caught if you're looking for them, but they generally just go all the way back up the call-stack and tell your program that it's time to die. You don't have to declare what kinds of RuntimeExceptions you're throwing, nor do you have to put them inside a try block. They're generally looked at as the "unrecoverable" kind of exception, where as checked exceptions are thrown to give the programmer a chance to handle failure gracefully.


From a Java-conventions standard, Classes are named with capitol letters and methods are named with lower-case letters.

Gravity Pike fucked around with this message at 01:02 on Sep 15, 2013

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
quote != edit

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
Specifically the ArrayList<T>(Collection<? extends T> source) constructor creates a new list which contains the same objects as the source collection, in the same order that the source collection iterates over them. This means that you can create an ArrayList that contains the same elements that a Set contains, or the same elements that a LinkedList contains.

It's worth noting that these are literally the same objects, and while modifying the source list won't modify the new ArrayList, modifying one of the Objects in the source list will modify the Object in every list. Strings are safe, because strings are immutable; they can't change. However, if you had:

Java code:
class MyExample {
  public static void main(String[] args) {
    List<Dog> dogListOne = new ArrayList<Dog>();
    dogListOne.add(new Dog("Scrappy"));
    dogListOne.add(new Dog("Scooby"));
    dogListOne.add(new Dog("Snoopy"));
    
    List<Dog> dogListTwo = new ArrayList<Dog>(dogListOne);
    
    System.out.println(dogListOne.toString()); //{Scrappy, Scooby, Snoopy}
    System.out.println(dogListTwo.toString()); //{Scrappy, Scooby, Snoopy}
    
    dogListTwo.remove(0);
    
    System.out.println(dogListOne.toString()); //{Scrappy, Scooby, Snoopy}
    System.out.println(dogListTwo.toString()); //{Scooby, Snoopy}
    
    dogListTwo.get(0).setName("Lassie");
    
    System.out.println(dogListOne.toString()); //{Scrappy, Lassie, Snoopy}
    System.out.println(dogListTwo.toString()); //{Lassie, Snoopy}

    //The second object in dogListOne is the same object as the first object in dogListTwo
  }
  
  static class Dog {
    private String name;
    public Dog(String name) {
      this.name = name;
    }
    public String getName() {
      return name;
    }
    public void setName(String name) {
      this.name=name;
    }
  }
}

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
I hate to tell you to RTFM, but Java has really good documentation. You can basically google any classname, and among the first few results will be a detailed description of the class, it's complete hierarchy, and a complete description of all of it's methods.

JavaDocs posted:

public E remove(int index)

Removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices).

Specified by:
remove in interface List<E>
Overrides:
remove in class AbstractList<E>
Parameters:
index - the index of the element to be removed
Returns:
the element that was removed from the list
Throws:
IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size())

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
Is plural class names a convention that anyone actually follows? I mean, it's not Lists<Dog> bestDogsList = new ArrayLists<Dog>();. The only place you see plural class names are the static "Utility" classes in Commons/Guava, where they really want to put a bunch of static methods in the parent class. (ie Lists.newArrayListWithExepectedSize(10);)

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

Zeether posted:

I went back and wrote a method for the word search which uses loops for each direction, but it doesn't work right and I tried debugging with println() to see what was wrong and got nothing out of it. The loops are most likely wrong but I'm not sure which way and I haven't made ones to check diagonals yet.

http://pastebin.com/tzUi0ZiE

Did you make a copy/paste error? wordCheck is never getting called. wordToFind is getting set within a loop, but never used. You've also got logic errors, but I kind of feel like you should work those out on your own.

Learning a debugger is like a super essential skill, and it's pretty dang easy for straightforward cases like your own. Are you using an IDE, like Eclipse? Read this tutorial.

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

KildarX posted:

Thanks for the help guys been working on it steadily.

Java code:
:words:
So here's my code, and I got two problems, it seems that the regex isn't actually checking everything[I looked up the regex of someone who had the same requirements], it's checking for at least one case, flipping valid to true and going on, the second problem is when I am using the comparison between confirm and pwd it's giving me a null pointer? Any help?

Honestly, I wouldn't try to fit everything in one matcher. Regular Expressions are all about patterns, and that's not what you're interested in - you don't care whether the upper case letter comes before or after the digit, which is why you've got all of those bizarre non-capturing groups. I'd create 3 or 4 different patterns, and use Matcher.find() instead of Matcher.matches().


Here's a broad question/statement/poll: I really hate do/while's. Instead of:

code:
boolean valid = false;
do {
  valid = someComplcatedTest();
} while (valid == false);
I prefer:
code:
while (true) {
  if (someComplicatedTest()) {
    break;
  }
}
Maybe it's part of my recent "make everything (within reason) final/immutable" kick that I picked up from Scala. Is this terrible style? Anyone else have input?

Gravity Pike fucked around with this message at 07:48 on Oct 4, 2013

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

1337JiveTurkey posted:

Check if the length of password.replaceFirst("\\d", "").replaceFirst("[a-z]", "").replaceFirst("[A-Z]", "") is 3 less than the original length. :colbert:

Dear everyone,

I hate you. This is my loving code, don't you dare come near it.

Miss me when I'm gone,

Jive Turkey


(I am kidding. (Exactly as much as you are))

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

KildarX posted:

So I need to read in a text file, which has lines in format " name; category; cost; date;" take like categories and add the costs up and out put them as totaled.

I assume the best way to do this would be to take in each line as an array, compare the arrays at index 1 to a list of known categories and if they're alike add them up and store it as a float. Any help on how to do that or a better solution than what I got.

Personally, I'd read in each line as a String, and use String.split() to split the input on the semicolon. I'd then use a Map<String, Float> to associate each category with it's sum of costs.

@MrPablo: Since this is titled "lab 7", you should give hints, but probably avoid flat-out doing this guy's homework for him. :(

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

KildarX posted:

:sigh: I guess I'm over thinking it again, thought I was gonna be clever using arrays and crap.

Thanks for the help guys, back to drawing board.

So other people might fervently disagree with me on this statement, but, as a professional software developer: Never be clever.

There are many things that you can optimize for in your code: speed, memory usage, source lines, compile size. The most important is maintainability. If you think you're being clever, the person sitting next to you is going to read the code and think that it's confusing. Clever code causes bugs. Clever code eats up dev-hours as people try to parse through your logic. Clever code usually fails to foresee the product requirement that is going to be thrown at the codebase a few months down the line. Clever code takes somewhere between two and ten times as long to update as boring, idiomatic code.

By all means, be intelligent. Write smart code. But remember that your code is going to be read by other devs far more frequently that the one time that you write it. It not only has to produce the correct output, it has to, at a glance, look like it's going to produce the correct output.

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
You are kind of missing out on the major positive aspects of inheritance in your sample classes: abstract methods.

First off, inheritance means that you can stick a more-specific object in a less-specific variable:
Java code:
Quadrilateral q1 = new Square(); //a Square ALWAYS is-a Quadrilateral 
Square s1 = new Quadrilateral(); //compile-time error; a Quadrilateral MIGHT NOT BE a square.
With an abstract class, you're saying that everything that is this type of object will be able to implement a method, even if the method doesn't make sense on the abstract class itself.
Java code:

public abstract class Quadrilateral {
  public abstract Double getArea();
}

public class Rectangle extends Quadrilateral {
  //...
  @Override
  public Double getArea() {
    return getLength() * getHeight();
  }
}

public class Trapezoid extends Quadrilateral {
  //...
  public Double getArea() {
    return getSumOfLenghts() * getHeight() / 2;
  }
}
Note that since Quadrilateral is abstract, you can't instantiate it. It doesn't make sense for you to have something that's just a Quadrilateral; you wouldn't know what it looks like! Instead, you can have things that are different kinds of Quadrilaterals, and can all be used in similar ways.


Put these two concepts together, and you can do things like:
Java code:
// pretend these are initialized properly
Quadrilateral[] myShapes = {new Rectangle(), new Rectangle(), new Trapezoid(), new Square()};

int sumOfAreas = 0;
for (Quadrilateral q : myShapes) {
  sumOfAreas += q.getArea();
}

System.out.println("All of myShapes take up a combined area of: " + sumOfAreas);

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

BexGu posted:

Any one know of any java classes that do the same things (or similar) to this Python script? (Creating Human readable UUIDs)

https://github.com/zacharyvoase/humanhash

Google is turning up like 2 people who have done a Bubble Babble assignment. Beyond that, you might be best off reimplementing that Python script on your own.

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
The Guava Throwables library has a nifty convenience operation for this use case:

Java code:
try {
    myDangerousOperation();
} catch (Exception e) {
    Throwables.propagate(e);
}
which basically expands to:

Java code:
try {
    myDangerousOperation();
} catch (Exception e) {
    if (e instanceof RuntimeException) {
        throw e;
    } else {
        throw new RuntimeException(e);
    }
}

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
I mean, absolutely, there is a science to propagating exceptions, and generally wrapping everything in a RuntimeException is the wrong thing to do. On the other hand, we have UnsupportedEncodingException. It is checked, and explicitly gives me a chance to react to it. Now, I'm asking for UTF-8. I know that I have access to UTF-8. It is utterly unreasonable to force everything at a higher level to deal with the possibility of an UnsupportedEncodingException. But it is also insanely unsafe to write code that would just swallow this exception, even though I know it'll never actually be thrown. So I wrap it in a RuntimeException, and get to ignore it, and still feel confident that the system isn't ignoring it, and it'll bubble up to a point where someone (the server framework, usually) will transform it into a useful response. (500 Server Error) (If you take issue with UnsupportedEncodingException in this instance, feel free to substitute NoSuchAlgorithmException.)

The law of the land is to propagate checked exceptions that calling code has a reasonable expectation of being able to recover from. If one of my arguments is the encoding, yeah, pass along that Exception so maybe my caller can ask for a different one. But if you just bubble up every possibly thrown exception in your method signature, you're preventing your users from seeing what is actually likely, and obscuring their options for recovering from any given exception.

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

Woodsy Owl posted:

Is there an elegant way to escape the blocking java.net.ServerSocket.accept() ? I've got a thread dedicated to listening and it's got something like this going on:

Disclaimer: I've never worked with sockets, and am approaching this purely as a "blocking call" problem. That being said, it seems to me like you could socket.setSoTimeout(somethingLow), and then just deal with your regular, expected SocketTimeoutExceptions.

Java code:
this.serverSocket = new ServerSocket(1234);
serverSocket.setSoTimeout(10);
while (!Thread.interrupted()) {
    Socket socket = null;
    try {
        socket = serverSocket.accept();
    } catch (SocketTimeoutException expected) {
        continue;
    }
    new DoStuffWithSocket(socket).start();
}

This will basically give you a 10 ms of trying to accept before you go back and check the thread's interrupted status. Is this what you were trying to do?

Gravity Pike fucked around with this message at 23:09 on Nov 16, 2013

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

Woodsy Owl posted:

What's the goonsensus on this? I'm still following the Java style guide just because when I'm reworking the conditional's instructions I don't have to worry about forgetting to add brackets.

In general, best practice is to follow the style guide, even where you personally disagree. If you're in an environment where you have a shared codebase (which basically every environment is, eventually), consistency plays a bigger role in readability than just about any other factor. Maybe you will remember to add the braces, but are you willing to bet that the next person to come along will? Will they be able to spot, at a glance, where their mistake is?

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
Well, it seems that you've implemented a For-Switch, which is a common enough mistake that it's got its own wikipedia page. It's a good way to exercise both of those control structures, but you generally want to choose whether you're doing something sequentially or in a loop. ("Both" is the wrong answer.)

In Comptuer Science we count starting at 0. In Java, we name classes starting with a capitol letter, in CamelCase, using full words. I can't see where you're using keybd to gather input at any point in time... unless it's in the Cat class? It's good practice to have "setter methods" accept an argument, rather than gather their own data. This way, you can load values from a database, or a text file, or by randomly generating them, and still use the same Cat class and setters.

I implemented a simple solution before I re-read your line that says you don't use Arrays yet. (That is crazy. Using arrays makes this simpler.) Arrays (or their big-brothers, Collections) are the correct way to manage storage of many of the same type of thing.

Java code:
public class CatDriver {
	public static void main(String[] args) {
		Scanner keybd = new Scanner(System.in);
    Cat[] cats = new Cat[3];

    for (int i = 0, i < 3, i++)
    {
      System.out.println("Enter the name of Cat " + i + ": ");
      String name = keybd.nextLine();
      System.out.println("Enter the age of Cat " + i + ": ");
      int age = keybd.nextInt();
      System.out.println("Enter the weight of Cat " + i + ": ");
      double weight = keybd.nextDouble();
      System.out.println("Enter the breed of Cat " + i + ": ");
      String breed = keybd.nextLine();
      System.out.println("Does the cat have claws? True or False?");
      boolean claws = keybd.nextBoolean();
      
      Cat myCat = new Cat();
      myCat.setName(name);
      myCat.setAge(age);
      myCat.setWeight(weight);
      myCat.setBreed(breed);
      myCat.setClawed(claws);
      
      cats[i] = myCat;
    }
  }
}
I guess you could use a switch to create a ghetto-array:

Java code:
  Cat cat0 = new Cat();
  Cat cat1 = new Cat();
  Cat cat2 = new Cat();
  
  for (int i = 0; i < 3; i++) {
    Cat currentCat;
    switch (i) {
      case 0:
        currentCat = cat0;
        break;
      case 1:
        currentCat = cat1;
        break;
      case 2:
        currentCat = cat2;
        break;
      default:
        throw new RuntimeException("THERE ARE TOO MANY CATS!");
        
    }
    
    currentCat.setName(name);
    //etc
    
  }
... but this is Too Much Work in order to achieve the same result. If you can't use arrays, could you use a function?

Java code:
public class CatDriver {
	public static void main(String[] args) {
		Scanner keybd = new Scanner(System.in);
    Cat cat0 = buildCat(keybd, 0);
    Cat cat1 = buildCat(keybd, 1);
    Cat cat2 = buildCat(keybd, 2);

  }
  
  private Cat buildCat(Scanner scanner, int catNum) {
    System.out.println("Enter the name of Cat " + catNum + ": ");
    String name = scanner.nextLine();
    System.out.println("Enter the age of Cat " + catNum + ": ");
    int age = scanner.nextInt();
    System.out.println("Enter the weight of Cat " + catNum + ": ");
    double weight = scanner.nextDouble();
    System.out.println("Enter the breed of Cat " + catNum + ": ");
    String breed = scanner.nextLine();
    System.out.println("Does Cat " + catNum + " have claws? True or False?");
    boolean claws = scanner.nextBoolean();
    
    Cat myCat = new Cat();
    myCat.setName(name);
    myCat.setAge(age);
    myCat.setWeight(weight);
    myCat.setBreed(breed);
    myCat.setClawed(claws);
      
    return myCat;
  }
}

Gravity Pike fucked around with this message at 08:16 on Dec 10, 2013

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

Bullio posted:

It meets the requirements, so I should get a proper grade for it, but I was hoping I could learn from you guys what I could do better with the tools at my disposal. Also, what books would you recommend? I like Java, but I'm really only relying on it as a stepping stone to learn how to program before focusing on learning another language entirely. The posts I've read here have been way informative and I look forward to delving deeper into the programming world.

Effective Java is a great Java book, as is Java Concurrency in Practice. The thing is, I'm not sure whether they'd be of a whole lot of use to you at this point; they expect kind of a lot of background knowledge that you just don't have yet, and they give you guidelines to solve problems that are beyond your skillset. Honestly, I'd probably go with the official Java Tutorials, paying a whole lot of attentions to "Getting Started" and "Language Basics." Having a very strong grasp of "Collections" is essential; these are your bread-and-butter tools for everyday programming. Date and Time functions are... well... there. Java's built-in Date object really isn't that great, tbh. (All the cool kids use the JodaTime library.)

And don't discount Java completely; it's not the newest, hottest language, but it is mature, which means that a lot of us make a living writing Java code. There are libraries to do basically anything in Java, and tools that work well surrounding the platform. A good programmer is language-agnostic; they'll be able to write in basically any language, given a while to study up on it, and have two or three at their fingertips to perform a wide variety of tasks. Having been on the interview-loop for a while, at my company we're looking for developers who are solid in any language, have a decent grasp of a scripting language to do simple tasks, and are familiar enough with bash to do very simple tasks without even writing a program in the first place.

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
Bash is the default linux terminal. Knowing how to pipe together simple commands like grep, sed, sort, uniq, wc in order to filter and reduce data is a very important skill to practice. Not a day goes by where I don't do something like log onto a load-balancer and, grep ' 500 ' load_balancer.log.2013-12-01* | grep -oP 'userid/\w+' | sort | uniq | wc -l to figure out how many unique users were affected by server errors in a given day. (Roughly, "Search through all files starting with load_balancer.log.2013-12-01 for lines containing ' 500 ', then take the parts of those lines that are the string 'userid/' followed by any number of letters and numbers, and then sort those alphabetically, and then remove duplicates, and then count the number of lines.") You could have written a Java program to do that, but you'd waste a whole lot of time worrying about things like reading from files, and looking up how to do directory manipulation, and deciding on data structures, and saving your code somewhere, and compiling, when you could have taken thirty seconds on the command line to do the same thing using tools that someone else already wrote.

Command line skills are a bit harder to pick up than programming, because there's often not a class that specifically teaches them. On the other hand, each command tends to be very simple, and you only need to know a few commands in order to accomplish 90% of what you'd ever want to do from the command line.

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

Sab669 posted:

Any recommendations on some absolute bare-bones First Programming Language books for Java? My roommate is going into his second semester of Comp Sci and he's really struggling. Decided to wait until the last week of vacation to buy a book and try to get back into it before the next semester starts :v:

Java, A Beginner's Guide seems to have good reviews.

Honestly, I think the Oracle turorials are pretty decent. (Scroll down to "Trails Covering the Basics".) Comp Sci II doesn't cover anything more complicated than, like, Generic Collections, right? It's been forever.

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

DholmbladRU posted:

This seems pretty trivial but I cant figure it out. How do you keep carriage returns from being removed from bufferedreader?


This is a perfect oppurtunity to use the Apache Commons IOUtils class:

Java code:
InputStream contentStream = (InputStream) connection.getInputStream();
String content = IOUtils.toString(contentStream);
This is not a problem that has never been solved before. No need to re-invent the wheel.


Fake Edit:

Also, if you're going to be looping through the file like that, you really ought use a StringBuilder instead of concatenating strings. Since a String is immutable, what that does is allocate memory for the first line, and write the first line's worth of characters to that memory. Then it allocates enough memory for the first two lines, and copies the first two lines worth of characters to that memory block. Then it allocates enough memory for the first three lines, and copies those three lines to memory... You end up writing something like (lines^2 * average-line-length) characters. If you use a StringBuilder, it saves a reference to each String, and only when you call toString does it allocate enough memory to hold everything put together.

Java code:
String line;
StringBuilder sb = new StringBuilder();
while ((line = reader.getLine()) != null) {
    sb.append(line);
    sb.append("\n"); // or whatever
}
String content = sb.toString();

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

rhag posted:

The java compiler (at least from Sun/Oracle) has been able to see these kind of patterns since jdk 1.4 or so. It generates code that is using the stringbuilder, no need to worry. Still, it is a good habit to have, to not concatenate strings just for the sake of it.

Huh, that's neat. I knew the compiler could do that for things like
Java code:
String msg = "Why hello there, " + name + ", you're looking particularly " + adjective + " today!";
but I had no idea that it was going to figure out loops for me.

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
There is a logical error, not a syntax error. (Syntax errors won't even compile in Java!) I have a feeling that you could catch your own error with a bit of testing. Tests should be simple. They should generally test one thing. Two is an easy number to work with in this case. Ask your program what 2^0, 2^1, 2^2, and 2^3 are. You're going to get wrong answers for some of them, but the pattern should make it pretty easy to work out what's happening.

Adbot
ADBOT LOVES YOU

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

Sagacity posted:

I've been dicking around with Java recently and I ran into a weird problem.

I had defined a JUnit test that did initialization using a setup function that I annotated with @Before. I derived this test class from an abstract superclass that also had a @Before method. In the setup method in my derived class, I explicitly called the superclass' setup method. This is wrong, since JUnit will automatically do this.

However, it worked as expected on Windows, but didn't work on Ubuntu, even though I was running the same Java JDK version.

Apart from clearly being a bug on my end, what could be causing the different behavior on the different OSes? Or should I just chalk it up to 'it's undefined behavior so meh'?

It is well-defined that the @Before methods of the superclass will be run before the @Before methods of any subclass; however, I have seen weird behavior if your subclass Overrides the superclass's setup method, and both are annotated @Before. ie

Java code:
public abstract class BaseTest {
  @Before
  public void setup() {
    ...
  }
}

public class MyUnitTest extends BaseTest {
  @Before
  @Override
  public void setup() {
    ...
  }
}
In these cases, I just make sure to name the child class's @Before method something different.

Gravity Pike fucked around with this message at 21:46 on Feb 1, 2014

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