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
baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

Jabor posted:

So if you have an instance of RadSuperClass, what values are you allowed to call setMode with?

You may wish to re-think your design with substitutability in mind.

Rad is abstract, but setMode is common to all the implementing classes.

Basically each subclass has its own set of valid constants that set a particular behaviour, so the method just sets a mode by passing in a constant. There's default behaviour for invalid constants, but I got playing with annotations and thought it would be nice to annotate the method call with a single subclass-aware annotation that pulls in the valid constant values - I was just wondering if it was possible

Adbot
ADBOT LOVES YOU

Sedro
Dec 31, 2008

carry on then posted:

So is there a quirk in Java/a point to doing multiple negations? I'm seeing essentially

code:
!!!string.equalsIgnoreCase(Boolean.toString(false))
I know in C sometimes you get those multiple ! to make sure the value is 0 or 1 instead of some other number, but I wasn't aware that there was any point to it in Java.
You might be confusing Java with Javascript.

Java has its own quirks though: !!expr can result in true, false, or NullPointerException

Loezi
Dec 18, 2012

Never buy the cheap stuff

Sedro posted:

You might be confusing Java with Javascript.

Java has its own quirks though: !!expr can result in true, false, or NullPointerException

I actually had to try this since I hadn't stumbled upon this before. Found the trivial case of
Java code:
public class Main {
    public static void main(String[] args) {
        boolean a = !!a(); //NPE
    }
    
    public static Boolean a() {
        return null;
    }
}
Is there any other situation where this can happen?

Sedro
Dec 31, 2008
You got it. It's not exclusive to the ! operator. Any time you auto-unbox there is the possibility of a NPE.
Java code:
Boolean x = null;
if (x) { ... } // NPE

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

Sedro posted:

You might be confusing Java with Javascript.

Java has its own quirks though: !!expr can result in true, false, or NullPointerException

I'm not sure what that has to do with Javascript.

Sedro
Dec 31, 2008

carry on then posted:

I'm not sure what that has to do with Javascript.
!! is common in javascript because it converts truthy/falsey to proper true/false

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

Sedro posted:

!! is common in javascript because it converts truthy/falsey to proper true/false

Ah yeah. Another language where it might mean anything, but I'm just not sure what this person was thinking when they wrote this. Very near that line is another where the comment says the timeout is 15 minutes but the math works out to 15 hours. Outstanding.

Volmarias
Dec 31, 2002

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

carry on then posted:

Ah yeah. Another language where it might mean anything, but I'm just not sure what this person was thinking when they wrote this. Very near that line is another where the comment says the timeout is 15 minutes but the math works out to 15 hours. Outstanding.

On the plus side, you now know that you cannot trust any code that this person has written, let alone any comments, as opposed to before where you merely suspected it.

geeves
Sep 16, 2004

Volguus posted:

On Home Depot there were some articles that were saying that the higher ups were warned years before about the lack of security and potential breaches. And they didn't give a poo poo. How do you think they'll behave when you come and tell them about how well are you going to make this software, and how many good development practices are you going to apply once you present them the price for it?

This is what's infuriating about my company. Our deadlines are set by marketing. Marketing! Some arbitrary date that seems like they're slotting a movie for release than they are a SaaS application. We've been run by marketing and their existential threats for the last few years.

We were hacked through an exploit in Struts - a well known exploit and even we raised it to get time slotted to upgrade (we were denied) . Suddenly we had to basically halt everything to address this because what we said would happened, happened.

It probably doesn't help that we are in one city while the rest of the company is in another. It doesn't even feel that we're part of a company. It feels like we're more a group of independent contractors. Our CTO is in our office, and he knows about all of our complaints and suggestions for improvements; they're well documented. Yet either he is not willing or not able to get the point across to the rest of the executives that some things need to be addressed. The CEO and others rather keep up the charade instead of actually delivering a well-designed and well-tested product. Hell, until the last 6 months we hadn't had a new hire in almost 3 years while the other office nearly tripled in size to meet non-existing demand.

Volguus posted:

I have learned over the years to pick my battles, however. Always try to improve, always try to do the right thing, but look at your surroundings, look at what can you do and let some things go if you have to. Change them if you can on the fly, and if you hit a wall ... make your decision then if you want to continue or not. You are sounding like a stubborn little child who's not going to do his homework unless the exact amount of cake is present on the table. No more, no less. And throws a tantrum until the cake arrives on the table. Good luck, is all I can say.

