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
Zaphod42
Sep 13, 2012

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

casual poster posted:

I've never used a debugger before (it never came up during my lessons, I think netbeans comes with one though, I'll have to play around with it tomorrow.

A lot of new programmers put off debuggers or don't know they exist or aren't taught about them for a long time, which is a huge mistake.

They're a very easy and intuitive way to look into how your code is operating. Definitely learn debugging. Not complicated at all

Adbot
ADBOT LOVES YOU

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

Here's a post I wrote on how to use the debugger in Netbeans, with screenshots: http://forums.somethingawful.com/showthread.php?threadid=2780384&pagenumber=192&perpage=40#post441859581

e: and if you want to get really crazy, you can do what's called remote debugging, and not even have to be on the same computer as the program while you debug: http://forums.somethingawful.com/showthread.php?threadid=2780384&pagenumber=203&perpage=40#post449656064

Probably not useful to a beginner, but you can see the lengths to which programmers will go t omake their debugger available. It's really useful.

carry on then fucked around with this message at 16:24 on Feb 7, 2016

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:

They're a very easy and intuitive way to look into how your code is operating. Definitely learn debugging. Not complicated at all

Being able to pause your program exactly where you want and check out the current state is definitely a lot easier than playing a guessing game with logging statements all over your code, which most beginners end up doing anyway

casual poster
Jun 29, 2009

So casual.
Holy crap, debugging is awesome! I had to look hard to find a good resource but this one helped me the best: http://www.itk.ilstu.edu/faculty/bllim/itk168/Labs/NetBeans_DebuggingW4/NetBeans_DebuggingW4_New.htm

Btw "Carry on then" I didn't read your post until just now. THanks a lot for that. I wished I had checked into this thread this morning!

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.
Yeah debugging is loving huge. I'm almost surprised people don't teach that FIRST, before anything else, because it really is that useful.

My only guess as to why they don't is maybe out of fear that you'd end up using the debugger as a crutch, testing out code brute-force style without learning what it does or how to anticipate or interpret what the compiler will do with a given bit of code. Which is important, but especially when you're new learning all the gotchas of the language can take time and watching them happen in the debugger is probably a more intuitive way to learn anyways.

The alternative is a bunch of new programmers who just fill their code with

System.out.println("Value of X: " + x);

Every other line. Like what's the point in that when you can just use a debugger?

22 Eargesplitten
Oct 10, 2010



If I want to put an application up as a .jar, what's the most user-friendly way to have it set up? In Eclipse, the options are Extract required libraries into JAR, Package required libraries into JAR, and Copy required libraries into sub folder next to JAR. From what I googled, I'm thinking Extract would keep it simplest?

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

Zaphod42 posted:

Yeah debugging is loving huge. I'm almost surprised people don't teach that FIRST, before anything else, because it really is that useful.

My only guess as to why they don't is maybe out of fear that you'd end up using the debugger as a crutch, testing out code brute-force style without learning what it does or how to anticipate or interpret what the compiler will do with a given bit of code. Which is important, but especially when you're new learning all the gotchas of the language can take time and watching them happen in the debugger is probably a more intuitive way to learn anyways.

The alternative is a bunch of new programmers who just fill their code with

System.out.println("Value of X: " + x);

Every other line. Like what's the point in that when you can just use a debugger?

Much like teaching source control, it's likely a case of instructors viewing it as outside the scope of their particular course/the degree (computer science isn't programming etc etc) and the instructors themselves not using/being familiar with it.

Zaphod42
Sep 13, 2012

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

22 Eargesplitten posted:

If I want to put an application up as a .jar, what's the most user-friendly way to have it set up? In Eclipse, the options are Extract required libraries into JAR, Package required libraries into JAR, and Copy required libraries into sub folder next to JAR. From what I googled, I'm thinking Extract would keep it simplest?

Package required libraries is AFAIK the best standard. That includes all the libraries into the JAR, but leaves them zipped in their own JARs. Extract would have all those packages unzipped as loose class files in folders which is just messier IMO. They should both work? Sub-folder next to JAR is the messiest by far as it means you have more files to distribute and they have to be in the right location.

carry on then posted:

Much like teaching source control, it's likely a case of instructors viewing it as outside the scope of their particular course/the degree (computer science isn't programming etc etc) and the instructors themselves not using/being familiar with it.

