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
Leehro
Feb 20, 2003

"It's a gaming ship."
Are they javax.swing.JComboBox objects?

There's a few ways to do it. The most basic would probably be this:

1. Create 3 instances of a DefaultComboBoxModel, one for each JComboBox. assign them with JComboBox.setModel(). Add all the choices to all of them.

2. Create add Action Listeners for each JComboBox. When you change the first combo box, it should update 2 and 3 to remove the choice you selected (removeElement()). When you change the second, it should update the third to remove that choice too.

You can get fancier than that, that should get you started. Using an IDE will help guide you along. I ran through it in NetBeans in about 5 minutes.

Adbot
ADBOT LOVES YOU

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Is there a way to do this without int count?

code:
Iterator accountIds = accounts.keySet().iterator();
int count = 0;
while (accountIds.hasNext()) {
	if (count>0)
		qry+=",";
	qry += "'"+accountIds.next()+"'";
	count++;
}

epswing
Nov 4, 2003

Soiled Meat

fletcher posted:

Is there a way to do this without int count?

There are lots of ways...

code:
StringBuilder qry = new StringBuilder();
// ...
Iterator accountIds = accounts.keySet().iterator();
while (accountIds.hasNext())
	qry.append("'" + accountIds.next() + "',");
if (qry.charAt(qry.length()-1) == ',')
	qry.deleteCharAt(qry.length()-1)
Edit: Here's what we should be doing, regarding the conversation below:

code:
StringBuilder qry = new StringBuilder();
// ...
Iterator accountIds = accounts.keySet().iterator();
while (accountIds.hasNext()) {
	qry.append("'");
	qry.append(accountIds.next());
	qry.append("',");
}
if (qry.charAt(qry.length()-1) == ',')
	qry.deleteCharAt(qry.length()-1)

epswing fucked around with this message at 21:41 on Apr 8, 2008