I've learned just to do whatever I want to improve things when I can and ask for forgiveness later; my boss has basically given me his approval for this approach. It's the only way we get critical things done that aren't new functionality.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

baka kaba posted:

Rad is abstract, but setMode is common to all the implementing classes.

Basically each subclass has its own set of valid constants that set a particular behaviour, so the method just sets a mode by passing in a constant. There's default behaviour for invalid constants, but I got playing with annotations and thought it would be nice to annotate the method call with a single subclass-aware annotation that pulls in the valid constant values - I was just wondering if it was possible

You didn't answer my question - if you have an instance of RadAbstractClass, but you don't know what subclass it is, is it valid for you to be calling setMode on it? If so, what values are you allowed to pass in?

covener
Jan 10, 2004

You know, for kids!

carry on then posted:

So is there a quirk in Java/a point to doing multiple negations? I'm seeing essentially

code:
!!!string.equalsIgnoreCase(Boolean.toString(false))
I know in C sometimes you get those multiple ! to make sure the value is 0 or 1 instead of some other number, but I wasn't aware that there was any point to it in Java.

I've seen this style in java code from the UK. The answer I got was that it makes the negation harder to miss for humans.

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

baka kaba posted:

Rad is abstract, but setMode is common to all the implementing classes.

Basically each subclass has its own set of valid constants that set a particular behaviour, so the method just sets a mode by passing in a constant. There's default behaviour for invalid constants, but I got playing with annotations and thought it would be nice to annotate the method call with a single subclass-aware annotation that pulls in the valid constant values - I was just wondering if it was possible

Unless I'm missing something important here, annotations don't actually do anything. You can apply them to classes, interfaces, members, or methods, and then check to see if they're there later. The limits to what you can do with them are basically the limits of Java reflection.

That being said, there are relatively few occasions where annotations are the best solution to your problem. I use them pretty much exclusively to pass information to interceptors, for example, an authentication interceptor in a WebService framework. They're great for signaling intent in loosely-coupled systems, but generally, you're writing something a little less complecated than a framework.

In your specific case, I'd probably have the abstract super-class define a private abstract Set<Integer> getValidConstants() method that all subclasses would have to implement. The golden rule of design is that it should be hard to use wrong, and it sounds far too simple to forget to properly annotate your subclasses. Conversely, abstract classes make it impossible to write a subclass that doesn't implement a method named getValidConstants that returns a Set of Constants - you'd almost have to try to write something that compiled, but didn't comply with the superclass' intentions.

In fact, I'd reconsider having setMode accept an int at all. Strong-typing is one of Java's strengths; if you define classes, enums, and interfaces that are specific to your needs, the compiler will prevent a whole class of errors that can cause unexpected behavior. Why use an integer to mean something, when you can just use that something instead?

Java code:
public abstract class RadSuperClass<T> {
    private T currentMode;

    RadSuperClass(T defaultMode) {
        this.currentMode = defaultMode;
    }

    public void setCurrentMode(T mode) {
        this.currentMode = mode;
    }
}

public class SweetSubClass extends RadSuperClass<SweetSubClass.WickedSickMode> {
    public static enum WickedSickMode {
        KICKIN,
        KEEPIN_IT_REAL,
        JUST_CHILLAXIN
    }

    public SweetSubClass() {
        super(WickedSickMode.JUST_CHILLAXIN);
    }
}
This way, we don't have to write any validation code at all; by definition, all setCurrentMode calls must pass in a valid mode.

FateFree
Nov 14, 2003

Gravity Pike posted:

Annotations don't actually do anything, thats the beauty of them!

Hughlander
May 11, 2005

HFX posted:

There is no reason other than obfuscation. The ! operator only works on booleans.

Even in embedded C, I would consider it bad practice to do something like that unless you were honing out every bit of speed on a particular platform.

As late as the PS3 and XBox 360 !! was the fastest way to coerce in C++. (Of course you could argue that a XBox360 is just a special case of embedded C)

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

Gravity Pike posted:

use enums stupid!