Yeah you're right about that. Not teaching source control for years in academia is ridiculous but happens left and right. And then suddenly you have a course on project management and you have to use source control and everybody resists change.

Kuule hain nussivan
Nov 27, 2008

Can anyone recommend a book about the best practices of unit testing? I think that's one point where I definitely need to improve, particularly regarding setting up parameters and such. Java, and especially JUnit, are preferred.

22 Eargesplitten
Oct 10, 2010



Yeah, come to think of it my university courses never taught the debugger. My CC classes were much more practical, and the teacher showed us how to use the debugger in both Eclipse and Visual Studio.

Thanks, I'll package the files with the .jar. When I was in school we either submitted all of the files in a .zip or put together a .jar from the Linux terminal.

E: packaged it up in its own folder since I've got a separate repository for the application. It only created the .jar, it didn't send any other files there. When I try to open it, nothing happens. Did I need to bring some other files over? I created it as a "Runnable Jar" if that makes a difference.

E2: Turns out I needed to include the .txt files that the application reads information in from.

22 Eargesplitten fucked around with this message at 20:57 on Feb 8, 2016

HFX
Nov 29, 2004

Zaphod42 posted:

Yeah debugging is loving huge. I'm almost surprised people don't teach that FIRST, before anything else, because it really is that useful.

My only guess as to why they don't is maybe out of fear that you'd end up using the debugger as a crutch, testing out code brute-force style without learning what it does or how to anticipate or interpret what the compiler will do with a given bit of code. Which is important, but especially when you're new learning all the gotchas of the language can take time and watching them happen in the debugger is probably a more intuitive way to learn anyways.

The alternative is a bunch of new programmers who just fill their code with

System.out.println("Value of X: " + x);

Every other line. Like what's the point in that when you can just use a debugger?

I still end up writing plenty of the equivalent of printlines 10 years into my career. They are highly useful in helping to tract down issues which are not easily reproducible. Debuggers are great but the aren't always the most appropriate tool.

HFX fucked around with this message at 21:51 on Feb 8, 2016

Zaphod42
Sep 13, 2012

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

HFX posted:

I still end up writing plenty of the equivalent of printlines 10 years into my career. They are highly useful in helping to tract down issues which are not easily reproducible. Debuggers are great but the aren't always the most appropriate tool.

Oh sure, same here. But its pretty obvious when somebody is using println()s as a crutch for not knowing what debugging is.

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

Anyone got any reckons about using Optionals versus @Nullable/@NonNull annotations for wrangling them nulls? I've been using annotations and they're neat, nice and simple and the linter lets you know when you need to handle a potential null value. Are Optionals preferred since they don't rely on linting? Any other good reasons to use them?

HFX
Nov 29, 2004

baka kaba posted:

Anyone got any reckons about using Optionals versus @Nullable/@NonNull annotations for wrangling them nulls? I've been using annotations and they're neat, nice and simple and the linter lets you know when you need to handle a potential null value. Are Optionals preferred since they don't rely on linting? Any other good reasons to use them?

They require Java 8 where as @Nullable / @NonNull can work back a few versions. I suppose both can be made to work reasonably.

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

