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
1337JiveTurkey
Feb 17, 2005

icehewk posted:

After six weeks of my first programming course, I know absolutely nothing. The instructor doesn't teach along with the book, nor does he teach much of the ideas behind the code. To borrow a lovely analogy, it's like he goes over what you can nail where without explaining where the spot to be nailed is located or why it's being nailed. As such, I've taken it upon myself through the resources provided here to learn Java outside of class and hope I can catch up before the next project is assigned. Unfortunately, my latest project is due Wednesday and I don't know where to begin. Can you guys help?

OK. With objects, what you're doing is describing their behavior, so that if you've got r1 and you add it to r2, you explain how the sum is found with plus(). I'll show you how to make an invert() function, something which isn't part of your assignment but is useful for a RationalNumber class. In order to invert a number, we make its numerator equal to the denominator and the denominator equal to the numerator.

code:
public class RationalNumber {
  // Other stuff is up here
  public void invert() {
    // If the reason for temp isn't clear, work out why by hand
    int temp = numerator;
    numerator = denominator;
    denominator = temp;
  }
}
This says whenever we have an object which is a RationalNumber, we can invert it by switching the numerator and denominator. In the case of an object r1, you'd do so by calling r1.invert(); In the assignment, the instructor wants you to do this for addition, subtraction, multiplication and division. However, since these have two numbers, you refer to the second number as r in the function, and its numerator and denominator are r.numerator and r.denominator respectively. Are there any specific problems you're having?

Adbot
ADBOT LOVES YOU

1337JiveTurkey
Feb 17, 2005

icehewk posted:

It would be a+c when b=d. How would you go about finding the LCD? Is the data field the part that corresponds to a, b, c and d?

Don't worry about least for the moment, just common.

1337JiveTurkey
Feb 17, 2005

ynef posted:

Depending on your game and what it will support in the future, I'd say that Player should be an abstract class and that you should subclass it with a Fighter and an Archer class. The reason (which may not be valid in your case) is that, for instance, you'll want to give all archers a bonus for ranged weapons or restrict so that fighters can't used crossbows (whatever). If you stick to using conditional statements (if, switch) then you will quickly get a headache trying to code all these rules that will be easily avoided if you just go with the subclassing. Also, the constructor for each class will be very simple and you can still keep the toString() method (which you should use) in the abstract Player class. Adding more types of Player will be ridiculously easy too.

If you go that route, keep in mind that you need to change all attributes in Player to "protected" for subclasses to access them.

Simple parameterization is a good start. One of the pitfalls of using inheritance with this is if you try something like races and classes for dwarven warriors or elven wizards, you end up with DwarfWarrior, ElfWarrior, DwarfWizard and ElfWizard. All this effort writing out almost-identical code makes programming with Java seem staggeringly inefficient. It's even worse if you're doing player-controlled versions and computer-controlled versions. Lots of people do that and then think that inheritance is only useful in a few cases when nothing could be further from the truth.

You'll often hear the terms is-a and has-a with classes and inheritance. A Wizard is-a Player or an Archer is-a Player, or a WizardArcher is-a Wizard and is-a Archer (and by extent is-a Player). Inheritance describes is-a relationships. On the other hand, a player has-a equippedWeapon or has-a wornArmor. Fields in a class describe has-a relationships. However, we can also say that a Player has-a Job and has-a Race, and a Wizard is-a Job, Warrior is-a Job, and Elf is-a Race and Dwarf is-a Race. The two can even be simply concrete instances of one parent class using parameters if there's nothing majorly different between the two.
code:
// Early on in design we just change some numbers
Race ELF = new Race("Elf", 10,10,15,5);
Race DORF = new Race("Dwarf" 10,5,15,10);

// Later on we can split them into their own subclasses
Race ELF = new CookieBakingRace("Elf",10,10,15,5);
Race DORF = new ShortHairyRace("Dwarf",10,5,15,10);
Now if you call ELF.getBaseStrength(), you don't know if it's actually Race.getBaseStrength() or CookieBakingRace.getBaseStrength() but as long as both classes do the same thing, you won't notice the difference.

