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
Volguus
Mar 3, 2009

FateFree posted:

Think about driving a car. You don't know or care how an engine works, all you know is theres a go pedal and a stop pedal and a steery wheel. Thats the interface to driving any car, gas, electric, whatever. Hiding complexity makes something easy to use and easy to understand. You want to take these concepts and apply them to code so that the classes you write are easy to use and easy to understand. If something doesn't need to be public, don't make it public. The entire goal of all this is to reduce complexity to make code easier to understand by you, and whoever else uses it.

To add to this:
Not only to make it easy to understand and use, but also to be able to change the internals in the future. If my car's engine gets suddenly an upgrade and now all of its internals are changed (and is more efficient) i still interact with it via the pedals and the steering wheel. I just get wherever I want to go faster, but otherwise everything is unchanged.
The less the users of your class know about its internals, the more freedom you have to change those internals whenever you want without breaking those users.

Adbot
ADBOT LOVES YOU

crimedog
Apr 1, 2008

Yo, dog.
You dead, dog.
Kind of a silly question, but which functionally identical java.time format() idiom is preferred?

code:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

private static DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyMMdd-HHmmss");

public static String timestamp() {
  return LocalDateTime.now().format(timeFormatter);
  // Or
  return timeFormatter.format(LocalDateTime.now());
}

For reference, this is for nothing important. I'm just giving a new image files unique filenames quickly without stopping the program.

Kuule hain nussivan
Nov 27, 2008

Another retarded problem with filepaths...

I'm trying to bundle my program into an executable jar, but I keep having trouble with one method. The method returns the number of files in a directory, and I'm using the file.list().length to get the info. But when I try to create a new file using new File(this.getClass.getResource("/directoryName").getPath()), it throws a null exception. I've checked that this returns a correct looking path (/home/loads/of/dirs/myProgram/target/classes/dirIWantToOpen). I also double checked that Maven does throw the directory and necessary files into /target/classes. Any idea why this doesn't work?

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

Which method is throwing the NPE? Look at your stack trace and see which one is flipping out (the top one), and look at any other exceptions begin thrown earlier (further down) and see if you can tell which one is actually running into a problem. Once you know which method is keeling over, you can start looking at why - the docs :airquote:should:airquote: tell you the circumstances when it throws NullPointerException, and you can step through in a debugger or do some logging and make sure the right thing is being passed at every step. You're getting a null somewhere you shouldn't!

Also where are you getting that correct-looking path? Are you logging it before you call the File constructor? Is this only failing in the executable version?

Kuule hain nussivan
Nov 27, 2008

baka kaba posted:

Which method is throwing the NPE? Look at your stack trace and see which one is flipping out (the top one), and look at any other exceptions begin thrown earlier (further down) and see if you can tell which one is actually running into a problem. Once you know which method is keeling over, you can start looking at why - the docs :airquote:should:airquote: tell you the circumstances when it throws NullPointerException, and you can step through in a debugger or do some logging and make sure the right thing is being passed at every step. You're getting a null somewhere you shouldn't!

Also where are you getting that correct-looking path? Are you logging it before you call the File constructor? Is this only failing in the executable version?
It's throwing the NullPointerException when I try to do anything with the File. I got the path by making a String path = this.getClass.getResource("/directoryName").getPath() and then using that to initialize the new File. This fails with the source code, so it won't actually build the jar out of it.

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

Can you post the stack trace? I'm not sure what you mean by "fails with the source code," do you mean during compilation? Or are you talking about a Java method you wrote to create a .jar file from a directory?

Kuule hain nussivan
Nov 27, 2008

carry on then posted:

Can you post the stack trace? I'm not sure what you mean by "fails with the source code," do you mean during compilation? Or are you talking about a Java method you wrote to create a .jar file from a directory?

Sure. Sorry about not being clear, I meant it fails when I try to build it. The previous version of the method just used the file path on my computer to initialize the File, so of course that didn't work when I made an executable jar out of it.

Anyway, the stack trace is...