Well Guava has them (I'm not on the magic of Java 8) which I'm playing around with, and that's why I'm wondering if I should start using them

speng31b
May 8, 2010

Pulling in Guava as a dependency just for Optionals (or even any of their other nice stuff) is usually the limiting factor moreso than anything else, especially for those of us on Android where dex limits are a huge pain in the rear end even with multidex support being much improved.

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

Well I mean just assuming they're there, since a lot of people add Guava as a dependency in general. Just looking for a general comparison here!

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
We aggressively use Optionals, and we're very happy with it. It drastically cuts down on NPE's, and clarifies intent in interfaces.

Also Java 8 is beautiful and nothing hurts. Except type erasure. gently caress that guy.

HFX
Nov 29, 2004

Gravity Pike posted:

We aggressively use Optionals, and we're very happy with it. It drastically cuts down on NPE's, and clarifies intent in interfaces.

Also Java 8 is beautiful and nothing hurts. Except type erasure. gently caress that guy.

He's going to be around forever due to removing him would break a lot of old code and make some code next to impossible to do.

Sistergodiva
Jan 3, 2006

I'm like you,
I have no shame.

Ok, so suddenly my project won't compile at all. Looking through my github stuff it doesn't seem like I have changed anything that could have caused this.

code:
Exception in thread "main" java.lang.NoClassDefFoundError: com/mygdx/casa/Casa
First I had this.

But now suddenly

code:
D:\casa\core\src\com\mygdx\casa\WorldMap.java
Error:(65, 5) java: cannot find symbol
  symbol:   class Entity
  location: class com.mygdx.casa.WorldMap
Error:(67, 10) java: cannot find symbol
  symbol:   class Entity
  location: class com.mygdx.casa.WorldMap
Error:(134, 20) java: cannot find symbol
  symbol:   class Entity
  location: class com.mygdx.casa.WorldMap
And other one of my files can't find my Enemy.java class apparently.

From what I can see every one of these have a proper package header and stuff, so this is just plain weird.

Any idea what it could be?

Edit: apparently moving them to a sub-directory and back again in IDEA fixed it. Weird.

Sistergodiva fucked around with this message at 12:29 on Feb 12, 2016

Carbon dioxide
Oct 9, 2012

Gravity Pike posted:

We aggressively use Optionals, and we're very happy with it. It drastically cuts down on NPE's, and clarifies intent in interfaces.

Also Java 8 is beautiful and nothing hurts. Except type erasure. gently caress that guy.

One of these days I'll get my head 'round lambda operators.

CPColin
Sep 9, 2003

Big ol' smile.

Gravity Pike posted:

We aggressively use Optionals, and we're very happy with it. It drastically cuts down on NPE's, and clarifies intent in interfaces.

Also Java 8 is beautiful and nothing hurts. Except type erasure. gently caress that guy.

Speaking of type erasure, you wouldn't be able to do this with Optional:

code:
public void setWhatever(Optional<ClassA> value) { ... }

public void setWhatever(Optional<ClassB> value) { ... }
but you would be able to do it with annotations:

code:
public void setWhatever(@Nullable ClassA value) { ... }

public void setWhatever(@Nullable ClassB value) { ... }
I really wish java.lang would pick up the null annotations and rt.jar would get annotated, so Eclipse could stop complaining about everything so much.

Zaphod42
Sep 13, 2012

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

Carbon dioxide posted:

One of these days I'll get my head 'round lambda operators.

Lambdas are pretty cool, I learned them many years back for C# and I was glad they were added to Java.

They're pretty much just mixing in some declarative programming / functional programming in the middle of java's otherwise imperative programming style.

Instead of writing

code:
class CheckPersonEligibleForSelectiveService implements CheckPerson {
    public boolean test(Person p) {
        return p.gender == Person.Sex.MALE &&
            p.getAge() >= 18 &&
            p.getAge() <= 25;
    }
}

public static void printPersonsWithPredicate(
    List<Person> roster, Predicate<Person> tester) {
    for (Person p : roster) {
        if (tester.test(p)) {
            p.printPerson();
        }
    }
}
Such that you iterate through and call the method on each, instead

code:
printPersons(
    roster,
    (Person p) -> p.getGender() == Person.Sex.MALE
        && p.getAge() >= 18
        && p.getAge() <= 25
);
Which will automatically iterate through and filter out the persons p which match the criteria specified.

The '->' arrow character is translated as "such that". (Person P such that p.getGender() == Person.Sex.MALE)

Its like combining a for-each with an if() condition.

You can also use them as a sort of function pointer, where you can pass a lambda operator as a parameter, which you can't otherwise do in Java.

code:
public class Calculator {
  
    interface IntegerMath {
        int operation(int a, int b);   
    }
  
    public int operateBinary(int a, int b, IntegerMath op) {
        return op.operation(a, b);
    }
 
    public static void main(String... args) {
    
        Calculator myApp = new Calculator();
        IntegerMath addition = (a, b) -> a + b;
        IntegerMath subtraction = (a, b) -> a - b;
        System.out.println("40 + 2 = " +
            myApp.operateBinary(40, 2, addition));
        System.out.println("20 - 10 = " +
            myApp.operateBinary(20, 10, subtraction));    
    }
}

Zaphod42 fucked around with this message at 21:43 on Feb 12, 2016

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

They really clean up ActionListeners too.

Java code:
JButton button = new JButton("your posting is bad");
button.addActionListener(e -> {
    JOptionPane.showMessageDialog(this, "yospos bithc", "219", JOptionPane.INFORMATION_MESSAGE);
});
vs

Java code:
JButton button = new JButton("your posting is bad");
button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        JOptionPane.showMessageDialog(this, "yospos bithc", "219", JOptionPane.INFORMATION_MESSAGE);
    }
});

