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
poopiehead
Oct 6, 2004

Alan Greenspan posted:

I have like 50-75 classes that need to have the same 9 lines:
......


This probably isn't the case, but if the classes can reasonably have a common base class or maybe can be grouped into a few common base classes, it's pretty easy. But unless they genuinely have something else in common, this would probably be a bad idea.

code:

abstract class AbstractListener<T>
{
  private ListenerProvider<T> listeners = new ListenerProvider<T>(); 
  public void addListener(T listener) 
  { 
    listeners.addListener(listener); 
  } 
  public void removeListener(T listener) 
  { 
    listeners.removeListener(listener); 
  }
}

class A extends AbstractListener<ConcreteListenerClass>
{
 ...
}

class B extends AbstractListener<SomeOtherConcreteListenerClass>
{
}

poopiehead fucked around with this message at 06:02 on Jul 2, 2008

Adbot
ADBOT LOVES YOU

mister_gosh
May 24, 2002

I'm pretty new to gui development in Java and am having a brain fart.

I have two JFrames. One contains a JTextField and JButton. When that button is pressed, it brings up the second JFrame (which contains a JTree where the user can select the path to their "file"). When the file is selected, the user should press an ok button and that second JFrame should close and send the selected path to the first JFrame's JTextField.

My question is, how do I communicate that string variable (selected file) back to that JTextField if it is in a separate frame?

Thanks in advance, I'm sure I'm brain dead.

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.

philihp
Jun 1, 2008

Cagado Anarquista posted:

I'm doing some matrix computations (more specifically, SVD) using the JAMA library. It's a very sparse matrix (document-feature matrix) and I would love to use some better representation to save memory (only positive elements), but I can't really rewrite the math needed.

Know any better way?

I'm a bit rusty on Java, but I would try using a TreeMap of a TreeMap, kinda like this:

[code]
new TreeMap<int,TreeMap<int,double>>();
[code]

mister_gosh
May 24, 2002

1337JiveTurkey posted:

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.

The second JFrame with JTree selection is used to select a "file" within an oracle database. I haven't used JFileChooser, but I'm guessing the API isn't robust enough to handle these requirements.

mister_gosh fucked around with this message at 14:55 on Jul 3, 2008

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.

mistermojo
Jul 3, 2004

I'm working on a homework assignment and I need some help. Basically, the idea is to read in multiple text files, then use Scanner to add the strings to an array, then sort it and print the lines back.

I wrote all of the parts, but my problem is that I'm not sure how to make it actually run all of them.

The area I'm having a problem with is the else in the main. I'm not sure if I should write something that executes all of those things, but I want to run search on the args, then the bubblesort on the array and then the lineprinter on the array. The search works but the bubblesort and lineprinter give me an error saying I can't use sortarray

Here's the code: http://www.mediafire.com/?hy3ddzypscg

Entheogen
Aug 30, 2004

by Fragmaster

mistermojo posted:

I'm working on a homework assignment and I need some help. Basically, the idea is to read in multiple text files, then use Scanner to add the strings to an array, then sort it and print the lines back.

I wrote all of the parts, but my problem is that I'm not sure how to make it actually run all of them.

The area I'm having a problem with is the else in the main. I'm not sure if I should write something that executes all of those things, but I want to run search on the args, then the bubblesort on the array and then the lineprinter on the array. The search works but the bubblesort and lineprinter give me an error saying I can't use sortarray

Here's the code: http://www.mediafire.com/?hy3ddzypscg

for god's sake man, why are you using bubble sort? Implement either Merge sort or Quick Sort. Alternatively you could use one of the Java's API sort which is probably a variation on quick sort.

Also where do you define sortarray? This doesn't compile because in scope of main, sortarray does not exist. declare sortarray as static ArrayList<String> outside of search method, but inside the class. Then all other methods will see it.

Alternatively just do this
code:
ArrayList<String> lolz = search(args);
bubblesort( lolz );
lineprinter( lolz );
The problem that you seem to be having is understanding the scope of variables. In above code example subsequent method calls see lolz array, because it was declared in same method and is in their scope. If you would have made it static instead, then all of them would also see it and work on that one array.

hope this helped.

mistermojo
Jul 3, 2004

the homework is divided into C, B and A levels and C level is Bubble sort. B is Insertion and A is Merge (and some other stuff).

thanks for the help, I understand what my problem was.