Yeah this is an Android thing, and the guidelines explicitly said not to use enums, so this is old code that I really want to use them with - I might eventually rewrite it that way, when I get around to looking at it properly and doing some benchmarking. Right now there's a switch in the main function that checks which ID is being passed (which is the setMode one if that was called earlier) and runs the relevant code, with a sane default, so passing invalid values is handled that way.

Correct input values can't be guaranteed anyway (it takes external input, so there is loose coupling), but I was looking at annotations as a nice way of providing code-completion hinting when I'm calling things explicitly from code - it's not important or anything, I was just playing around with annotations and wondered if I could have them work seamlessly with inheritance, but it doesn't seem like it's possible. I don't want to spend a lot of time on it anyway

Thanks for the code advice too guys - I'm well aware this isn't an ideal setup, and I'll definitely be revising it anyway in future (there's worse in there...)

ROFLburger
Jan 12, 2006

This might be a dumb question... but does anyone know why none of the JSON libraries have the JSONObject class implement the Map interface? I can't think of any reason that it shouldn't

Ellie Crabcakes
Feb 1, 2008

Stop emailing my boyfriend Gay Crungus

ROFLburger posted:

This might be a dumb question... but does anyone know why none of the JSON libraries have the JSONObject class implement the Map interface? I can't think of any reason that it shouldn't
Exceptions, probably.

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.
Edit: Actually that doesn't even work. No clue.

Max Facetime
Apr 18, 2009

ROFLburger posted:

This might be a dumb question... but does anyone know why none of the JSON libraries have the JSONObject class implement the Map interface? I can't think of any reason that it shouldn't

JSON doesn't strictly prohibit non-uniquely named members of objects. It just strongly discourages them. Depending on how faithfully one might want to represent such JSON data, one might have JsonObject implement Map<String, JsonObject> or Map<String, Set<JsonObject>> or List<Pair<String, JsonObject>> etc...

BTW, json-simple is one library where JSONObject implements Map and JSONArray implements List.

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

Max Facetime posted:

JSON doesn't strictly prohibit non-uniquely named members of objects. It just strongly discourages them. Depending on how faithfully one might want to represent such JSON data, one might have JsonObject implement Map<String, JsonObject> or Map<String, Set<JsonObject>> or List<Pair<String, JsonObject>> etc...

BTW, json-simple is one library where JSONObject implements Map and JSONArray implements List.

That's what I was thinking, but then JSONObject still deals with keys, right? So do you just collect all the colliding keys and put them into a Set as you deserialize it?

That's still no reason not to be a Map implementation though. And even if they were still using a List<> behind the scenes, they could still implement the map interface since it has to have get(key) and put(key) methods either way.

Zaphod42 fucked around with this message at 00:10 on Apr 7, 2015

Max Facetime
Apr 18, 2009

Well, the values of the keys can be strings, JSON objects, JSON arrays etc.

So then json-simple will allow Strings, Maps and Lists as values. This in turn means that their JSON object has to implement Map as Map<String, Object>, which isn't that great. I suspect that the reason more libraries don't do this is that implementing such a disparate Map type adds a lot of code complexity. Adding strongly-typed helper methods (getAsString, getAsJSONArray, ...) is easier to implement and easier to use.

Ellie Crabcakes
Feb 1, 2008

Stop emailing my boyfriend Gay Crungus

As it turns out, json-simple's JSONObject does implement the Map interface and extends HashMap, which doesn't preclude getAsBoolean() or what have you, they just haven't seemed to put it in.

Aegisfury
Mar 24, 2009
Hey everyone, I had a quick question regarding an assignment I am doing and could use some advice or a hint. This is probably a dumb question but I've never been great at programming in any language. I am supposed to write a program that asks a user for two numbers, then display their input and perform a power calculation. This is what I have so far:

code:
import javax.swing.JOptionPane;