The Laplace Demon
Jul 23, 2009

"Oh dear! Oh dear! Heisenberg is a douche!"

CPColin posted:

Speaking of type erasure, you wouldn't be able to do this with Optional:

code:
public void setWhatever(Optional<ClassA> value) { ... }

public void setWhatever(Optional<ClassB> value) { ... }
but you would be able to do it with annotations:

code:
public void setWhatever(@Nullable ClassA value) { ... }

public void setWhatever(@Nullable ClassB value) { ... }
I really wish java.lang would pick up the null annotations and rt.jar would get annotated, so Eclipse could stop complaining about everything so much.

code:
class Foo {
     public void setWhatever(ClassA value) { ... }
     public void setWhatever(ClassB value) { ... }
}

final Foo foo = ...;
optionalA.ifPresent(foo::setWhatever);
optionalB.ifPresent(foo::setWhatever);
:smugdog:

CPColin
Sep 9, 2003

Big ol' smile.
And what if setWhatever() needs to do something different when you pass it a null value?

The Laplace Demon
Jul 23, 2009

"Oh dear! Oh dear! Heisenberg is a douche!"

CPColin posted:

And what if setWhatever() needs to do something different when you pass it a null value?

If it's a setter on a POJO, why not let the constructor initialize it to a default value instead of relying on somebody remembering to call setWhatever(null);? That sounds absurdly contrived.

CPColin
Sep 9, 2003

Big ol' smile.
Assume it's not a setter on a POJO, despite the name I arbitrarily gave it. Like, maybe these processValue() methods have to do something special, like display an error, when you pass in an empty Optional:

code:
public abstract void processValue(Optional<ClassA> classA);

public abstract void processValue(Optional<ClassB> classB);
You can't do this, because of type erasure:

code:
public void someCodeSomewhere()
{
   Optional<ClassA> classA = loadSomeValueFromSomewhereMaybe();

   processValue(classA);

   Optional<ClassB> classB = loadSomeValueFromSomewhereElseMaybe();

   processValue(classB);
}
You would have to change processValue() to make the signatures different:

code:
public abstract void processValue(ClassA classA);

public abstract void processValue(ClassB classB);
and then you'd have to unwrap the Optional values before you passed them, which kind of defeats the purpose. Now you need @Nullable on the method parameters anyway and ugh Oracle just extend the JVM spec already!

The Laplace Demon
Jul 23, 2009

"Oh dear! Oh dear! Heisenberg is a douche!"

CPColin posted:

Assume it's not a setter on a POJO, despite the name I arbitrarily gave it. Like, maybe these processValue() methods have to do something special, like display an error, when you pass in an empty Optional:

code:
public abstract void processValue(Optional<ClassA> classA);

public abstract void processValue(Optional<ClassB> classB);
You can't do this, because of type erasure:

code:
public void someCodeSomewhere()
{
   Optional<ClassA> classA = loadSomeValueFromSomewhereMaybe();

   processValue(classA);

   Optional<ClassB> classB = loadSomeValueFromSomewhereElseMaybe();

   processValue(classB);
}
You would have to change processValue() to make the signatures different:

code:
public abstract void processValue(ClassA classA);

public abstract void processValue(ClassB classB);
and then you'd have to unwrap the Optional values before you passed them, which kind of defeats the purpose. Now you need @Nullable on the method parameters anyway and ugh Oracle just extend the JVM spec already!

Yes, and I still say you shouldn't be doing that in the first place. That said, if you're stuck using legacy code with bizarre null semantics:
code:
abstract class Foo {
     public abstract void processValue(@Nullable ClassA value);
     public abstract void processValue(@Nullable ClassB value);
}

final Foo foo = ...;
foo.processValue(optionalA.orElse(null));
foo.processValue(optionalB.orElse(null));