I'm not really sure how this line works though
code:
ArrayList<String> lolz = search(args);

Entheogen
Aug 30, 2004

by Fragmaster

mistermojo posted:

the homework is divided into C,B and A levels and C level is Bubble sort. B is Insertion and A is Merge (and some other stuff).

thanks for the help, I understand what my problem was.

I'm not really sure how this line works though
code:
ArrayList<String> lolz = search(args);

your search method has declared Array<String> as its return type, and in the body you return sortarray, that you create in beginning of same method. so lolz == sortarray, just different names or references, pointing to same array.

One important thing to remember about java is that all variables are references, unless its an atomic type like int, or float. Because of this if you say array_1 = array_2, array_1 is not merely a copy or a clone of array_2. if you make changes to array_1 they will appear when you reference elements from array_2 because both store reference to the same object in memory.

Also this is why if you ever need to compare 2 strings for equality always use .equal method instead of ==. Two strings might have same content, but be different references. That is there are 2 separate String in memory. While they have the same content, the references pointing to them store different address, so == will return false even though they have same content.

Entheogen fucked around with this message at 00:29 on Jul 4, 2008

mjan
Jan 30, 2007

Entheogen posted:

One important thing to remember about java is that all variables are references, unless its an atomic type like int, or float. Because of this if you say array_1 = array_2, array_1 is not merely a copy or a clone of array_2. if you make changes to array_1 they will appear when you reference elements from array_2 because both store reference to the same object in memory.

Not exactly - all variables are passed by value, but in the case of non-primitives the value happens to be an internal pointer to an object instance. It's a subtle but important distinction that makes it possible to reassign a variable within a different scope without affecting the object reference outside of said scope.

Twitchy
May 27, 2005

mjan posted:

Not exactly - all variables are passed by value, but in the case of non-primitives the value happens to be an internal pointer to an object instance. It's a subtle but important distinction that makes it possible to reassign a variable within a different scope without affecting the object reference outside of said scope.

Oh god not this again (not saying you're wrong, but this topic always turns into a derailing clusterfuck in CoC)!

Entheogen
Aug 30, 2004

by Fragmaster
you are right mjan, but this is a technicality that newbies shouldn't worry about. he should learn how to do merge sort before anything else at least.

mistermojo
Jul 3, 2004

ok, I have another problem with the same code: After search, my sortarray has a list of values. However, when I check right after search(args); in the main, it says sortarray is empty. I'm not sure why this is. Here's the code: http://www.2shared.com/file/3550150/fe98a50b/Sort.html

BeefofAges
Jun 5, 2004

Cry 'Havoc!', and let slip the cows of war.

mistermojo posted:

ok, I have another problem with the same code: After search, my sortarray has a list of values. However, when I check right after search(args); in the main, it says sortarray is empty. I'm not sure why this is. Here's the code: http://www.2shared.com/file/3550150/fe98a50b/Sort.html

Your search method is returning a value, but you're not doing anything with it.

code:
}else {
	search(args);
	bubblesort(sortarray);
	lineprinter(sortarray);
}
should be
code:
}else {
	sortarray = search(args);
	bubblesort(sortarray);
	lineprinter(sortarray);
}
See the difference?

You'll probably also want to do something similar with bubblesort(), seeing as you've set it up to return the sorted array.

epswing
Nov 4, 2003

Soiled Meat
mistermojo: Also, it's imperative to understand how return values work.

For example,

code:
array = search(args);
sortedarray = bubblesort(array);
lineprinter(sortedarray);
is the same as

code:
lineprinter(bubblesort(search(args)));
without having to use explicit variables.

mistermojo
Jul 3, 2004

thanks a lot, doing sortarray = whatever worked.

mistermojo fucked around with this message at 01:24 on Jul 6, 2008

sonic bed head
Dec 18, 2003

this is naturual, baby!
Could someone help me with an algorithm to find a repeat? I have a string of characters like "12345123451234512345123" and I need to output 5 because that is how long the repeat is.I'm trying to solve a projecteuler.net problem and I cannot think of a way to solve it without doing this. I have tried putting each character into an array and then checking for the first index of each character but that method gets all confused with repeats like "11122211122211122212." Any help or links would be appreciated. Thanks.

Entheogen
Aug 30, 2004

by Fragmaster

sonic bed head posted:

Could someone help me with an algorithm to find a repeat? I have a string of characters like "12345123451234512345123" and I need to output 5 because that is how long the repeat is.I'm trying to solve a projecteuler.net problem and I cannot think of a way to solve it without doing this. I have tried putting each character into an array and then checking for the first index of each character but that method gets all confused with repeats like "11122211122211122212." Any help or links would be appreciated. Thanks.

is the string guaranteed to be made up of repeats, or is a repeat any sub sequence that is present in a string in consecutive form more than 1 time?

sonic bed head
Dec 18, 2003

this is naturual, baby!
It is guaranteed to be only made up of repeats but since I don't know the length of the repeat yet, it will have to be cut off arbitrarily so the end of the string isn't necessarily the end of a repeat.

Edit: I have another question actually. Is there any way to extend the java.lang classes? Extending meaning what "add to the prototype" would mean in JavaScript. I would like to add a ".getDigit()" method to all Integers and Longs. Is there any inherent way to do this in Java?

sonic bed head fucked around with this message at 02:55 on Jul 7, 2008

Entheogen
Aug 30, 2004

by Fragmaster

sonic bed head posted:

It is guaranteed to be only made up of repeats but since I don't know the length of the repeat yet, it will have to be cut off arbitrarily so the end of the string isn't necessarily the end of a repeat.

Edit: I have another question actually. Is there any way to extend the java.lang classes? Extending meaning what "add to the prototype" would mean in JavaScript. I would like to add a ".getDigit()" method to all Integers and Longs. Is there any inherent way to do this in Java?

I don't think you can modify java.lang classes. You could just make a static method some class in your project that would take an int or long and return the number of digits in it ( is this what you are tyring to do? )

You could just do brute force for the string. Start with repeat of size 1 and look at first character, see if it is longest repeat in string, if not then move on to size 2. For each possible repeat, check whole string if it satisfies this repeat. For end of string just implement a special case, to deal with string being cut-off in mid-repeat.

Alternatively you could start at beginning of string and keep reading until something starts to repeat. Think of it is a PDA that has language A = { w^c | c > 0 and c is real number }

ColdPie
Jun 9, 2006

This should be super easy, but I'm just having a dog of a time figuring this out.

Java doesn't have unsigned types, which makes reading binary files from languages that do have unsigned types a pain. I'm using a java.nio.ByteBuffer to read a file, and need to do a conversion from an unsigned byte into a Java type (I figure just an int). I've got b = b < 0 ? b + 256 : b;, which seems like an obvious fix, except if b=128. In that case, the binary reads 1000 0000, which when converted to signed types is -0, which fails that test and returns 0 instead of 128 like it should.

I feel like I'm overthinking this. What am I missing?

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

ColdPie posted:

This should be super easy, but I'm just having a dog of a time figuring this out.

Java doesn't have unsigned types, which makes reading binary files from languages that do have unsigned types a pain. I'm using a java.nio.ByteBuffer to read a file, and need to do a conversion from an unsigned byte into a Java type (I figure just an int). I've got b = b < 0 ? b + 256 : b;, which seems like an obvious fix, except if b=128. In that case, the binary reads 1000 0000, which when converted to signed types is -0, which fails that test and returns 0 instead of 128 like it should.

I feel like I'm overthinking this. What am I missing?

You want to do bitwise and'ing on it and store it in a type that is larger than necesary. In your example, you want to put those bytes in an int after you & 0xFF them to yank the sign extension.

ColdPie
Jun 9, 2006

TRex EaterofCars posted:

You want to do bitwise and'ing on it and store it in a type that is larger than necesary. In your example, you want to put those bytes in an int after you & 0xFF them to yank the sign extension.

Well, that worked perfectly. Thank you.

Alan Greenspan
Jun 17, 2001

poopiehead posted:

This probably isn't the case, but if the classes can reasonably have a common base class or maybe can be grouped into a few common base classes, it's pretty easy. But unless they genuinely have something else in common, this would probably be a bad idea.

code:

abstract class AbstractListener<T>
{
  private ListenerProvider<T> listeners = new ListenerProvider<T>(); 
  public void addListener(T listener) 
  { 
    listeners.addListener(listener); 
  } 
  public void removeListener(T listener) 
  { 
    listeners.removeListener(listener); 
  }
}

class A extends AbstractListener<ConcreteListenerClass>
{
 ...
}

class B extends AbstractListener<SomeOtherConcreteListenerClass>
{
}