public class PowerInput
{
	public static void main(String[] args)
	{

	Float a;	// floating point a
	Long n;		// long n
	String base;
	String exponent;

	base = JOptionPane.showInputDialog("Enter the base number for this problem.");
	a = Float.parseFloat(base);
	exponent = JOptionPane.showInputDialog("Enter the exponent");
	n = Long.parseLong(exponent);

	JOptionPane.showMessageDialog(null, "You entered " +a+ " and " +n+ " .");

	double result = Math.pow(a, n);
	System.out.println("The answer is " +result+ ".");


	}
}
This basically works, however the assignment calls for us to use two programs, one that asks for the input and passes the values to the second, which performs the calculation and passes the result back to the first for display. I'm having trouble figuring out how to pass the input to a new method, then get that back. Any advice or some kind of example would be highly appreciated, as the textbook seems to just gloss over methods and passing values between them.

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

What is the specific trouble you're having? It's hard to tell right now since you didn't include any attempt at it in your source.

If it's just that you don't know where to begin, the short version is, you'll need a method that accepts two parameters of the same type as the numbers you get from the user, and returns a third of that type. Does that make sense in the context of the textbook?

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

Aegisfury posted:

This basically works, however the assignment calls for us to use two programs, one that asks for the input and passes the values to the second, which performs the calculation and passes the result back to the first for display. I'm having trouble figuring out how to pass the input to a new method, then get that back. Any advice or some kind of example would be highly appreciated, as the textbook seems to just gloss over methods and passing values between them.

The Oracle documentation is really good and really readable, it's worth a look to get a handle on the basics. This is the bit you want to look at (assuming you mean methods when you say programs)

Captain Cappy
Aug 7, 2008

So I have recently begun having to program in Java for my job and I was wondering what reflection's use case is. The few times I've seen it used in our codebase it just seems like a lazy and error prone way to get something done instead of just using an interface/closure/lambda. As a C++ programmer it just seems like a lovely attempt at templates without the benefits of compile time type-checking or speed.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
Generally you should never use reflection, with the only exception being cases where reflection is the only way to achieve something. The usual use case is interfacing with multiple different versions of external code, where a method you might want to call might not exist in some versions, or have had its parameters changed, or some other reason that you can't just write a method call and have it work with all the versions you want your application to work with.

Using reflection that only touches code you've written that will be deployed as an atomic unit is definitely a huge code smell.

Sedro
Dec 31, 2008

Captain Cappy posted:

So I have recently begun having to program in Java for my job and I was wondering what reflection's use case is. The few times I've seen it used in our codebase it just seems like a lazy and error prone way to get something done instead of just using an interface/closure/lambda. As a C++ programmer it just seems like a lovely attempt at templates without the benefits of compile time type-checking or speed.
Reflection is used for many types of meta-programming.

You might relate a class to a database table using annotations (e.g. @Column("VARCHAR(128)") String butts). The program would use reflection to read the annotations. There are many frameworks which offer this type of thing.

There is an alternate way of programming Java that's fairly common where you instead write your code as XML. Reflection is used heavily to instantiate objects and call methods on them. (knock yourself out)

Dependency injection is a technique used to wire a program together at runtime.

Sometimes you just need to get at something declared private in a third-party API.

Bleusilences
Jun 23, 2004

Be careful for what you wish for.

Hey it's me again!
I have a question about another assignment, everything is working but I am trying to catch exception and I don't understand why eclipse isnt letting me close the bufferedWriter in finally{. It is telling me I need to initialize the buffer before I can do so. I thought by setting it to null it would do the tricl!? I know I am missing something and this assigment, while easy, required me to figure a bunch of thing on my own.
code:
import java.util.Scanner;
import java.io.File;
import java.io.BufferedWriter;
import java.io.FileWriter;

//File utility took some reading to make 
public class FileUtilities {
	public static void main(String[] args) {
/*So I used the main to collect information from the user that will be needed to pass to other methods, like the file path
for the original file and  from the file that need to be copy into other methods*/
		String originalFilePath;
		String copyFilePath;
		Scanner input = new Scanner(System.in);

		System.out.println("Please input the file path of the original: ");
		originalFilePath = input.nextLine();
		System.out.println("Please input the file path of the future copy: ");
		copyFilePath = input.nextLine();
		//I close the scanner input because I wont need it anymore and I want the less scanner running as possible
		input.close();

		fileCopier(originalFilePath, copyFilePath);
		compareFile(originalFilePath, copyFilePath);

	}