The Laplace Demon fucked around with this message at 01:42 on Feb 13, 2016

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
Guava's optionals have a nice orNull() method.

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
Java 8's have an .orElse(T val), so when our Optionals finally end up at the database layer, we have a lot of someValue.orElse(null) floating around our DAO code.

Where lamdas really shine, in my opinion, is in the new CompletableFuture stuff. Lamdas make it especially convenient to chain things together. We've built up a generic "Retrier" class that lets us try things that might fail or timeout, essentially turning blocking code into asynchronous code:

Java code:
CompletableFuture<ExternalObject> externalFuture = retrier.handle(() -> externalService.getThing());

public CompletableFuture<NotificationStatus> sendNotification(final UUID thingId) {
    return retrier.handle(() -> externalService.getThing(thingId))
        .thenCompose(thing -> retrier.handle(() -> notificationHandler.sendNotifications(thing)));
        .exceptionally(e -> log.warn("Failed to get thing {} and then notify about it", thingId, e));
}

SmellsLikeToast
Dec 30, 2005

A GREATER MAN THAN I DESERVE
I need to make a method with a String parameter that compares that String to the (String)name parameter of all objects within an ArrayList. If the names match, I then have to set the parameters of an existing (currently null) variable equal to the object with the matching name in the ArrayList. I have a getName() method for the objects in the ArrayList, but no setter as the name variable is final. I have a for loop written with an if statement inside of that, but it isn't panning out. Happy to provide any missing info. Thanks for any help.

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

What do you mean "isn't panning out"? Be specific: what are you expecting to happen, what is happening (an exception? wrong/no output? something else?) What code have you written so far?

CPColin
Sep 9, 2003

Big ol' smile.
Also, do you get to use Java 8 features?

SmellsLikeToast
Dec 30, 2005

A GREATER MAN THAN I DESERVE

carry on then posted:

What do you mean "isn't panning out"? Be specific: what are you expecting to happen, what is happening (an exception? wrong/no output? something else?) What code have you written so far?

The variable (selection) is initialized to null, and remaining that way because what I'm writing isn't actually changing it. I want the selection variable to essentially become a copy of an existing object within the ArrayList within makeSelection if the name parameter passed to makeSelection matches the name parameter of an existing item in the ArrayList. I have JUnit tests for a few cases; if the item is null, name is equal to NO_ITEM_SELECTION(passes), if the item name being input doesn't match an existing item name from the ArrayList, name is equal to NO_ITEM_SELECTION (passes), and if the name passed in matches that of an item already in the list, then selection.getName() is the same as the input. Using Eclipse Mars 4.5.0. Here's what I have:

code:
public class Controller {
	public static final String NO_ITEM_SELECTION = "None";