Thank you for your reply, but you're obviously right. That's a really bad idea because it's not really a problem to be solved with inheritance (especially in a language with only single-inheritance support).

Java. :argh:

Smackbilly
Jan 3, 2001
What kind of a name is Pizza Organ! anyway?

Alan Greenspan posted:

Thank you for your reply, but you're obviously right. That's a really bad idea because it's not really a problem to be solved with inheritance (especially in a language with only single-inheritance support).

Java. :argh:

If your goal is to reduce duplication of implementation code, you could create a Listenable<T> (or whatever) interface, and have some ListenerManager<T> class implement it with those 9 lines, and then have every other class that needs to do listener management implement Listenable<SomeType> and also contain a private ListenerManager<SomeType> object such that all of the calls to addListener and removeListener are just pass-throughs to the internal ListenerManager object's methods.

Now of course the downside here is that this will actually increase the number of lines of code dedicated to listener management, so if making your code more terse is your goal, obviously don't do this.

Entheogen
Aug 30, 2004

by Fragmaster
I am developing a JOGL program that utilizes some nio buffers. I use com.​sun.​opengl.​util.BuffersUtil.new*Buffer to create buffers. When I go past certain size i get the following error

"An unrecoverable stack overflow has occurred", after JVM crashes.

I tried playing around with -Xmx but it didn't help at all.

What is the problem here and how can I correct it?

Mudoubleha
May 20, 2001
I have no title and I must scream.
I have this weird problem with Java Swing in that I have a JPanel that does drag and drop.

When I set that DnD JPanel as the contentPane in my main JFrame using setContentPane(), I can see my drawn squares on-screen and am able to move them around.

However, when I add my DnD JPanel to another JPanel which controls the layout, I end up with an unmovable square on my screen. However, my other components which are within the Layout JPanel are there.

I have 3 files which I'm using to try out(not part of the full app, but they illustrate the problem I have):

This class is the 2D object that's drawn on screen.
http://www.decruz.org/Blob.java


This is the driver class that sets up the Frame, and the contentPane. I've set up a new JPanel called test for this. It works fine as it is, but when I add the BlobPanel to test, the objects dont show up properly.
http://www.decruz.org/Blobber.java


This is the JPanel that does drag and drop.
http://www.decruz.org/BlobPanel.java

sonic bed head
Dec 18, 2003

this is naturual, baby!

Entheogen posted:

I don't think you can modify java.lang classes. You could just make a static method some class in your project that would take an int or long and return the number of digits in it ( is this what you are tyring to do? )

You could just do brute force for the string. Start with repeat of size 1 and look at first character, see if it is longest repeat in string, if not then move on to size 2. For each possible repeat, check whole string if it satisfies this repeat. For end of string just implement a special case, to deal with string being cut-off in mid-repeat.

Alternatively you could start at beginning of string and keep reading until something starts to repeat. Think of it is a PDA that has language A = { w^c | c > 0 and c is real number }

I'm actually trying to get digit by index, so it should have been getDigit(int index), so I can get the 1st digit or the 3rd digit or something like that. I made a static method in another class and got that to work, so thanks.

For the string, I don't really understand how to do what you're saying in Java, or any language for that matter. How do I do "see if it is longest repeat in string"? And for your alternate, how do I tell if something starts to repeat that isn't the whole repeat such as the case "1111222211112222." Wouldn't that method tell me that the repeat was "11"? Also, I have no idea what PDA is and a quick google of PDA+java and PDA+language gives nothing but links to Mobile development pages. Thanks a lot for your help and hopefully I'll get some more. :)

sonic bed head fucked around with this message at 14:47 on Jul 8, 2008

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
What's a good way to store a table of information? I want to use the same function and be able to output the results as an HTML table or as an excel spreadsheet using the POI HSSF stuff. There's a mix between strings, ints, etc that are going to go in the table.

epswing
Nov 4, 2003

Soiled Meat

fletcher posted:

What's a good way to store a table of information? I want to use the same function and be able to output the results as an HTML table or as an excel spreadsheet using the POI HSSF stuff. There's a mix between strings, ints, etc that are going to go in the table.

You might want to consider something out of the Swing library, namely the model that JTables use, TableModel. You can write your own implementation, or extend the existing DefaultTableModel to suit your needs.

Entheogen
Aug 30, 2004

by Fragmaster