code:
Exception in thread "main" java.lang.NullPointerException
	at com.nurikabe.controller.Nurikabe.getNumberOfLevels(Nurikabe.java:102)
	at com.nurikabe.GUI.Gui.setupMainMenu(Gui.java:166)
	at com.nurikabe.GUI.Gui.<init>(Gui.java:45)
	at com.nurikabe.controller.Nurikabe.start(Nurikabe.java:62)
	at com.nurikabe.controller.Nurikabe.main(Nurikabe.java:24)
Line 102 is where I try to get the number of files from the File object using File.list().length.

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

That means either your File object is null, or list() is returning null. Since you're sure you actually have a non-null File object there, it's probably the list() call. Let's investigate the docs:

quote:

Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.
If this abstract pathname does not denote a directory, then this method returns null. Otherwise an array of strings is returned, one for each file or directory in the directory. Names denoting the directory itself and the directory's parent directory are not included in the result. Each string is a file name rather than a complete path.

quote:

Returns:
An array of strings naming the files and directories in the directory denoted by this abstract pathname. The array will be empty if the directory is empty. Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.

That's a pretty strong clue, and Files tend to thrown NPEs on their methods when something doesn't actually exist. The important thing to realise is that a File isn't actually referring to a thing on disk, it's a convenience class for holding a path and a few useful methods. I can do new File("C:\Butts\butt1.jpg") and get a File object back, but it doesn't mean that location actually exists. That's why there are methods like exists() and mkdirs(), and abstract methods like getName() which only manipulates the path it's been given, and gives no fucks about whether it also happens to be the path to a real file somewhere

Oh also, it's probably not an I/O error, because usually (?) that would show up lower down on the stack trace like I was saying - an IOException would be thrown, and in turn that would cause File to throw its NullPointerException like it says it will, and you get those causes listed in reverse order in the trace

baka kaba fucked around with this message at 23:57 on Oct 11, 2015

Volguus
Mar 3, 2009

crimedog posted:

Kind of a silly question, but which functionally identical java.time format() idiom is preferred?

code:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

private static DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyMMdd-HHmmss");

public static String timestamp() {
  return LocalDateTime.now().format(timeFormatter);
  // Or
  return timeFormatter.format(LocalDateTime.now());
}

For reference, this is for nothing important. I'm just giving a new image files unique filenames quickly without stopping the program.

Either would work, I wouldn't worry too much about it. However, if you want to generate unique filenames ... timestamps are one of the worst things to do. You're better off with an AtomicInteger (or long ) that just gets incremented.
Why time is a bad choice for uniqueness?

1. Server-side application: You will have 2 people doing the same thing at the same time. Therefore, you will overwrite one file with the other.
2. Even on client side application, single threaded, that has a sleep for 2 seconds between runs, can still overwrite? Why? Read this list: Falsehoods programmers believe about time
(most importantly point number 1. On Nov 1st this year, in timezones who observe DST there will be 01:00:00 twice. An hour apart. And the day has obviously 25 hours).

If those filenames are not for humans to read just use UUID. That's not 100% unique, but is good enough for most things. Or Apache Commons library that can generate unique strings. Or just a number.

ExcessBLarg!
Sep 1, 2001

Volguus posted:

You're better off with an AtomicInteger (or long ) that just gets incremented.
Works until the process is restarted, then you start overwriting a bunch of stuff.

Volguus posted:

On Nov 1st this year, in timezones who observe DST there will be 01:00:00 twice.
The real horror is not including a zone offset in the format pattern.

Edit: Oh right, it's not the horrors thread.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

ExcessBLarg! posted:

Works until the process is restarted, then you start overwriting a bunch of stuff.

You can just query the output directory and start from where you left off.

Kuule hain nussivan
Nov 27, 2008

baka kaba posted:

That means either your File object is null, or list() is returning null. Since you're sure you actually have a non-null File object there, it's probably the list() call. Let's investigate the docs:



That's a pretty strong clue, and Files tend to thrown NPEs on their methods when something doesn't actually exist. The important thing to realise is that a File isn't actually referring to a thing on disk, it's a convenience class for holding a path and a few useful methods. I can do new File("C:\Butts\butt1.jpg") and get a File object back, but it doesn't mean that location actually exists. That's why there are methods like exists() and mkdirs(), and abstract methods like getName() which only manipulates the path it's been given, and gives no fucks about whether it also happens to be the path to a real file somewhere

Oh also, it's probably not an I/O error, because usually (?) that would show up lower down on the stack trace like I was saying - an IOException would be thrown, and in turn that would cause File to throw its NullPointerException like it says it will, and you get those causes listed in reverse order in the trace
Yeah, I figured it's not finding the specified content at the path I gave it, but the problem is I'm completely stumped on how to build a working filepath in Maven. My current method works if I want to initialize an InputStream (InputStream in = this.getClass().getResourceAsStream()), and this.getClass().getResource().getPath() returns a path with the directory and files I'm looking for, but for some reason, when I try to initialize a new file with it, it just won't find the directory.

Sedro
Dec 31, 2008
Resources are placed inside jar (which is a zip file) so you shouldn't treat them like files. That's why getResource returns a URL.

Kuule hain nussivan
Nov 27, 2008

Sedro posted:

Resources are placed inside jar (which is a zip file) so you shouldn't treat them like files. That's why getResource returns a URL.
So should I be using getResourceAsStream then? Any idea if I can get the number of files in the directory from the InputStream somehow? I have a feeling that might mean I need to mess with bytes, so it's probably easier to just do a variable with the number of files in it and just update that manually.

Zaphod42
Sep 13, 2012

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

Squashy Nipples posted:

No, that's all good, that's pretty much exactly what I wanted to hear.

The only concept I'm a little fuzzy on is what makes a Method "Static". It barked at me and told me to make my Method static, but without that prompt I wouldn't have known to add that keyword.

EDIT:
HOLY CRAP, I'm in love with Refactoring. My code is short at the moment, but it's still a timesaver.

Static means static, versus dynamic. A static class is like old school C code, you call it and it executes the subroutine and then comes back, simple. Dynamic (any class that doesn't have static) means that you have to have an instance of the object first before you can do anything with it.

For example, think of a Math class. The class handles addition, subtraction, division, etc. There's no need to instance that class, since it has no class variables. Each method is just a quick throwaway method where you pass it parameters and get some result back. Really simple.

But consider a more advanced Calculator class, which could store the result of an operation and then use that in the next operation. Now you could still have it be a static class, and it could store the result of the first operation in some class variable. But what if you later want a second calculator to keep track of different operations? You could have several variables, or the class could have a whole List of results, and you'd have to tell it which numbered result slot to use. But alternatively you could make the class dynamic.

Having a dynamic Calculator class means you could simply instantiate Calculators when you need them, and each Calculator instance only has access to its own copies of the class variables. So one Calculator has a stored Result, and another Calculator has its own stored Result. Each calculator doesn't know about the other and doesn't know abut the other's results. They don't mess with each other, the code is effectively copied to multiple separate object instances.

The difference between Static and non-static (dynamic) classes forms the basis for OOP, Object Oriented Programming. If you don't know what static means, its because you need to learn OOP. OOP is pretty complicated but ultimately allows you to organize your code so it doesn't turn into spaghetti.

Squashy Nipples posted:

So which is it? Is Encapsulation is optional or mandatory?

For OOP, encapsulation is pretty drat important. But you can write non-OOP Java code; you just probably shouldn't.

Kuule hain nussivan posted:

So should I be using getResourceAsStream then? Any idea if I can get the number of files in the directory from the InputStream somehow? I have a feeling that might mean I need to mess with bytes, so it's probably easier to just do a variable with the number of files in it and just update that manually.

Yep, getResourceAsStream(...) should work pretty well for grabbing files from within the JAR.

Zaphod42 fucked around with this message at 15:35 on Oct 12, 2015

Squashy Nipples
Aug 18, 2007

Zaphod42 posted:

The difference between Static and non-static (dynamic) classes forms the basis for OOP, Object Oriented Programming. If you don't know what static means, its because you need to learn OOP. OOP is pretty complicated but ultimately allows you to organize your code so it doesn't turn into spaghetti.

For OOP, encapsulation is pretty drat important. But you can write non-OOP Java code; you just probably shouldn't.

Interesting. I thought that OOP just meant "I can pull in APIs, and get access to their Objects' Fields and Methods."

Guess not. :)