	private ArrayList<Item> items;		
	private Item selection;

public Controller() {
		this.selection = null;
		this.items = new ArrayList<Item>();	

public String getSelection() {

		String tempName = "nomatter";
		if (this.selection == null) {
			tempName = Controller.NO_ITEM_SELECTION;
		} else {
			tempName = selection.getName();
		}
		return tempName;

	}	

	public Item makeSelection(String itemName) {

		for (Item anItem : items) {
			Item currentItem = null;
			if (itemName == item.getName()) {
				currentItem = item;
			}
			this.selection = currentItem;
		}
		return selection;

		}
}
I know that makeSelection doesn't need to return anything, that was just trial and error.

SmellsLikeToast fucked around with this message at 02:04 on Feb 15, 2016

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

SmellsLikeToast posted:

code:
if (itemName == item.getName()) {
	currentItem = item;
}

Ah, there we go.I'll just go ahead and say this right out because I know how unintuitive this is until you "get" it, which will come with time. == compares two variables for equality, and when the variables are Objects instead of primitives, the value of the variables is the reference to the object, not its contents. In essence, here you are checking if the name is the exact same object rather than if the two Objects are both Strings that contain the exact same characters in the exact same order, and of course that's coming up false. You'll want to use the equals() method on the String class to compare the two based on contents:

https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equals(java.lang.Object)

e to add: it was common back when I was tutoring that people would say "but it worked for me before." Occasionally == does appear to compare contents because people will do something like itemName = "my item" and then later on do something like (if itemName == "my item") and it'll seem to work. What actually happens is that for speed, the Java virtual machine notices hardcoded strings directly in your code, and creates one object with that string and shares it to all the places in your code where you used that String; this is called String interning. So in the first line you stored the single, interned String object representing "my item" and in the second statement, you compared against that very same object and it would come back as true despite not being a real comparison of the contents of the two strings.

carry on then fucked around with this message at 02:44 on Feb 15, 2016

SmellsLikeToast
Dec 30, 2005

A GREATER MAN THAN I DESERVE
Thanks. Somewhere in the back of my mind I knew that. Makes sense. I still can't manage to get the selection variable to take on the other object's parameters. I was thinking using the currentItem variable then setting selection equal to that would do it, but it doesn't seem to be. If it helps any, here's the JUnit test for the makeSelection method I can't get to pass.

code:
	@Test
	public void returnsCorrectNameIfItemExists() {
		this.controller.makeSelection("Item Name");
		assertEquals("Item Name", this.controller.getSelection());

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

SmellsLikeToast posted:

Thanks. Somewhere in the back of my mind I knew that. Makes sense. I still can't manage to get the selection variable to take on the other object's parameters. I was thinking using the currentItem variable then setting selection equal to that would do it, but it doesn't seem to be. If it helps any, here's the JUnit test for the makeSelection method I can't get to pass.

code:
	@Test
	public void returnsCorrectNameIfItemExists() {
		this.controller.makeSelection("Item Name");
		assertEquals("Item Name", this.controller.getSelection());
First, when it says currentItem = item, shouldn't that be anItem? I'd expect a compiler error here.

There's another logic error in your loop. Let's say the item that matches is second from last, so at the end of that iteration, selection is equal to the Item you're looking for. Now do the last iteration with an item that isn't what you're looking for. Keep track of the value of currentItem and selection. Can you see why selection is guaranteed to be null unless the matching item is also the last item?

You may want to try out the debugger for this. I'll paste in links to a post I made showing how to use the debugger a long time ago in the thread.

carry on then posted:

Here's a post I wrote on how to use the debugger in Netbeans, with screenshots: http://forums.somethingawful.com/showthread.php?threadid=2780384&pagenumber=192&perpage=40#post441859581

e: and if you want to get really crazy, you can do what's called remote debugging, and not even have to be on the same computer as the program while you debug: http://forums.somethingawful.com/showthread.php?threadid=2780384&pagenumber=203&perpage=40#post449656064

Probably not useful to a beginner, but you can see the lengths to which programmers will go t omake their debugger available. It's really useful.

SmellsLikeToast
Dec 30, 2005

A GREATER MAN THAN I DESERVE

carry on then posted:

There's another logic error in your loop. Let's say the item that matches is second from last, so at the end of that iteration, selection is equal to the Item you're looking for. Now do the last iteration with an item that isn't what you're looking for. Keep track of the value of currentItem and selection. Can you see why selection is guaranteed to be null unless the matching item is also the last item?

Yes, I see that. I'm guessing I need to do something with the index of the object that has the same name, but I don't know enough yet to know how to do that. Then again, could I just halt the loop at that point if those parameters match? In case it's not obvious, this is for an assignment. The problem I keep running into is the professors at my school take self-instruction to a whole new level. They basically just lecture on theory and logic then tell you what they want and that's about it. I usually don't have a problem with the logic end (as far as HOW it should work is concerned), I just don't have the knowledge of the API I need. I check stackoverflow and the Java API for every problem I run into but haven't been able to find what I need for this particular one. I appreciate your help.

Adbot
ADBOT LOVES YOU

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

SmellsLikeToast posted:

Yes, I see that. I'm guessing I need to do something with the index of the object that has the same name, but I don't know enough yet to know how to do that. Then again, could I just halt the loop at that point if those parameters match? In case it's not obvious, this is for an assignment. The problem I keep running into is the professors at my school take self-instruction to a whole new level. They basically just lecture on theory and logic then tell you what they want and that's about it. I usually don't have a problem with the logic end (as far as HOW it should work is concerned), I just don't have the knowledge of the API I need. I check stackoverflow and the Java API for every problem I run into but haven't been able to find what I need for this particular one. I appreciate your help.

You're closer than you think. If you want selection to be set only when the currentitem matches the one you're looking for, when should you be setting selection?

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