1337JiveTurkey
Feb 17, 2005

nnnotime posted:

For plain Java, Eckel's Thinking in Java was recommended earlier in this thread, and I noticed his 3rd edition, published in 2002, is available for free but his 4th edition is not free. Here's a link to the third edition, which has link to 4th edition page:
http://www.mindview.net/Books/TIJ/

Are there any significant differences between Eckel's 3rd and 4th editions that I should consider purchasing the 4th edition instead? I don't mind spending money if I will be able to obtain the latest-and-greatest information.

In 2002, it'd be talking about Java 1.3 or 1.4 (both are pretty drat old). I wouldn't look at anything which talks about Java before 1.5 except for purposes of maintaining legacy code. Even with legacy code 1.4.2 is as old as I'd venture and I'm hoping to avoid having much to do with my company's clients still stuck on 1.3.1. It's still important to know when certain things came into being or became usable (Ask me about JAXB 1.0), but new code should be predominantly written with the newer versions of the language.

quote:

How useful are Sun's Java Learning Center pages?
http://java.sun.com/learning/index.html

The Sun documentation can be pretty good, although I'm not a fan of their XML/Web Services tutorials and security is just a nightmare regardless. Learning the (very) extensive APIs should probably be one of your first goals. Start out with something simple and sane like java.util.logging and slowly expand your horizons outwards.

1337JiveTurkey
Feb 17, 2005

TRex EaterofCars posted:

I'm curious what that client's excuse for sticking with Java 1.3 is. Did they use some Sun internal API that got removed?

We only guarantee certain versions of our software against certain JVMs, and nobody wants to do the full testing process against 1.4.2 even though in principle it shouldn't break anything. Moving them up to a newer version would be tough since they've got lots of bugfixes by the custom development team (my group) which should have been backports by the core development team. Since there have been a huge number of bugfixes and tweaks in the years between releases, there's a lot of risk that the two sets of bugfixes would be incompatible. Since there's a major release that will break compatibility with most of our older code coming around the corner next week, the hope is that we can leapfrog the previous versions and go straight to Java 1.5. It's an improvement at least.

1337JiveTurkey
Feb 17, 2005

FearIt posted:

I'm typing 'objectsName.' in my IDE (eclipse) and when the list of methods comes up none of them are clone(). The object is a class I defined myself, would I need it to implement something for .clone() to work? Or alter my class in someway?

You want to implement the java.lang.Cloneable interface. That's enough to clone() an object without any work on your part. Many people dislike it because they feel that it allows you to gloss over the implications of clone() with regards to how your objects behave. In particular a shallow copy of the fields might not be what you wanted. There are a couple of alternatives which work: Creating a constructor which takes another instance of the object (or even an implemented interface) offers you the chance to make it a deep copy if you want to as well as share any immutable data. Immutable objects are also a possible alternative. If you're not constantly modifying a class of objects, you can get around all of that by just creating a new object for every change. Immutable objects work well with each other because any two objects can share a third object without needing to worry if the third object will change underneath them. This reduces memory usage requirements and makes it easier to turn other objects immutable if all of their fields are immutable.

1337JiveTurkey
Feb 17, 2005

ColdPie posted:

Basically a utility function that compares two strings in different ways based on the bitflags. The code's for work, so I don't have it on me, but the flags are something like COMP_CASE_INSENSITIVE, COMP_BEGINS_WITH, COMP_ENDS_WITH, COMP_CONTAINS and so on. It's a whole lot easier to maintain one function and a couple bitflags than a few dozen functions with various combinations of the above options. The functions signature is essentially static void compare(String expected, String found, int flags).

That sounds like something which might be more efficiently described with java.util.regex.

1337JiveTurkey
Feb 17, 2005

fletcher posted:

Thank you to all the replies about my previous question. I've got another one for you guys.

I want to find unique values from a collection SomeCollection. Right now I'm just iterating through the collection and throwing every value into a HashMap<String, String> SomeUniqueCollection, where the key and value are both the key from SomeCollection. Should I be using a different type of collection for SomeUniqueCollection since I don't really need a K,V but just a K? Or is there a better way to approach this?