	public static void compareFile(String originalFilePath, String copyFilePath) {

		boolean wroteToDistination = true;
		Scanner scanOriginal = null;
		Scanner scanCopy = null;

		try {
			scanOriginal = new Scanner(new File(originalFilePath));
			scanCopy = new Scanner(new File(copyFilePath));
			while (scanOriginal.hasNext()) {
				if (!scanOriginal.nextLine().equals(scanCopy.nextLine())
						|| scanCopy.hasNext() != scanOriginal.hasNext()) {
					wroteToDistination = false;
					break;
				}
			}
		} catch (java.io.IOException e) {
			System.out.print(e);
		} finally {
			if (scanOriginal != null)
				scanOriginal.close();
			if (scanCopy != null)
				scanCopy.close();
		}

		System.out.println(wroteToDistination);

	}

	public static void fileCopier(String originalFilePath, String copyFilePath) {
		String originalLine;
		Scanner scanReader = null;
		FileWriter copyFW = null;
		BufferedWriter copyBW = null;

		try {
			scanReader = new Scanner(new File(originalFilePath));
			copyFW = new FileWriter(copyFilePath);
			copyBW = new BufferedWriter(copyFW);
			while (scanReader.hasNext()) {
				originalLine = scanReader.nextLine();
				copyBW.write(originalLine);
				copyBW.newLine();
			}
			copyBW.close();
		} catch (java.io.IOException e) {
			System.out.print(e);

		} finally {
			if (scanReader != null)
				scanReader.close();
		}
	}
}

Bleusilences fucked around with this message at 21:30 on Apr 12, 2015

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
You're referring to copyBW in fileCopier? The following compiles, runs, and throws an NPE just as I'd expect.
Java code:
   public static void main(String[] args) throws Exception {
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(null);
        } finally {
            bw.close();
        }
    }
Throwing in an if-not-null check gets me the other NPE. I don't see any throws annotations on your methods; are you running into trouble because Closables.close() throws an IOException, which you're not catching inside your finally blocks?


Captain Cappy posted:

So I have recently begun having to program in Java for my job and I was wondering what reflection's use case is. The few times I've seen it used in our codebase it just seems like a lazy and error prone way to get something done instead of just using an interface/closure/lambda. As a C++ programmer it just seems like a lovely attempt at templates without the benefits of compile time type-checking or speed.

Java does have generics to fill C++'s Template's role. I find myself mostly using reflection alongside annotations, which in turn are mainly used to bind two loosely-related frameworks together.

Reflection helps power java's Proxy class, which is a very powerful tool. There's an interface, InvocationHandler, which defines a method that accepts a Method and an array of Object[] arguments. You can then create a proxy, given an Interface class and an Invocation handler, which then implements that Interface, but passes all method calls directly to the InvocationHandler. This lets you set up frameworks with interceptors, create Mock-objects for tests, all sorts of neat stuff.

Bleusilences
Jun 23, 2004

Be careful for what you wish for.

Gravity Pike posted:



Throwing in an if-not-null check gets me the other NPE. I don't see any throws annotations on your methods; are you running into trouble because Closables.close() throws an IOException, which you're not catching inside your finally blocks?



Not even, it catches everything, But that's what eclipse complain about if I put it in finally. But if Closables.close() throws ioexception maybe it's for the best to be in the body.

Bleusilences fucked around with this message at 02:30 on Apr 15, 2015

Volmarias
Dec 31, 2002

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

Bleusilences posted:

Not even, it catches everything, But that's what eclipse complain about if I put it in finally. But if Closables.close() throws ioexception maybe it's for the best to be in the body.

No, it's right and proper to have your close method in the finally block, unless you're using the new fancy java try-with-resources stuff. You just have another try/catch block inside of the finally block to catch a possible exception being thrown there.

Bleusilences
Jun 23, 2004

Be careful for what you wish for.

Volmarias posted:

No, it's right and proper to have your close method in the finally block, unless you're using the new fancy java try-with-resources stuff. You just have another try/catch block inside of the finally block to catch a possible exception being thrown there.

Ok it's done thanks the assignment was due today so I had the time to make the adjustment. I also realized that I forgot to call a method in my last class to close multiple stream.

Bleusilences fucked around with this message at 03:11 on Apr 15, 2015

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

Volmarias posted:

No, it's right and proper to have your close method in the finally block, unless you're using the new fancy java try-with-resources stuff. You just have another try/catch block inside of the finally block to catch a possible exception being thrown there.