derelict515
Sep 10, 2003
I'm looking for some info on asynchronous method calls in Java, sorta like the .NET Asynchronous Programming Model. I know you could do it manually by creating a thread and spinning off work (and maybe using a Future<> and an Executor) but that's annoying and cumbersome and in the case of asynchronous I/O, fairly wasteful if you could do it directly to the hardware instead of spinning up a new thread to do it. I'm finding surprisingly little via Google and Sun's site (though maybe I'm just missing something).

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
edit: nevermind

Brain Candy
May 18, 2006

epswing posted:

There are lots of ways...

code:
StringBuilder qry = new StringBuilder();
Iterator accountIds = accounts.keySet().iterator();
while (accountIds.hasNext())
	qry.append("'" + accountIds.next() + "',");
if (qry.charAt(qry.length()-1) == ',')
	qry.deleteCharAt(qry.length()-1)

This makes my brain hurt, or maybe its a coffee deficiency.
code:
qry.append("'" + accountIds.next() + "',");
This still leads to multiple String creation, which you were trying to avoid with the StringBuilder. Go with three appends instead.

code:
if (qry.charAt(qry.length()-1) == ',')
Just check that length is non-zero instead?

the onion wizard
Apr 14, 2004

fletcher posted:

Is there a way to do this without int count?

code:
Iterator accountIds = accounts.keySet().iterator();

while (accountIds.hasNext()) {

    qry += "'"+accountIds.next()+"'";
    
    if (accountIds.hasNext()) {
	qry+=",";
    }
}

How's that?




epswing & Brain Candy: I was under the impression that the compiler will take care of substituting StringBuilder during string concatenation?

http://java.sun.com/developer/technicalArticles/Interviews/community/kabutz_qa.html posted:

When Strings are added using the + operator, the compiler in J2SE 5.0 and Java SE 6 will automatically use StringBuilder

epswing
Nov 4, 2003

Soiled Meat

Brain Candy posted:

Just check that length is non-zero instead?
Nope, depends on if qry already has content such as "select ...".

triplekungfu posted:

epswing & Brain Candy: I was under the impression that the compiler will take care of substituting StringBuilder during string concatenation?
Sounds like this will create a new StringBuilder instance per iteration, in which case the extra append calls would be better.

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

epswing posted:

Sounds like this will create a new StringBuilder instance per iteration, in which case the extra append calls would be better.
Why would the compiler do that?

Kennedy
Aug 1, 2006


hard to breathe?
JSTL SQL Insert Query - Kinda fixed

code:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
 
<sql:setDataSource var ="bookdB" scope = "session"   driver = "sun.jdbc.odbc.JdbcOdbcDriver" url = "jdbc:odbc:books" />

<sql:update var = "usersInsert" dataSource ="${bookdB}" scope="request">
	INSERT INTO Users (Username, Password, FirstName, Surname, AddressLine1, AddressLine2, City, Telephone, Mobile)
	VALUES ('test', "test", 'test', 'test', 'test', 'test', 'test', 1111111, 1111111111)
</sql:update>


<jsp:forward page="test.jsp" />
The above is a test Insert statement using JSTL in a JSP page. As you can see, I'm trying to create a new row in an Access database and fill it with test data. All fields are TEXT apart from the phone numbers which are LONG INTs.

Whenever I run it, I get a

quote:

java.sql.SQLException: General error
error. The dataSource is fine, I've copied it from a working query.

Any ideas why I can't get it to work? Running on a Tomcat 6.0.10 server.

EDIT: don't know how, but the INSERT is running fine now. Don't know what I changed to fix it :(

EDIT 2: Goddamn it, don't know whether it good or not that, after being stuck for an hour or so, I manage to fix my problem with 10 mins of posting. EVERY. TIME. :)

Fixed statement:

code:
<fmt:parseNumber var="telephone" value="${param.telephone}" type="number" />
<fmt:parseNumber var="mobile" value="${param.mobile}" type="number" />

<sql:update var = "Insert" dataSource ="${bookdB}">
	INSERT INTO Users (Username, Password, FirstName, Surname, AddressLine1, AddressLine2, City, Telephone, Mobile)
	VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
	<sql:param value="${param.username}" />
	<sql:param value="${param.password}" />
	<sql:param value="${param.firstname}" />
	<sql:param value="${param.lastname}" />
	<sql:param value="${param.addressline1}" />
	<sql:param value="${param.addressline2}" />
	<sql:param value="${param.city}" />
	<sql:param value="${param.telephone}" />
	<sql:param value="${param.mobile}" />
</sql:update>

Kennedy fucked around with this message at 17:00 on Apr 8, 2008

epswing
Nov 4, 2003

Soiled Meat

TRex EaterofCars posted:

Why would the compiler do that?

I don't know anything about the java compiler. From my lofty perch, far from such low-level details, it sounds like
code:
String s1 = "hello" + "there";
conceptually amounts to something like
code:
String s1;
StringBuilder sb = new StringBuilder();
sb.append("hello");
sb.append("there");
s1 = sb.toString();
Are there StringBuilder instances lying around that the VM uses on a per-thread basis for all String + String concat operations? I'm interested to know how this works.

epswing fucked around with this message at 16:58 on Apr 8, 2008

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

epswing posted:

I don't know anything about the java compiler. From my lofty perch, far from such low-level details, it sounds like
code:
String s1 = "hello" + "there";
conceptually amounts to something like
code:
String s1;
StringBuilder sb = new StringBuilder();
sb.append("hello");
sb.append("there");
s1 = sb.toString();
Are there StringBuilder instances lying around that the VM uses on a per-thread basis for all String + String concat operations? I'm interested to know how this works.

I just decompiled this code (All code generated using JDK6_u3, should probably upgrade):

code:
public class StringDemo {
        public static void main(String [] args) {
                String s1 = "Hello" + " world!";
                System.out.println(s1);
        }
}
and javac turned "Hello" + " world!" into a single literal. So, I modified it to this:

code:
public class StringDemo {
        public static void main(String [] args) {
                String s1 = "Hello";
                String s2 =  " ";
                String s3 = " world!";
                String s4 = s1 + s2 + s3;
                System.out.println(s4);
        }
}
and it uses .append() with only 1 instance of StringBuilder.

epswing
Nov 4, 2003

Soiled Meat

TRex EaterofCars posted:

...and it uses .append() with only 1 instance of StringBuilder.

That's exactly what I was concerned with: does the following mean 5 instances of StringBuilder?

code:
public class StringDemo {
        public static void main(String [] args) {
                for (int i = 0; i < [b]5[/b]; i++) {
                        String s1 = "Hello";
                        String s2 =  " ";
                        String s3 = " world!";
                        String s4 = s1 + s2 + s3;
                        System.out.println(s4);
                }
        }
}

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

epswing posted:

That's exactly what I was concerned with: does the following mean 5 instances of StringBuilder?

Sure does.

epswing
Nov 4, 2003

Soiled Meat

TRex EaterofCars posted:

Sure does.

Ok, which brings me back to http://forums.somethingawful.com/showthread.php?threadid=2780384&pagenumber=5#post342041228

epswing posted:

Sounds like this will create a new StringBuilder instance per iteration, in which case the extra append calls would be better.

TRex EaterofCars posted:

Why would the compiler do that?

Looks like it would. In which case I'm saying that N*3 calls to append might be faster than N new StringBuilder objects.

Fehler
Dec 14, 2004

.
I have a JTable with two columns and I want their widths to be distributed 9:1, i.e. if the whole table is 100px wide, column1 should be 90px and column2 10px.

After some searching it looked like these lines could help, but they don't seem to have any effect:
jTable1.getColumnModel().getColumn(0).setPreferredWidth(9);
jTable1.getColumnModel().getColumn(1).setPreferredWidth(1);

What am I doing wrong?


Also, it seems like when I restart the program, it will automatically resize the columns to the way they were in the last session. Why does this happen? Could it be the reason why the two lines don't work?

epswing
Nov 4, 2003

Soiled Meat
Here's how I set my column widths:

code:
table.getColumn("User").setMaxWidth(75);
table.getColumn("Start Time").setMinWidth(130);
table.getColumn("End Time").setMinWidth(130);

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

epswing posted:

Ok, which brings me back to http://forums.somethingawful.com/showthread.php?threadid=2780384&pagenumber=5#post342041228



Looks like it would. In which case I'm saying that N*3 calls to append might be faster than N new StringBuilder objects.

Yeah, I misread your post. I actually copied that code straight now and disassembled it and it's definitely creating 2 new StringBuilder instances for every loop. I wonder if HotSpot would be able to optimize this further and move the allocation if it unrolled the loop.

This bugged the poo poo out of me so I benchmarked it. You're right, the overhead of allocating those StringBuilders is significant for even modest numbers of iterations. I'll post the code if anyone wants, but for 1000 keys of random size, it took anywhere from 875-1000ms to run the naive method, and from 0-3ms for the explicit append() method.

I run under linux so the JVM uses the server VM by default. I tried this under -client and got FAR worse performance for the naive method, even after HotSpot dealt with it.

epswing
Nov 4, 2003

Soiled Meat

TRex EaterofCars posted:

I'll post the code if anyone wants

I'd love to see it firsthand. :)

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

epswing posted:

I'd love to see it firsthand. :)

code:
import java.util.*;
import java.io.*;

public class StringDemo {

        private static String testNaive(Map<String,String> map) {
                long start = System.currentTimeMillis();
                String qry ="";
                Iterator accountIds = map.keySet().iterator();
                while (accountIds.hasNext()) {
                        qry += "'"+accountIds.next()+"'";
                        if (accountIds.hasNext()) qry+=",";
                }
                System.out.println((System.currentTimeMillis()-start) + "ms for naive.");
                return qry;
        }

        private static String testExplicit(Map<String,String> map) {
                long start = System.currentTimeMillis();
                StringBuilder qry = new StringBuilder();
                Iterator accountIds = map.keySet().iterator();
                while (accountIds.hasNext()) {
                        qry.append("'").append(accountIds.next()).append("'");
                        if (accountIds.hasNext()) qry.append(",");
                }
                System.out.println((System.currentTimeMillis()-start) + "ms for explicit.");
                return qry.toString();
        }

        static Random r = new Random(System.currentTimeMillis());

        private static Map<String,String> generate() {
                int length = 1000;

                Map<String,String> map = new HashMap<String,String>(length);

                byte [] k; byte [] v;

                while (length-- > 0) {
                        int klen = r.nextInt(256);
                        int vlen = r.nextInt(256);
                        k=new byte[klen];
                        v=new byte[vlen];
                        r.nextBytes(k); r.nextBytes(v);
                        map.put(new String(k), new String(v));
                }

                return map;
        }

        private static void write(String name, String data) throws Exception {
                FileWriter f = new FileWriter(name);
                f.write(data,0,data.length());
                f.close();
        }

        public static void main(String [] args) throws Exception {

            Map<String, String> map = generate();

            for (int x = 1; x<100; x++) {
                write("naive.out", testNaive(map));
                write("explicit.out", testExplicit(map));
            }

            System.out.println(map.size() + " pairs");
        }
}
The file writing was just to make sure they were generating the same output. I md5summed the output and it is indeed the same. There's a few optimizations that could be made to the loop itself but that's not what I am testing so I didn't do it.

Brain Candy
May 18, 2006

epswing posted:

Nope, depends on if qry already has content such as "select ...".

In the code block you gave, you constructed qry inside the block. So if your while loop executes at least once, the last char of qry will be ','.

ColdPie
Jun 9, 2006

Is there a "Java way" to accomplish the same thing as bitflags? I know it's possible to do bitflags in Java, but it just doesn't feel right. I'd like the same kind of functionality, but without significantly more complicated syntax. For example, I'd rather avoid making a whole new class containing a half-dozen Booleans, then have to construct this class every time I want to call a function.

What I have now is basically:
code:
static final int Flag_01 = 0x000000001;
static final int Flag_02 = 0x000000002;
static final int Flag_03 = 0x000000004;
static final int Flag_04 = 0x000000008;
static final int Flag_05 = 0x000000010;
static final int Flag_06 = 0x000000020;

public void someMethod(int flags){
    if( (flags & Flag_01) != 0){
        //do something
    }
    if( (flags & Flag_02) != 0){
        //do something else
    }
    //etc.
}

//invoking:
    someMethod(Flag_01 | Flag_03);
How "should" I be doing this in Java?

Brain Candy
May 18, 2006

ColdPie posted:

How "should" I be doing this in Java?

Inheritance and/or enums. Its hard to say exactly without any idea of why you want to use bit flags.

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

Brain Candy posted:

Inheritance and/or enums. Its hard to say exactly without any idea of why you want to use bit flags.

Yeah, please let us know a bit more about your problem. There is almost always a more elegant way of handling that sort of multiplexing.

ColdPie
Jun 9, 2006

TRex EaterofCars posted:

Yeah, please let us know a bit more about your problem. There is almost always a more elegant way of handling that sort of multiplexing.

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).

epswing
Nov 4, 2003

Soiled Meat

Brain Candy posted:

In the code block you gave, you constructed qry inside the block. So if your while loop executes at least once, the last char of qry will be ','.

Look at what fletcher gave us initially, there's a qry variable out of nowhere, it could contain anything. I instantiated a StringBuilder in my block because I needed a StringBuilder instead of a String, I clearly needed to indicate this somehow, but that's not necessarily where he/she is instantiating it. (That's what the // ... is for.)

(Edit: Yay, first time I use [fixed]!)

epswing fucked around with this message at 06:21 on Apr 9, 2008

zootm
Aug 8, 2006

We used to be better friends.

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).
Yeah, you probably want enums, assuming you're using Java 5 or newer. The EnumSet class will let you do the 'bitflag' thing in a typesafe way while also getting the full functionality of the Set interface. It's implemented as bitflags too so you get that time efficiency.

Whilst farting I
Apr 25, 2006

I'm writing an applet which plays a card game, but I wrote it misunderstanding how the game works. How it's supposed to work: three cards are drawn, two are put face up, user enters how much money he/she would like to bet that the integer value of the third card is between the two being shown, third card is shown and winnings are added/subtracted accordingly. How I wrote it: user enters how much money they'd like to bet, all 3 cards are drawn at once and uses whatever bet was given before beginning the round.

beginRound is the function that compares the cards, determines if the card is in between the first and second card drawn, and accordingly adds/subtracts from the user's total winnings.

The user enters into a textfield his/her bet and any button clicked will automatically get the bet for the user, but how do I make it so for begin round, two cards are drawn, and then have the program wait for the user to enter a new bet and click the corresponding button associated with bet before continuing with the rest of the function? I feel like right after the line with curCard3 is where it should wait for the user's bet before continuing, but I can't find any information on how to make the program wait on a non-input dialog basis. The rest of the program works perfectly. Thank you!

code:
public void actionPerformed(ActionEvent e)
	{
		// Gets the user's bet no matter what action is called
		int currentBet = getBet();
		
		// Starts the round, calls function to get the winnings
		// and appends them
		if (e.getActionCommand().equals("startround"))
		{
			// Deals three cards, first two displayed to user, all removed from deck 
			curCard1 = deck.dealCard();
			curCard2 = deck.dealCard();
			curCard3 = deck.dealCard();
			
			newWinnings = beginRound(currentBet, currentWinnings);
			currentWinnings = newWinnings;
			displayWinnings.setText("" + currentWinnings + "");
		}
		
		// Gets the user's bet
		if (e.getActionCommand().equals("bet"))
		{
			currentBet = getBet();
		}
		
		// If user wants a new game, erases winnings, clears
		// text areas, and creates a new deck
		if (e.getActionCommand().equals("newgame"))
		{
			currentWinnings = 0;
			displayWinnings.setText(null);
			deck.shuffle();
		}
	} // end actionPerformed

Fehler
Dec 14, 2004

.

epswing posted:

Here's how I set my column widths:

code:
table.getColumn("User").setMaxWidth(75);
table.getColumn("Start Time").setMinWidth(130);
table.getColumn("End Time").setMinWidth(130);
Great, thanks!


Does anybody here have experience with the Apache Commons FTPClient class? When I try to cancel an upload with abort(), the program just freezes and waits for the upload to complete. Afterwards abort() returns true, though.

oh no computer
May 27, 2003

Whilst farting I posted:

but I can't find any information on how to make the program wait on a non-input dialog basis.
I too would love to know how to do this. I had a similar problem when doing my final year project for my CS degree, and I got around it by doing something like:
code:
while (!finished)
{
    // check to see if input has been given, if so set finished to true
    Thread.sleep(100); // to stop it using your CPU at 100%
}
but this is a hack and pretty bad practise. Something like how the Scanner class patiently waits for input would be perfect.

the onion wizard
Apr 14, 2004

Whilst farting I posted:

I'm writing an applet which plays a card game...
I may be missing something, but shouldn't the flow go something like this:
[list=1]
[*]Display 2 cards
[*]Accept user's bet
[*]Final card and winnings calculation
[/list]
Now, #1 is triggered by "startround", #2 by "bet", and #3 by #2?

Whilst farting I
Apr 25, 2006

triplekungfu posted:

I may be missing something, but shouldn't the flow go something like this:
[list=1]
[*]Display 2 cards
[*]Accept user's bet
[*]Final card and winnings calculation
[/list]
Now, #1 is triggered by "startround", #2 by "bet", and #3 by #2?

You're right, I knew something didn't seem right. I solved the problem by dealing the cards in the start round function and moving the actual comparison and calculation functions and display into the bet.

The GUI includes 3 buttons: Start a New Game (start from scratch), Start A New Round (deals 3 new cards and displays 2), and Bet (gets the bet from the user, displays the last card, and gives output). So the flow is now identical to what you just posted. This is really rough (error-checking statements to be added, variable names are hosed up, graphic display of cards to add), but it works. Thank you!

code:
public void actionPerformed(ActionEvent e)
	{
		int currentBet;
		
		// Deals 3 cards and displays first 2 so user can bet
		if (e.getActionCommand().equals("startround"))
		{
			curCard1 = deck.dealCard();
			curCard2 = deck.dealCard();
			curCard3 = deck.dealCard();
			displayBet.append("Card 1: " + curCard1 + "\nCard 2: " + curCard2 + "\nCard 3: ");
		}
		
		// Gets the user's bet after displaying the first two cards
		if (e.getActionCommand().equals("bet"))
		{
			currentBet = getBet();
			
			// Calculates the amount of cards left in the deck
			noCardsLeft = deck.cardsLeft();
			
			// Calculates if third card is between first two, appends final card with results
			newWinnings = beginRound(currentBet, currentWinnings);
			displayBet.append("" + curCard3 + "\n\n" + noCardsLeft + "\n\n");
			currentWinnings = newWinnings;
			displayWinnings.setText("" + currentWinnings + "");
		}
		
		// If user wants a new game, erases winnings, clears
		// text areas, and creates a new deck
		if (e.getActionCommand().equals("newgame"))
		{
			currentWinnings = 0;
			displayWinnings.setText(null);
			deck.shuffle();
		}
	} // end actionPerformed
Out of curiousity for the future, though, does anyone know a better way for making a program wait on a non-input dialog basis besides the sleep method BELL END mentioned?

ColdPie
Jun 9, 2006

zootm posted:

Yeah, you probably want enums, assuming you're using Java 5 or newer. The EnumSet class will let you do the 'bitflag' thing in a typesafe way while also getting the full functionality of the Set interface. It's implemented as bitflags too so you get that time efficiency.

Neat, that looks like a good solution. Thanks.

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.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
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?

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.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

1337JiveTurkey posted:

HashSet does exactly what you're looking for.

Right on, thanks!

the onion wizard
Apr 14, 2004

Whilst farting I posted:

Out of curiousity for the future, though, does anyone know a better way for making a program wait on a non-input dialog basis besides the sleep method BELL END mentioned?

The technique BELL END mentioned is called polling, and is usually a bad idea.

If you've got an event driven UI (which is the case here), then you don't need to poll; actions are triggered by events.

An alternative to this is to use queues, and when attempting to read from a queue the consumer will be blocked until something is available (same goes for the producer putting stuff into the queue if the queue is full). Once a message becomes available in the queue, the consumer will be awoken and handed the message.

I used the above a couple of times in Uni assignments, rolling my own queue in Java 4. Java 5 includes BlockingQueue, which probably would have saved me a bit of time.



Also, TRex EaterofCars and epswing thanks for the clarification on StringBuilder.

Drumstick
Jun 20, 2006
Lord of cacti
Im having a problem with 2d arrays. How can I assign a value to each spot in the array?
I dont know if this would further complicate the issue, but the size of the array is based on user input.

this is what i have right now. My hope is that this will assign a random boolean to each location within the array. Will this function how I would like it to?

quote:

boolean[][] lifegame = new boolean[i][h];

for( int a = 0; a < i; a++ )
for (int b = 0; b < h; b++){

Random random = new Random();
boolean r = random.nextBoolean();

lifegame[i][h]= r ;

Adbot
ADBOT LOVES YOU

oh no computer
May 27, 2003

Drumstick posted:

this is what i have right now. My hope is that this will assign a random boolean to each location within the array. Will this function how I would like it to?
You'll want to set lifegame[a][b] on the last line, not i,h

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