HashSet does exactly what you're looking for.

1337JiveTurkey
Feb 17, 2005

Thlom posted:

Sorry for wasting your time, I will go and throw my self out of the window now.

Just make sure you haven't dispose()d your Graphics2D context first.

1337JiveTurkey
Feb 17, 2005

mister_gosh posted:

I am running a third party command line based application through a Runtime call. This is using Java1.4. Essentially I have:

Process p = Runtime.getRuntime().exec("cmd.exe /c "+thirdPartyCommand);

The command takes about 2 seconds to run but in order to complete the command, it prompts you with a yes or no question. I always, programmatically, want to answer "y", but how do I pass that to the single Runtime command?

To clarify, currently I am running this third party application but want to serve the application to my users through a servlet. So I figured I would just use a Runtime system call, but I forgot about the yes/no prompt that needs to be answered in order for the application to finish.

Thanks in advance!!

Just call p.getOutputStream() (keeping in mind that the OutputStream is really the InputStream for the other process) and then wrap the Stream you get in a BufferedWriter or whatever and then send a 'y' through that. Then you can wait for it to finish with p.waitFor which returns the exit value of the terminated process.

1337JiveTurkey
Feb 17, 2005

Avenging Dentist posted:

Maybe there's a Java library to interface with the Windows registry? :v:

I haven't messed around with it personally, but you want java.util.preferences for that. True to Java form, it's designed to be cross-platform and scalable so it also supports LDAP and XML config files.

1337JiveTurkey
Feb 17, 2005

What that's doing is getting a static or class method and then calling it without any arguments. Since a static method has no underlying object to invoke it upon, the argument may be null. Since the static method also has no parameters, that's why you're seeing methodStatic.invoke(null, null). The reason for this is most likely because the person writing the code wanted to be able to call the same method from a class specified and loaded at runtime. That code would work, but it's not the standard idiom, where you'd define an interface and then instantiate the interface with a zero-argument constructor.
code:
MyInterface myInstance = null;
try {
	// JAR files are accessed through a URL object
	ClassLoader cl = new URLClassLoader(myURLs);
	Class<MyInterface> myClass = cl.loadClass(myClassName);
	// Reflective equivalent of zero-arg constructor
	myInstance = myClass.newInstance();
// This keeps the containing class from needing to declare these exceptions
} catch (SecurityException e) {
	throw new RuntimeException("Insufficient permissions.", e);
} catch (ClassNotFoundException e) {
	throw new RuntimeException("Class doesn't exist.", e);
} catch (InstantiationException e) {
	throw new RuntimeException("Class has no zero-arg constructor.", e);
} catch (IllegalAccessException e) {
	throw new RuntimeException("Cannot access constructor.", e);
}
// At this point you've got a regular object ready for use
myInstance.myMethod();
This does seem a bit more elaborate, but the advantage is that at the bottom you don't need to worry about myInstance.myMethod() ever failing for any reason related to reflection. At that point it's virtually indistinguishable from any normal class except for the issue of their having differing ClassLoaders (This should never be an issue in any remotely sane program). The performance is also substantially better if you're calling that method very often since only instantiation is dealt with through reflection.

1337JiveTurkey
Feb 17, 2005

Led posted:

I don't know if this is the right thread, but does anyone want to test my Java applet for me ?
I heard some people had problems with it, especially on other operating systems.
(I've only tested it locally on windows)

it's at http://www.supercheckmate.com (but it has nothing to do with chess :))

OSX 10.5 on a G5 iMac failed to initialize the applet and provided no error console message. I'm running Java 5 and have enough porn lying around to cripple some filesystems.

1337JiveTurkey
Feb 17, 2005

shodanjr_gr posted:

How can i detect when a JFrame closes "for good".

I know about the WindowListener adn looking for a Window_closing event. Thing is, i want my app's defaultOnCloseOperation to be HIDE_ON_CLOSE, but i want to be able to catch the event when the app "shuts down" and do some finalization stuff...

Ideas?

If you want closing that window to end the application, then you want the default operation to be DISPOSE_ON_CLOSE. HIDE_ON_CLOSE is for when you foresee yourself showing it again in the near future and don't want to incur the expense of disposing one window and creating a new one a short time later. If you want it only sometimes to close the application and other times not to, then I'd suggest reconsidering that aspect since it will be quite confusing to users for their program to only sometimes shut down when they close the window.

1337JiveTurkey
Feb 17, 2005

I think that SwingUtilities.isEventDispatchThread() is exactly what you guys are looking for.

1337JiveTurkey
Feb 17, 2005

Just make the button create a new JFileChooser. Call showOpenDialog() and if the return value is equal to APPROVE_OPTION, then getSelectedFile() will have the File they selected without the need for extra JFrames or message passing.

1337JiveTurkey
Feb 17, 2005

mister_gosh posted:

The second JFrame with JTree selection is used to select a "file" within an oracle database. I need to control whether the Ok button is enabled or not due to the type of object selected.
If you're using an Action or AbstractAction for the button, have it implement ChangeListener for whatever component has the object selected in question and then have that method call setEnabled() based on whether you want it working or not. You can also keep a local copy of it I guess so that your action callback doesn't need to refer to the other dialog again.

quote:

I haven't used JFileChooser, but I'm guessing the API isn't robust enough to handle these requirements.
Yeah. I tried that as an FTP interface and it didn't work at all.

1337JiveTurkey
Feb 17, 2005

It's a shallow copy because there's no way for the implementor to really know what the cloning semantics of your keys and values are. Requiring everything put in the HashMap to implement Cloneable or having one HashMap for Cloneables and one for non-Cloneables would make collections less generally useable. The alternative would be having a clone() method which does a deep copy when its contents implement Cloneable and a shallow copy otherwise would just be inviting trouble. In other words, you're going to have to do it manually.

1337JiveTurkey
Feb 17, 2005

Did you fully qualify the name? You can't just say GetUserNames if it's actually com.example.GetUserNames, then you need to add that so it knows what package to look in. If it goes above 70 characters (I think this is the right number), then you should truncate the line at that point and continue on the next, leading with a whitespace. Here's an example created by Ant that I built yesterday:

code:
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.7.0
Created-By: 1.4.2_15-b02 (Sun Microsystems Inc.)
Built-By: REDACTED
Main-Class: com.REDACTEDREDACTEDREDACTED.document.NewModelCreateDocume
 ntAction
Class-Path: REDACTED.jar REDACTED.jar REDACTED.jar

1337JiveTurkey
Feb 17, 2005

The idea with packages is that they mirror your file structure. So you have a folder under your source root called 'com', a folder under that called 'example' and under 'example' you put your source file 'ExampleFactoryStrategy.java'. When you compile, the output would go in an output directory with the same 'com' and 'example' folders. When you want to refer to that class, you've got to call it 'com.example.ExampleFactoryStrategy' for it to be able to distinguish it from potentially many files named that in the JAR. If you look through the JAR files in your JRE, you can see how the folder structure is parallel to that of the packages in the Javadoc. That's how the ClassLoader finds your file: It looks in the JAR for the folder corresponding to your package and then looks for the class file with the right name inside that folder. If you don't have the right files in the right folders in your JAR file, then it won't be able to find it and you'll get that error.

1337JiveTurkey
Feb 17, 2005

Apache Derby claims to be fairly lightweight but I don't have much experience with it.

1337JiveTurkey
Feb 17, 2005

TRex EaterofCars posted:

This is pretty much exactly what web services are meant to do. Secure, abstracted, simple (for various values of simple).

If it's some practice toy app for fun running on a local network, there's nothing wrong with just opening a socket to the server and passing serialized objects for messages.

1337JiveTurkey
Feb 17, 2005

Boz0r posted:

How do I execute an external application with or without parameters?

Runtime.exec() runs the command given with cmdarray being the command name and the command line arguments passed to it. There's also an optional array of environment variables and an optional directory to run it in. The return value is an object used to control the spawned process.

ProcessBuilder is an object which you can set everything for beforehand and then just call start() repeatedly to spawn any number of processes.

1337JiveTurkey
Feb 17, 2005

Pesch posted:

Is there a platform independent way to open a text file using the default system text editor?

Barring that, how difficult would it be to set up some swing components to display text files? I have very little experience with GUI programming or Swing.

java.awt.Desktop supports browse(), edit(), mail(), open() and print().

The Swing component you're looking for is called JTextArea. The simplest way to put data into it would be to use the default backing Document and then repeatedly append() lines from a file to the end. That works up to several megabytes. If the file's too big for that, Document does support alternative backing methods like just mapping a file into memory and using that as the Document model. That's probably far more difficult than most people would care to implement.

1337JiveTurkey
Feb 17, 2005

Are you running on an application server such as JBoss? Also, what's the exact error or exception you get? There should be a stacktrace somewhere which tells what went wrong, and that will go a long way towards solving your problems.

1337JiveTurkey
Feb 17, 2005

If you're interfacing with native code, make sure that you're using the code exactly like the authors intended. For instance if the library authors just translated some code over using the idioms of the other language without modification, you may be expected to call some cleanup code after every invocation.

1337JiveTurkey
Feb 17, 2005

Fruit Smoothies posted:

Hey guys, I'm basically a pascal / C kinda guy, and I've just had this java applet planted on me. It has a bug, which I have narrowed down by decompiling (DJ) one of the class files in a cab file.

A .cab file? That's new to me. Usually applets are deployed as .jar files. Nevertheless, you could make a project in NetBeans or Eclipse with nothing of its own but containing the .jar file as a library. You can then navigate to the class files in the source tree and they should show the information available at link time and at run time for every single class. Then set the IDE to run the applet, and you should be able to use the debugger, although it may not give much in the way of useful information. The class you want to run as an applet can be found from the tag used to embed the Applet in the web page.

quote:

Naturally, all the strings are named systematically, and I have no idea where the values I'm looking for are. (There are many global variables)

OK, from your use of the term global variables, it sounds like you're thinking of things in a C/Pascal way. There are a million tutorials out there, but for the moment, you can think of objects like records and classes as types of records. I can go into more detail later and answer any questions you might have as well.

quote:

What are my options for debugging a java applet that's already been "compiled"?

Outside of decompiling like you have, the NetBeans/Eclipse project I mentioned earlier has another use. You can get all that information from the .class files because Java keeps it around so that it can dynamically link everything. That means you can also make your own code that links against those class files and verifies that they do what you think they do.

quote:

Sorry for my blinding ignorance.

You're doing pretty good for not knowing the language or having the source, actually.

1337JiveTurkey
Feb 17, 2005

Fruit Smoothies posted:

Ok, so I downloaded Eclipse, and I imported the jar file into a library, however it doesn't seem to be decompiling or showing the functions within. Is this supposed to happen? Or do I need to use the decompiled versions?

EDIT: When I open it, it says damaged / corrupt.

Make sure that instead of opening it, you're importing it into the project. Go to the File menu, then select Import... and then from the list of options, select import archive and pick the .jar file. If that doesn't work and you can extract everything by unzipping it, then you can just import the directory tree containing the .class files. You should then see the folders under your package manager and you can look at the specific classes. Since it can't match them back to a source file you'll get something saying Source not found but then it'll list some data like:

code:
// Compiled from Scheduler.java (version 1.4 : 48.0, super bit)
final class org.drools.common.Scheduler {
  
  // Field descriptor #19 Lorg/drools/common/Scheduler;
  private static final org.drools.common.Scheduler INSTANCE;
  
  // Field descriptor #21 Ljava/util/Timer;
  private final java.util.Timer scheduler;
  
  // Method descriptor #23 ()Lorg/drools/common/Scheduler;
  // Stack: 1, Locals: 0
  static org.drools.common.Scheduler getInstance();
    0  getstatic org.drools.common.Scheduler.INSTANCE : org.drools.common.Scheduler [1]
    3  areturn
      Line numbers:
        [pc: 0, line: 45]
  
  // Method descriptor #27 ()V
  // Stack: 4, Locals: 1
  private Scheduler();
     0  aload_0 [this]
     1  invokespecial java.lang.Object() [2]
     4  aload_0 [this]
     5  new java.util.Timer [3]
     8  dup
     9  iconst_1
    10  invokespecial java.util.Timer(boolean) [4]
    13  putfield org.drools.common.Scheduler.scheduler : java.util.Timer [5]
    16  return
      Line numbers:
        [pc: 0, line: 62]
        [pc: 4, line: 63]
        [pc: 16, line: 64]
      Local variable table:
        [pc: 0, pc: 17] local: this index: 0 type: org.drools.common.Scheduler
  
  // Method descriptor #31 (Lorg/drools/common/ScheduledAgendaItem;)V
  // Stack: 6, Locals: 4
  void scheduleAgendaItem(org.drools.common.ScheduledAgendaItem item);
     0  new java.util.Date [6]
     3  dup
     4  invokespecial java.util.Date() [7]
     7  astore_2 [now]
     8  new java.util.Date [6]
    11  dup
    12  aload_2 [now]
    13  invokevirtual java.util.Date.getTime() : long [8]
    16  aload_1 [item]
    17  invokevirtual org.drools.common.ScheduledAgendaItem.getRule() : org.drools.rule.Rule [9]
    20  invokevirtual org.drools.rule.Rule.getDuration() : org.drools.spi.Duration [10]
    23  aload_1 [item]
    24  invokevirtual org.drools.common.ScheduledAgendaItem.getTuple() : org.drools.spi.Tuple [11]
    27  invokeinterface org.drools.spi.Duration.getDuration(org.drools.spi.Tuple) : long [12] [nargs: 2]
    32  ladd
    33  invokespecial java.util.Date(long) [13]
    36  astore_3 [then]
    37  aload_0 [this]
    38  getfield org.drools.common.Scheduler.scheduler : java.util.Timer [5]
    41  aload_1 [item]
    42  aload_3 [then]
    43  invokevirtual java.util.Timer.schedule(java.util.TimerTask, java.util.Date) : void [14]
    46  return
      Line numbers:
        [pc: 0, line: 75]
        [pc: 8, line: 77]
        [pc: 37, line: 79]
        [pc: 46, line: 81]
      Local variable table:
        [pc: 0, pc: 47] local: this index: 0 type: org.drools.common.Scheduler
        [pc: 0, pc: 47] local: item index: 1 type: org.drools.common.ScheduledAgendaItem
        [pc: 8, pc: 47] local: now index: 2 type: java.util.Date
        [pc: 37, pc: 47] local: then index: 3 type: java.util.Date
  
  // Method descriptor #27 ()V
  // Stack: 2, Locals: 0
  static {};
     0  new org.drools.common.Scheduler [15]
     3  dup
     4  invokespecial org.drools.common.Scheduler() [16]
     7  putstatic org.drools.common.Scheduler.INSTANCE : org.drools.common.Scheduler [1]
    10  return
      Line numbers:
        [pc: 0, line: 33]
}

1337JiveTurkey
Feb 17, 2005

Use TCP instead? Otherwise, use NIO with the ByteBuffer and make an OutputStream that appends anything sent to it to the ByteBuffer and force out a datagram every time the ByteBuffer won't take any more bytes.

1337JiveTurkey
Feb 17, 2005

Convert by changing the string to a byte array, then using the array to construct a BigInteger.

1337JiveTurkey
Feb 17, 2005

Read a constant number of bytes at a time, every time. The number should be defined for the algorithm as the block size.

1337JiveTurkey
Feb 17, 2005

Bill O'Riley is GENIUS posted:

Yeah, but there's no guarantee of the size of the ciphertext blocks. If I'm using a 128-bit modulus each encrypted character could be of any size less than that.

The way it's expected to be done is you use the asymmetric encryption to transfer the session key which is a symmetric cypher. Then you use that to encrypt the actual file. Asymmetric encryption is just too slow to use on its own.

1337JiveTurkey
Feb 17, 2005

The idea is that you always use a block size smaller than the actual key and then give it a predetermined padding. When the recipient gets the message, they decrypt the message block, remove the padding, and then have the message. The encoded message would need to be transmitted with the length of the encrypted message in bytes sent first so you know where the end is. In practice you don't end up doing this multiple times because the algorithm's so slow. Instead you'd send a securely randomly generated key (called the session key) for some other algorithm like AES. That way you'd only need to encrypt one message giving the algorithm type, the key, and the nonce (one time number used to initialize the algorithm). Then the receiver gets that key and you use the shared session key to encrypt the real message. AES and other similar encryption algorithms always produce output blocks the exact same size as the input blocks, so you know that if you're using 128-bit blocks, you always grab the next 128 bits to get the next block. At the end of the session, you just throw away that key and create a new one for the next session.

1337JiveTurkey
Feb 17, 2005

Rhaegar posted:

Can I set the URLClassLoader class to null and then call the JVM's garbage collector? Am I unloading all the classes that were loaded from jars in the URLClassLoader's URLClassPath?

Yep. Just make sure that you pay attention to the issues that were mentioned just a bit earlier about PermGen space. There can't be any dangling references to the ClassLoader, Classes or any instances for it to be collected so be careful with static references.

1337JiveTurkey
Feb 17, 2005

The most obvious problem is that you don't close the catch block after the println().

A few points: Scanner is for parsing out more complex files for just the data you're interested in. You'd probably just want System.getConsole() to get the console for this program or use a BufferedReader created from the System.in input stream. Integer.parseInt() can parse any input string to tell if it's an integer. Typically you'd put a try-catch block around that and catch any NumberFormatExceptions. For situations where you don't know how many inputs you're going to have, an ArrayList<Integer> is usually cleaner. It uses auto-boxing to act like the ArrayList<Integer> really is an int[]. Finally, using -1 as a sentinel value is more trouble than it's worth when you can read in and recognize "q", "quit", "exit" or whatever.

1337JiveTurkey
Feb 17, 2005

Another alternative is to call java.text.Collator.getInstance() to get a Collator object which you can call myCollator.compare(string1, string2) and get the correct behavior for where you live.

1337JiveTurkey
Feb 17, 2005

zootm posted:

It'll be an internationalisation thing. I imagine the case conversion is not necessarily reflexive.

Yeah. It handles the German esszett, or ß character. When capitalized, it turns into SS, which then lowercases back to ss, the equivalent without the ligature. So Straße becomes STRASSE becomes strasse. Note that not only is this irreflexive, it gets longer in the process, potentially overflowing buffers for the unwary.

1337JiveTurkey
Feb 17, 2005

It uses an operator, I can tell you that much. It also doesn't use the result of the operator directly, but compares it to another number. If they're equal, it's divisible.

1337JiveTurkey
Feb 17, 2005

Mustach posted:

Those are the String methods you're talking about, though. compareToIgnoreCase uses the Character ones, which don't do those kinds of conversions.

OK, there's gotta be something really subtle going on there but at least in the case of Turkish, it'd map small i (no dot) to large I (no dot) back to small i (dot) and large I (dot) to large I (dot) to small I (dot) instead of the locale-specific way. Lots of programs break when run in the Turkish locale because they assume that every language with I and i map between the cases the same way as English.

Adbot
ADBOT LOVES YOU

1337JiveTurkey
Feb 17, 2005

Without Pants posted:

I'm starting a simple project in Java (actually it's in clojure, but Java+swing libs will be used) to enter recipes and save them in a database, for the gui part, what would be the best widget to handle it? I was just reading over the docs and my head is spinning a bit.

It should be simple, just adding/removing lines of text (ingredients) and being able to access them easily by line is my only concern. Would JTextArea suffice?

Yeah. If you're really only looking for something simple for entering individual lines of text, you could just use a JList with some sort of customization for in-place editing. Using a single selection model and a JTextField for rendering on top of the active cell seems like a horrible hack but it should work in theory.

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