With OutputStreams, I prefer to close in the try, and then again in the catch. The way it's implemented, the buffer will flush when it needs to during write, and then once again, finally, during the close. This means that if close throws, you need to treat it the same way you'd treat write throwing an IOException, usually accounting for the fact that you may have an incomplete file on your system. (See the discussion on Guava's Closeables.closeQuietly method.)

brand engager
Mar 23, 2011

Do stream wrappers not play nicely with swing components? I've got an InputStream from a Socket wrapped in a Scanner, and a Timer that calls nextLine() from that scanner once every second. When that happens the swing components just stop responding to input, and the cursor in my JTextField stops blinking. Everything works for the first few seconds after the program is run, but as soon as the scanner doesn't have any more lines to read the swing components just stop doing their thing.
What is happening here?

Edit: More searching shows that it might be "blocking" and I have to use threads. I don't know poo poo about threads or threadsafe or any of that. :blush:

brand engager fucked around with this message at 03:31 on Apr 16, 2015

Volguus
Mar 3, 2009

SperginMcBadposter posted:

Do stream wrappers not play nicely with swing components? I've got an InputStream from a Socket wrapped in a Scanner, and a Timer that calls nextLine() from that scanner once every second. When that happens the swing components just stop responding to input, and the cursor in my JTextField stops blinking. Everything works for the first few seconds after the program is run, but as soon as the scanner doesn't have any more lines to read the swing components just stop doing their thing.
What is happening here?

Edit: More searching shows that it might be "blocking" and I have to use threads. I don't know poo poo about threads or threadsafe or any of that. :blush:

don't worry. just use SwingWorker.

brand engager
Mar 23, 2011

Couldn't figure out what to do with swingworker. I got it working with the nextLine() in it's own thread, but the threads are constantly making GBS threads out IndexOutOfBoundsExceptions.
Like this
code:
Exception in thread "Thread-6" java.lang.IndexOutOfBoundsException: end
	at java.util.regex.Matcher.region(Matcher.java:1038)
	at java.util.Scanner.hasTokenInBuffer(Scanner.java:873)
	at java.util.Scanner.hasNext(Scanner.java:1337)
	at irc.Irc$ReadThreaded.run(Irc.java:84)
	at java.lang.Thread.run(Thread.java:745)
The threaded part looks like
Java code:
private class ReadThreaded implements Runnable
    {
        @Override public void run()
        {
            if (socketInWrapper.hasNext()) //this is line 84 referenced in the trace above
            {
                streamInput = socketInWrapper.nextLine();
                if(streamInput.startsWith("PING ")) {ping(streamInput); return;}
                displayString(streamInput);
            }
        }
    }
It still works, but something about it being threaded now is making that java.util code poo poo out that exception whenever the stream doesn't have anything to be read.

Doin its thing

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
Go through this tutorial first, you typically don't want to try and update any swing components outside of the EDT or else you will block your UI. The swing worker helps you do that in a simple class without having to know too much about threads and concurrency. That tutorial should hopefully get you started on the right track and feel free to ask more questions.

https://docs.oracle.com/javase/tutorial/uiswing/concurrency/interim.html

VegasGoat
Nov 9, 2011

SperginMcBadposter posted:

It still works, but something about it being threaded now is making that java.util code poo poo out that exception whenever the stream doesn't have anything to be read.

Did you change the socket to non-blocking at some point while troubleshooting? If so put it back to blocking mode.

Like Janitor Prime said you also need to update the GUI from the event dispatch thread. So in your ReadThreaded class instead of calling displayString() directly you'd call SwingUtilities.invokeLater() with a different Runnable object that calls displayString(). It might seem like overkill, and the program may even seem to work without that but at some point you will see weird behavior like parts of the GUI not updating, or text being cut off or something like that.

Adbot
ADBOT LOVES YOU

Slime
Jan 3, 2007
So I've got an object which contains an object which contains a 2D array of objects that each have an object that has a vector that the top object needs to get stuff from. It's kinda lovely, any recommendations on handling this in a way that doesn't suck?

Edit: I suppose this can be considered a general OO question, but I'm doing it in Java, so...yeah.

Slime fucked around with this message at 19:21 on Apr 16, 2015

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