Anyway, I've been enjoying working through the tutorial trail, building little programs and learning as I go. But I just hit a major roadblock with the Nested Classes topic (Inner, Local, Anonymous, and Lambda expressions). It's just too much for my brain to absorb all at once. I'm just venting, please don't write me any novels trying to explain it; I'm just going to have to bash my head into a few times until it sticks, because that's how I learn.

I really enjoyed the Enum topic, though. I expanded on the Card and Deck Objects to build a simple Blackjack game, and that makes me happy. I think I'm going to use Enum as the first method to crack the Pokedex program (my student is still hacking around with infinite nested flow control).
I think this works like this:

1. Build an Enum Class for each category (Region, Type, Sub Type, Egg Type....). These will just be a simple lists with no data.

2. Build a Pokemon Class with a Constructor that requires a name string, and one each of each of the Enums.
Include Methods full pulling out each of the Fields.

3. Build a Pokedex Class that contains an Array of Pokemon Objects. Fill the Array manually with Pokemon Objects like this:
code:
static final int countPokemon = x;  // x = whatever the population count is
private static Pokemon[] = new  Pokemon[x];

Pokemon[0] = new Pokemon(Name, Region, Type, Sub Type, Egg Type....)
Pokemon[1] = new Pokemon(Name, Region, Type, Sub Type, Egg Type....)
...
Add Methods that return individual Pokemon by Name, or complete set of inputs

public Pokemon getByName(String pokeName)

public Pokemon getByStats(String[] pokeStats)


Does that make some sense?

Squashy Nipples fucked around with this message at 18:24 on Oct 12, 2015

Zaphod42
Sep 13, 2012

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

Squashy Nipples posted:

Interesting. I thought that OOP just meant "I can pull in APIs, and get access to their Objects' Fields and Methods."

Guess not. :)

Absolutely not. Languages like C let you pull in APIs and use their functions, but they are not OOP. OOP is a paradigm, its a philosophy of how to organize code.

https://en.wikipedia.org/wiki/Object-oriented_programming

Most anything could be written as OOP or as not-OOP, but in general the OOP way is considered to be easier to read and understand and maintain.

Squashy Nipples posted:

Does that make some sense?

Yep, that all makes enough sense.