sonic bed head posted:

For the string, I don't really understand how to do what you're saying in Java, or any language for that matter. How do I do "see if it is longest repeat in string"? And for your alternate, how do I tell if something starts to repeat that isn't the whole repeat such as the case "1111222211112222." Wouldn't that method tell me that the repeat was "11"?

You said that constraint of the problem is that entire string is composed of these repeats. Therefore a string with a repeat of 11 would be entirely composed of 1s. "1111222211112222" would not have repeat of 11 because 2s violate that constraint. If this constraint holds for your original problem, then seeing if something is a repeat is rather easy. You can use what is called a brute force method, and just try possible repeats in your string and then verifying that they are indeed valid repeats. That is if you had repeat of "11112222", you would go through all string and see that it is "11112222" repeated one after another.

The language A = { w^c | c >= 1 and c is REAL and w is in {0,1}* } describes language that is repeats of w, but not necessarily whole copies of w, but there is at least one w in the whole string of language A.

sonic bed head posted:

Also, I have no idea what PDA is and a quick google of PDA+java and PDA+language gives nothing but links to Mobile development pages. Thanks a lot for your help and hopefully I'll get some more. :)
http://en.wikipedia.org/wiki/Pushdown_automaton
http://en.wikipedia.org/wiki/Turing_machines
PDA is from computational theory. It means push down automation which is a theoretical device that reads its input on a tape, and has a stack data structure that it can use to process the information from the tape. it can only move forward on input tape, and it has a finite amount of internal states that it can switch between. If after reading all input and doing its stuff with the stack, it accepts the string then that string belongs to the language that this particular PDA decides. You might have herd about Turing machines. PDA is just one step below turing machines in terms of its language recognizing/deciding power. Of course, if you can think of algorithms to recognize something as belonging to a language, its not usually a huge step to ask other questions about that string, language.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

epswing posted:

You might want to consider something out of the Swing library, namely the model that JTables use, TableModel. You can write your own implementation, or extend the existing DefaultTableModel to suit your needs.

Sweet, thank you!

Another question - I want to attempt to parse a date multiple times. If the first one fails I want to try a different format. The parse method throws a ParseException. What's the proper way to do what I want? It seems like it could be done with another try/catch inside the first catch, but that seems like the wrong way to do it.

Smackbilly
Jan 3, 2001
What kind of a name is Pizza Organ! anyway?

fletcher posted:

Sweet, thank you!

Another question - I want to attempt to parse a date multiple times. If the first one fails I want to try a different format. The parse method throws a ParseException. What's the proper way to do what I want? It seems like it could be done with another try/catch inside the first catch, but that seems like the wrong way to do it.

Try something like this:

code:
boolean parsed = false;
int failures = 0;
String[] formatStrings = {"foo", "bar", "baz"};

do {
  try {
    parseMethod(date, formatStrings[failures]);
    parsed = true;
  } catch (ParseException ex) {
    ++failures;
    if (failures >= formatStrings.length) throw;
  }
} while(!parsed);
Assuming you want to throw a ParseException yourself if none of the format strings work. Adjust accordingly.

hey wiz
Jun 18, 2005

if (failures >= formatStrings.length) throw;

should be

if (failures >= formatStrings.length) throw ex;

Smackbilly
Jan 3, 2001
What kind of a name is Pizza Organ! anyway?

hey wiz posted:

if (failures >= formatStrings.length) throw;

should be

if (failures >= formatStrings.length) throw ex;

Oops, yeah, I was thinking in C++ there (where a throw with no arguments re-throws the exception you just caught).

zootm
Aug 8, 2006

We used to be better friends.

Smackbilly posted:

Oops, yeah, I was thinking in C++ there (where a throw with no arguments re-throws the exception you just caught).
This also works in C#, incidentally. I thought you'd put a C# code sample in the Java thread there, which was jolly confusing.

Fehler
Dec 14, 2004

.
Is there any function in Java that lets me check whether a host name has a DNS entry, like PHP's CheckDNSrr function?

zootm
Aug 8, 2006

We used to be better friends.
I'm pretty sure there's not in the default libraries.

Adbot
ADBOT LOVES YOU

Fehler
Dec 14, 2004

.
Any idea if there's a way at least to see if a host name is resolvable? The only thing I found was java.net.InetSocketAddress, but it looks like that will also open a socket, which is a bit overkill for my needs.

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