But like I asked before when you discussed 'guess pokemon' thing, how do you handle collisions? That is to say, if you ask for a pokemon that is from region 1 and has egg type 1 (I don't know) and there's 10 pokemon that match that, do you just return the first one that does, or what?

Squashy Nipples
Aug 18, 2007

Zaphod42 posted:


Yep, that all makes enough sense.

But like I asked before when you discussed 'guess pokemon' thing, how do you handle collisions? That is to say, if you ask for a pokemon that is from region 1 and has egg type 1 (I don't know) and there's 10 pokemon that match that, do you just return the first one that does, or what?

First iteration will be FULL stats only: give it a full set of stats, it pulls back the one pokemon it could be.

Next Iteration will return sets of possible pokemon based on what the user decides to input.

After that, we're going to start over: build a real RDB and teach the kid SQL queries.

pepito sanchez
Apr 3, 2004
I'm not mexican
nevermind. solved!

pepito sanchez fucked around with this message at 15:49 on Oct 13, 2015

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

Squashy Nipples posted:

gotta catch em all

Things like inner classes depend on an understanding of instances and static elements, so don't worry if you don't get all the nuances yet. They're mostly a way of encapsulating functionality without going to the trouble of creating a whole new class file

Your Pokemon thing is ok, but why are you falling back on arrays? I really think you need to explore the Collections package, just to see what else is out there and what it can do for you. Arrays can involve a lot of unnecessary janitoring

For example, finding a pokemon by name with an array means iterating over its length, looking at each element in turn and comparing it to your input. Finding by a group of stats means iterating over the array looking for one stat, collecting the matching results in another structure (another array if you really want to hate yourself), then iterating over that to find the next trait and collect them into another structure... or some situation where you copy the array and zero out non-matching results as you go, and collect the remaining ones when you're done. That's pretty awkward

Or you can use a HashMap and do get(name), and then you got your pokemon in one line. You can add and delete to your heart's content, letting them dream up their own pokemon without worrying about gaps in the array or having to copy everything to a bigger one when you run out of space. You can iterate over the result of values() (which will return all the pokemon) and remove() any pokemon that don't match the traits you're checking

It's a really good idea to get familiar with this stuff, it's incredibly useful and lets you focus on the logic and manipulating the tools, instead of wrangling an array to reinvent the (square) wheel and get some basic functionality. I've been there! Sometimes arrays are the right choice, usually not though

Zaphod42
Sep 13, 2012

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

Squashy Nipples posted:

First iteration will be FULL stats only: give it a full set of stats, it pulls back the one pokemon it could be.

Next Iteration will return sets of possible pokemon based on what the user decides to input.

After that, we're going to start over: build a real RDB and teach the kid SQL queries.

Yeah but even with a full stats set you're still not going to get only one pokemon. I'm not super familiar with all the rules of pokemon but even from what I know of the original pokemon you'd have a ton of collisions. Unless one of the stats is pokemon name in which case you may as well just supply that single unique field, there's no point in supplying the other stats or else the program is just telling you what you already know.

Like I said you could just return the first pokemon that matches or a random pokemon that matches or you could return the full set, but there are going to be collisions and you need to plan for how you're going to handle it.

There's just too many pokemon and not enough unique stats, pidgeonhole principle applies.

baka kaba posted:

Your Pokemon thing is ok, but why are you falling back on arrays? I really think you need to explore the Collections package, just to see what else is out there and what it can do for you. Arrays can involve a lot of unnecessary janitoring

Yeah I was about to say this myself earlier but I didn't just because I feel like I've already said it to Squasy Nipples a lot, but dude.

USE LISTS. THEY'RE GOOD FOR YOU.

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

Zaphod42 posted:

pidgeonhole principle applies.

Is this a pokemon?

Zaphod42
Sep 13, 2012

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

baka kaba posted:

Is this a pokemon?

Um, is this a joke?

No, its math. https://en.wikipedia.org/wiki/Pigeonhole_principle

Its not exactly the same situation here since this is a multi-variable box, but the idea still works more or less.

Like with multiple variables it isn't as simple as just n > m but you're going to hit the same problem.

Squashy Nipples
Aug 18, 2007

Zaphod42 posted:

There's just too many pokemon and not enough unique stats, pidgeonhole principle applies.

Crap. You mean that there are Pokemon that are identical EXCEPT for the name and picture?

What a stupid game. Maybe I'll just use playing cards for our homework stuff.



Zaphod42 posted:

USE LISTS. THEY'RE GOOD FOR YOU.

Ok, Lists it is. I just haven't gotten that far in the trail yet.

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

Zaphod42 posted:

Um, is this a joke?

I had a go :v:

Squashy Nipples posted:

Crap. You mean that there are Pokemon that are identical EXCEPT for the name and picture?

What a stupid game. Maybe I'll just use playing cards for our homework stuff.

It might be overcomplicating things slightly, but it's good practice to check for these things - deciding how to handle a hit, multiple hits or none at all. Even if you just end up returning the first result, you need to think it over and decide that's the best or an acceptable thing to do. A lot of programming is about these decisions, and especially considering the cases you need to handle

baka kaba fucked around with this message at 19:13 on Oct 12, 2015

Zaphod42
Sep 13, 2012

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

Squashy Nipples posted:

Crap. You mean that there are Pokemon that are identical EXCEPT for the name and picture?

What a stupid game. Maybe I'll just use playing cards for our homework stuff.

Hahaha yeah, that's what I'm saying. It is is a pretty dumb game in a number of ways (EVs, yuck)

I mean... it depends upon how specific "stats" are. Like, is pokedex number a stat? If so that's globally unique for each, but that's pretty much the same as name.

Are things like height and weight and stuff stats? If so, that's a pain in the rear end to have to enter in numbers like that, not very useful. If not, then yeah you're going to have collisions.

And I could even be wrong, it could be that every pokemon has at least one degree of difference from other pokemon's stats. But I have a feeling there's several collisions unless you get into really really specific traits.

Like Picachu and Raichu are both egg group field and fairy, and are electric type that are in the same regions, because they're in the same family. Raichu is a 3rd stage evolution though so I guess you could filter them on that?

But yeah, there are going to be pokemon that are identical other than name, unless you get insanely specific to the point where you have to enter in the starting stat-ranges for each species or something.

Oh, that actually raises another issue. Things like egg type aren't a single value, which makes your enums not such a great choice. Picachu is both field and fairy type. I guess you could still have the enums and then just make egg type a List or Array of those enums, which would be easier than having N-factorial enums total.

Squashy Nipples
Aug 18, 2007

^ From what my student showed me, "type" is the only dual stat, so I was thinking "Type1" (no NULLs) and "Type2" (NULL OK).
But yeah, sounds like I've made a variety of bad assumptions about the data.

baka kaba posted:

It might be overcomplicating things slightly, but it's good practice to check for these things - deciding how to handle a hit, multiple hits or none at all. Even if you just end up returning the first result, you need to think it over and decide that's the best or an acceptable thing to do. A lot of programming is about these decisions, and especially considering the cases you need to handle

Yup, I'm used to validating my RecordSets: just because you THINK you know what you are getting back, that's not always the case. So, check for unexpected EOF, and make sure that the RecordCount is within expected range. Same idea.

TheresaJayne
Jul 1, 2011

baka kaba posted:

Things like inner classes depend on an understanding of instances and static elements, so don't worry if you don't get all the nuances yet. They're mostly a way of encapsulating functionality without going to the trouble of creating a whole new class file

Your Pokemon thing is ok, but why are you falling back on arrays? I really think you need to explore the Collections package, just to see what else is out there and what it can do for you. Arrays can involve a lot of unnecessary janitoring

For example, finding a pokemon by name with an array means iterating over its length, looking at each element in turn and comparing it to your input. Finding by a group of stats means iterating over the array looking for one stat, collecting the matching results in another structure (another array if you really want to hate yourself), then iterating over that to find the next trait and collect them into another structure... or some situation where you copy the array and zero out non-matching results as you go, and collect the remaining ones when you're done. That's pretty awkward

Or you can use a HashMap and do get(name), and then you got your pokemon in one line. You can add and delete to your heart's content, letting them dream up their own pokemon without worrying about gaps in the array or having to copy everything to a bigger one when you run out of space. You can iterate over the result of values() (which will return all the pokemon) and remove() any pokemon that don't match the traits you're checking

It's a really good idea to get familiar with this stuff, it's incredibly useful and lets you focus on the logic and manipulating the tools, instead of wrangling an array to reinvent the (square) wheel and get some basic functionality. I've been there! Sometimes arrays are the right choice, usually not though

/me shies away from mention of pokemon :sob: I have to refactor the battle code in pixelmon mod for minecraft. Its a horror and a half

unpacked robinhood
Feb 18, 2013

by Fluffdaddy
I'm trying to parse a css file to build a java representation of the following file. Css classes should be grouped in a different list depending on their background color.

code:
/*free*/
.s15,.s16,.s25,.s26,.s27,.s28,.s34,.s17,.s35,.s36,.s37,.s38,.s39,.s40,.s41,.s42,.s43,.s44,.s18,.s45,.s19,.s20,.s21,.s22,.s23,.s24{background-color:#00d25d;}
/*available*/
.s29,.s30,.s31,.s32,.s33{background-color:#ff950b;}
I'm using the following regexp to match each different line
code:
.*(background-color.*);
then
code:
Pattern p= Pattern.compile(".*(background-color.*);");
Matcher m=p.matcher(doc.text());

while (m.find()) { 
                       
                        Log.d("dbg", "matcher\t " + m.group(0));
                        Log.d("dbg", "matcher\t " + m.group(1));
}
For some reason it will only go though the loop one time (instead of 2)

What's going on here ?

Basically I'd like to detect each different line containing a background-color instruction and do things to the string.

e: I'm not convinced it's the correct way to do it, but I'd like to understand why it doesn't seem to work the way I think it would.

unpacked robinhood fucked around with this message at 16:11 on Oct 13, 2015

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.
E: Nm, that website was just hosed. The regex should be good.

I'm not sure, that looks fine but I haven't used matcher a ton myself.

Zaphod42 fucked around with this message at 17:36 on Oct 13, 2015

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

TheresaJayne posted:

/me shies away from mention of pokemon :sob: I have to refactor the battle code in pixelmon mod for minecraft. Its a horror and a half

An entire game franchise added into minecraft? How hard can it be!

Now I'm hoping minecraft is based around one giant 3-dimensional array. Although maybe that would actually be the best way :ohdear:

Zaphod42
Sep 13, 2012

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

TheresaJayne posted:

/me shies away from mention of pokemon :sob: I have to refactor the battle code in pixelmon mod for minecraft. Its a horror and a half

Hah, I've played that mod. Its pretty cool, but it also feels super janky so yeah, I would hate to see what the code looks like.

MInecraft in general is a mess of some code that's good and some code that's really ugly. I had fun working on minecraft mods though, and I'm tempted to go back...

baka kaba posted:

Now I'm hoping minecraft is based around one giant 3-dimensional array. Although maybe that would actually be the best way :ohdear:

It is and it isn't. The game world is built in an array of chunks, (actually I don't even think its an array) and each chunk object has its own 3-dimensional array of blocks. Chunks can be dynamically loaded and unloaded, which sometimes fucks up and is why every once in awhile minecraft just doesn't load a big square area of the map and you just have this pit that you can see into, until you walk into that pit and suddenly it loads the terrain. The chunk got unloaded and never loaded properly, but entering that chunk forces it to re-load.

In addition to that you have players and animals and stuff that aren't blocks which have to be stored in big lists and called upon as necessary.

Minecraft modding is pretty fun and simple for a 3D game, I really wish it had better official mod support. Having to de-compile the java code is so loving ugly, even if there's lots of APIs and toolkits to make it less painful and update the references with human-readable names.

Notch promised he was going to make an API like 5 loving years ago, made a bitbucket account for it, and then did gently caress-all with it. :argh:

He's too busy counting his money now to worry about the state of Minecraft's development, which he completely handed off to some nobody programmers. And surprise, surprise, Minecraft's development has completely stagnated since.

Zaphod42 fucked around with this message at 22:00 on Oct 13, 2015

M31
Jun 12, 2012

unpacked robinhood posted:

e: I'm not convinced it's the correct way to do it, but I'd like to understand why it doesn't seem to work the way I think it would.
It's definitely not the correct way. Use one of the many CSS parsers out there.

That being said: the code you posted is correct, so something else is going wrong. One thing I can think of is that the actual input does not contain any newlines, which would be pretty obvious from the output though and can be 'fixed' by using non-greedy modifiers in your regular expression:
code:
Pattern.compile(".*?(background-color.*?);")
or more specific selectors:
code:
Pattern.compile("[^}/]*(background-color[^;]*);");

unpacked robinhood
Feb 18, 2013

by Fluffdaddy

M31 posted:

It's definitely not the correct way. Use one of the many CSS parsers out there.

That being said: the code you posted is correct, so something else is going wrong. One thing I can think of is that the actual input does not contain any newlines, which would be pretty obvious from the output though and can be 'fixed' by using non-greedy modifiers in your regular expression:
code:
Pattern.compile(".*?(background-color.*?);")
or more specific selectors:
code:
Pattern.compile("[^}/]*(background-color[^;]*);");

The first one works, thanks !

FieryBalrog
Apr 7, 2010
Grimey Drawer
It still blows my mind that Java hasn't overridden the == operator on String to mean the same thing as equals().

AFAIK you already can't rely on String == comparison for reference equality because of interning, and in any case it sounds to my newbie ears like a horrible practice to rely on distinguishing String references for code to work.

Zorro KingOfEngland
May 7, 2008

== compares reference equality. If you want to compare string equality, you use the .equals method. These two things are logically different, and so they must be separated out.

If I had to guess, I'd say the reason it hasn't been changed is because it would break a lot of existing code that relies on null checks (so basically every non-trivial program out there) so for example:

Java code:
	if(someString != null)
would translate into

Java code:
	if(!someString.equals(null))
The first is perfectly safe if someString is null, but the second would throw a NullPointerException.

How would you write a null check if == became syntactic sugar for .equals?

Jo
Jan 24, 2005

:allears:
Soiled Meat
Update on a previous question. I have a library I'm working on (link). I'd like to make a trainer which uses OpenCL, but since trainers are pluggable, I don't want to make OpenCL a requirement to build the project. I could just say, "Yo, delete this file after you clone the repo," but that seems like a terrible solution. What are my options as far as including a library for a single class file during compile time? Anything like conditional compilation #ifdefs in C?

Volmarias
Dec 31, 2002

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

Zorro KingOfEngland posted:

== compares reference equality. If you want to compare string equality, you use the .equals method. These two things are logically different, and so they must be separated out.

If I had to guess, I'd say the reason it hasn't been changed is because it would break a lot of existing code that relies on null checks (so basically every non-trivial program out there) so for example:

Java code:
	if(someString != null)
would translate into

Java code:
	if(!someString.equals(null))
The first is perfectly safe if someString is null, but the second would throw a NullPointerException.

How would you write a null check if == became syntactic sugar for .equals?

You could probably have some additional behavior regarding comparing objects to null. Regardless,

code:

String s1 = "abcde"
String s2 = "abcde"

println(s1 == s2)
Object o1 = s1
Object o2 = s2
println(s1 == o2)
println(s2 == o2)
println(o1 == o2)


What semantics do you invoke here when checking actual objects that may or may not be strings? What do you expect the output to be?

FieryBalrog
Apr 7, 2010
Grimey Drawer
Yup. On the other hand:

code:
        String s1 = "abcde";
        String s2 = "abcde";

        System.out.println(s1 == s2);
        Object o1 = s1;
        Object o2 = s2;
        System.out.println(s1 == o2);
        System.out.println(s2 == o2);
        System.out.println(o1 == o2);

        String s3 = new String("abcde");
        System.out.println(s2 == s3);
code:
true
true
true
true
false
So it's not like you can know ahead of time which String was created with new and which was created with a literal...

In any case, I don't know what the answer would be for existing null comparisons. Maybe it's way too late to do this. Or maybe they just change equals itself.

Something that has always bothered me about equals() is that a.equals(b) throws NPE when a is null but not when b is null. Equality seems like it should behave symmetrically, without respect to the state of either input to the comparison, which is also something that the contract of course specifies (outside of the null case). Yeah it's a method on an object, but it's also special! Wouldn't it have been better if it just never threw NPE? Is there any technical reason why a == b never needs to throw null pointer but a.equals(b) can't be changed to do the same?

FieryBalrog fucked around with this message at 00:26 on Oct 15, 2015

Adbot
ADBOT LOVES YOU

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
Because invoking a method on an object requires the object to exist, otherwise you don't even know what bit of code you're trying to call. ==, being an operator, is more like a static function. There actually isn't anything special about the equals() method other than it being defined on the Object class.

Note that you can use the static function Objects.equals(a, b) if you want a null-safe equality check.

Jabor fucked around with this message at 01:01 on Oct 15, 2015

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