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
fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Also, always use curly braces, even for 1 line statements. And make sure your indentation is consistent, it makes things a lot easier to read and debug.

Adbot
ADBOT LOVES 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


I've wrestled with this a bit over the last couple of days (this was pretty decent for covering things), and I'm still having trouble - can someone tell me if it's even possible to do what I'm trying? I get the feeling I'm using things the wrong way.

To recap:
  • I have a superclass with some abstract methods (and some not, which is why it's not an interface) that all subclasses have to implement
  • One of the methods takes a unique Options object for each subclass, and only that object, so they don't actually implement the same method signature
  • I'd like the unique object to be created from an inner class, for organisation and also so I can just refer to it as Subclass.Options
  • So the abstract method signature I'm thinking of is really method(Options options), in the scope of each class that implements it. I want each class to accept an instance of its own Options class

Nothing I've tried with generics has worked so far - I thought the first suggestion got the classes sorted out, but they didn't actually work the way they were supposed to. Eclipse was even throwing out what looked like a weird recursion error, which I assume was something like it going Controller<Controller<Controller<?>.Options>.Options>.Options and so on. So:

Am I making my life hell with inner classes?

Can I even use generics to make an abstract method signature, where the implementing classes' signatures are always more restrictive?

I could just have the method accept everything and do an internal type check and save myself the headaches, but I was wondering if there was a more 'elegant' way to do things ('elegant' in quotes after a horrorshow of angle brackets)

FateFree
Nov 14, 2003

Can't you just have an AbstractOptions class that your base method uses, and have all your subclasses have inner classes that extend it? Subclass.Options extends AbstractOptions?

Otherwise you'll just have a base class that has generics, BaseClass<? extends AbstractOptions>, and your subclasses SubClass<SubClass.Options>, and Subclass.Options extends AbstractOptions.

This will let you do things like SubClass.Options options = subClass.getOptions();


baka kaba posted:

I could just have the method accept everything and do an internal type check and save myself the headaches

This will cause the headaches, not save them!

FateFree fucked around with this message at 21:14 on Jan 22, 2014

Sedro
Dec 31, 2008
Looking back at the earlier code, you probably need to make the inner classes static.
Java code:
public abstract class BaseClass<T extends BaseClass.Options> {
    public abstract void method(T options);
    public static class Options {}
}

public class SubClass extends BaseClass<SubClass.Options> {
    @Override public void method(SubClass.Options options) {
        System.out.println(options);
    }

    public static class Options extends BaseClass.Options {
        @Override public String toString() {
            return "I'm a subclass options!";
        }
    }
}

SubClass sub = new SubClass();
sub.method(new SubClass.Options()); // I'm a subclass options!

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

FateFree posted:

Can't you just have an AbstractOptions class that your base method uses, and have all your subclasses have inner classes that extend it? Subclass.Options extends AbstractOptions?

Otherwise you'll just have a base class that has generics, BaseClass<? extends AbstractOptions>, and your subclasses SubClass<SubClass.Options>, and Subclass.Options extends AbstractOptions.

This will let you do things like SubClass.Options options = subClass.getOptions();


That's along the lines of what I was trying, I just need every class implementing that method to require a specific subclass of AbstractOptions, whereas the abstract signature requires any subclass of AbstractOptions. It's basically a different signature, but it's logically fixed and consistent, so I thought I might be able to express that relationship with generics.

The trouble (I think) I've been running into is having a generic class like Subclass<Subclass.Options>, which seems to work fine for the definitions - but when it comes to using it that inner Subclass is considered a raw type, and there are obviously complaints. I'll have to take a look at exactly what is going wrong, but I'm just worried that it's a sign that I shouldn't even be trying to do this, at least not this way


FateFree posted:

This will cause the headaches, not save them!

No see I can just fall to the defaults and log an error if I like, it'll be totally sweet, let me gooooo

Sedro posted:

Looking back at the earlier code, you probably need to make the inner classes static.

Now this is interesting. I'm getting a good feeling about this one

baka kaba fucked around with this message at 21:30 on Jan 22, 2014

FateFree
Nov 14, 2003

baka kaba posted:

The trouble (I think) I've been running into is having a generic class like Subclass<Subclass.Options>, which seems to work fine for the definitions - but when it comes to using it that inner Subclass is considered a raw type, and there are obviously complaints. I'll have to take a look at exactly what is going wrong, but I'm just worried that it's a sign that I shouldn't even be trying to do this, at least not this way

Generics in Java are notoriously horrible, don't take any warnings as a sign you are doing the wrong thing. In some cases, suppressing warnings are the only thing you can do. But in your case, I don't see how it wouldn't work..if its complaining about raw types that means you arent declaring SubClass<Subclass.Options> everywhere you use it.

Declaring the inner classes static is essentially the same thing as storing them in a separate class file.

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
I can't seem to get KeyEvents on a fullscreen exclusive mode JFrame. I spent some time cutting my program down to a small reproduction case and I'm left with this:

code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Simplified {

	public static void main(String[] args) {
		Game game = new Game();
		View view = new View();
		view.setFocusable(true);
		view.addKeyListener(game);

		JFrame frame = new JFrame();
		frame.setUndecorated(true);
		frame.getContentPane().add(view);
		frame.setFocusable(true);
		frame.addKeyListener(game);
		frame.pack();
		frame.setVisible(true);

		GraphicsEnvironment.
			getLocalGraphicsEnvironment().
			getDefaultScreenDevice().
			setFullScreenWindow(frame);
	}
}

class Game implements KeyListener {
	public void keyTyped   (KeyEvent k) { System.out.println("key typed"); }
	public void keyPressed (KeyEvent k) { System.out.println("key pressed"); }
	public void keyReleased(KeyEvent k) {
		System.out.println("key released");
		if (k.getKeyCode() == KeyEvent.VK_ESCAPE) { System.exit(0); }
	}
}

class View extends JPanel {
	public void paint(Graphics g) {
		g.setColor(Color.BLACK);
		g.fillRect(0, 0, getWidth(), getHeight());
		g.setColor(Color.RED);
		g.drawRect(0, 0, getWidth()-1, getHeight()-1);
	}
}
Note that I add my KeyListener to both the JPanel and the JFrame for good measure and make both focusable.

When I try this on my laptop running OSX 10.7.5 and Java 1.6.0_65 it works perfectly.
On my desktop running OSX 10.8.5 and Java 1.7.0_25 it doesn't respond to any keypresses.

Any ideas? Am I exercising some kind of undefined behavior in the way I'm doing this?

Internet Janitor fucked around with this message at 23:33 on Jan 22, 2014

Drunkenboxer
Oct 3, 2007

eh?
Just wanted to say thanks for all the advice, my simple program works like a charm now.

I've always thought of myself as a fairly logical person, nothing like programming to make you realize just how little you know!

ivantod
Mar 27, 2010

Mahalo, fuckers.

FateFree posted:

Generics in Java are notoriously horrible, don't take any warnings as a sign you are doing the wrong thing. In some cases, suppressing warnings are the only thing you can do. But in your case, I don't see how it wouldn't work..if its complaining about raw types that means you arent declaring SubClass<Subclass.Options> everywhere you use it.

Unfortunately, suppressing the warnings partially defeats the purpose of using generics (such as it is) in the first place. Because you are only guaranteed no class cast exceptions at runtime if there are no generics-related warnings during compilation. Note that I am not saying here that generics in Java actually make sense, just stating simple facts of life. :v:

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."
What's the best way to preselest items in a JList if I have one large Collection and another one with elements selected from the first? That is,

Collection one: {item1, item2, item3, item4}; Collection two: {item2, item3};

JList:
-----
item1
item2
item3
item4
-----

And also maybe what is the best type of Collection to use here? Right now I'm just using the Collection interface in the dialog I'm doing (with TreeSet underneath because I thought it would be neat to have unique sorted elements by default). And maybe hints as to how to make the dialog not crap, the dialog used for editing a column in a table, because I want to have multiple choice in the cells. Please ask me clarifying questions!

Volguus
Mar 3, 2009

supermikhail posted:

What's the best way to preselest items in a JList if I have one large Collection and another one with elements selected from the first? That is,

Collection one: {item1, item2, item3, item4}; Collection two: {item2, item3};

JList:
-----
item1
item2
item3
item4
-----

And also maybe what is the best type of Collection to use here? Right now I'm just using the Collection interface in the dialog I'm doing (with TreeSet underneath because I thought it would be neat to have unique sorted elements by default). And maybe hints as to how to make the dialog not crap, the dialog used for editing a column in a table, because I want to have multiple choice in the cells. Please ask me clarifying questions!

Make the renderer and editor for the jlist contain a checkbox. Checked if item is selected, unchecked otherwise. Making the label bold may not be a bad idea too. The model should contain item+selected flag. If you only need a collection, whatever works. SortedSet, TreeSet are all fine. It comes down to what are you using the Collection for. And if you want to do fast searches and you do that a lot, then TreeSet surely is better ( provides guaranteed log(n) time cost for the basic operations (add, remove and contains)). But if you don't do searches, just mainly add/remove then maybe a linked list would be better.

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."
Okay, but now I'm worried that the custom (:)) is to move to a table when you need to add a checkbox (e: or maybe I'm imagining). Also, the primary functions of this program mostly involve "contains", so that's going to be my justification for TreeSet?

Volguus
Mar 3, 2009

supermikhail posted:

Okay, but now I'm worried that the custom (:)) is to move to a table when you need to add a checkbox (e: or maybe I'm imagining). Also, the primary functions of this program mostly involve "contains", so that's going to be my justification for TreeSet?

You can move to a jtable, sure. Then you'd have to add code to remove the jtableheader when you put the table in a jscrollpane (if you want to). And jtable consumes more memory than a jlist. But it is more powerful, yes. Essentially, is up to you and how you like your component to look and behave. Both approaches are fine, both have pros and cons. As far as i know, there is no such thing as: "if you want to do X you gotta go with Y". If you want to later on have other columns in your list, yes, then go with jtable.

Regarding collections: If you do "contains" most of the time, sure, go with TreeSet. You can also look at maps, would that help you more? HashMap has "constant-time performance for the basic operations (get and put)" for example.

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."
Well, looks like this http://stackoverflow.com/questions/17951886/cannot-add-checkbox-to-the-jlist is where I got my info on lists and tables. JLists really don't have the setCellEditor method. :eng101: And I'll go with TreeSet - its sorted property just appeals to me (and it's apparently one of the only two out-of-the-box implementations of SortedSet, the other being synchronized).

Thanks for your help!

Kilson
Jan 16, 2003

I EAT LITTLE CHILDREN FOR BREAKFAST !!11!!1!!!!111!
I have a problem with Spring and AOP. The aspects are getting applied twice, when they should only be getting applied once. I've stripped out everything I can (Transactional annotation support, etc.), to reduce this problem to its smallest possible representation.

This is in my Spring configuration.
code:

<bean id="aspectLog" class="com.xyz.aspects.AspectLogger"/>

<aop:config>
  <aop:aspect ref="aspectLog" id="loggingAspect">
    <aop:after method="logAspect" pointcut="@annotation(com.xyz.aspects.LogAspect)"/>
  </aop:aspect>
</aop:config>
The logging class:
code:
public class AspectLogger {

  private static final Logger log = Logger.getLogger(AspectLogger.class);

  private void logAspect(JoinPoint joinPoint) {
    log.info("KIND: " + joinPoint.getKind()); //
    log.info("TARGET: " + joinPoint.getTarget());
    log.info(joinPoint.toShortString());
  }
}
An example of the annotated method that the aspect applies to:
code:
@LogAspect
public int update(IpRange range) {
  return mapper.update(range);
}
I have verified that the above method is only being called once. Yet the output looks like this:

Returning cached instance of singleton bean 'aspectLog'
KIND: method-execution
TARGET: com.xyz.db.dao.IpRangeDao@3ed53703
execution(IpRangeDao.update(..))
Returning cached instance of singleton bean 'aspectLog'
KIND: method-execution
TARGET: com.xyz.db.dao.IpRangeDao@3ed53703
execution(IpRangeDao.update(..))

As you can see, it's somehow applying the pointcut twice. It doesn't appear to be caused by the difference between method call and method execution (as is a common cause of this problem). The target class does get instantiated twice (once as itself, then it's proxied by CGLIB so that AOP can be applied), but that's normal. Plus, the target objects are identical. I don't see how that could be the reason this happens, but I can't think of anything else.

Is there some other reason that annotations could be applied more than once? How can I prevent it?

Kilson fucked around with this message at 23:41 on Jan 27, 2014

Volguus
Mar 3, 2009

Kilson posted:

words....

I just made a small console spring app to test this and, as expected, it works as it should. The pointcut only gets called once. But, if i made 2 different context.xml files, which double defined the "loggingAspect" and i loaded them, i got your described behaviour.

Example context.xml:
code:
    <bean id="myaspect" class="test_spring.AspectLogger"/>
    <bean id="mybean" class="test_spring.TestBean"/>
    

    <aop:config>
        <aop:aspect ref="myaspect" id="logaspect">
            <aop:after method="logAspect" pointcut="@annotation(test_spring.LogAspect)"/>
        </aop:aspect>
    </aop:config>
And duplicate context1.xml:
code:
    <aop:config>
        <aop:aspect ref="myaspect" id="logaspect">
            <aop:after method="logAspect" pointcut="@annotation(test_spring.LogAspect)"/>
        </aop:aspect>
    </aop:config>
And now load them and call the bean method:
code:
ApplicationContext context = new ClassPathXmlApplicationContext("/context.xml","/context1.xml");
TestBean logger1 = context.getBean(TestBean.class);
logger1.someMethod();
I get what you got:

test bean ctor
test bean ctor
test bean : some method
KIND: method-execution
TARGET: test_spring.TestBean@6a3b02d8
execution(TestBean.someMethod())
KIND: method-execution
TARGET: test_spring.TestBean@6a3b02d8
execution(TestBean.someMethod())

Kilson
Jan 16, 2003

I EAT LITTLE CHILDREN FOR BREAKFAST !!11!!1!!!!111!

rhag posted:

I just made a small console spring app to test this and, as expected, it works as it should. The pointcut only gets called once. But, if i made 2 different context.xml files, which double defined the "loggingAspect" and i loaded them, i got your described behaviour.

This is inside an application deployed in a J2EE container, and the aspect is definitely defined only once. However, we do have a somewhat tangled chain of context imports, and I wonder if that's somehow causing it to get applied twice because it's imported twice. Normally with beans that doesn't really matter, but in this case it might be different? Anyway, you've given me something to look into, so thanks.

edit: I just verified that it is indeed the problem to import an aspect definition twice, even though it has an ID, so you'd think it would just overwrite itself like any other bean rather actually applying the aspect twice. Well, this sucks.

Kilson fucked around with this message at 16:10 on Jan 28, 2014

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."
So I've GUI-built (Netbeans) a
code:
                           split-pane containing 
                         /                        \
         panel containing                          scrollpane containing
           /      \                                        |
        stuff    scrollpane containing              panel containing
                           |                               |
                         JList                           stuff
I've come to the conclusion that this setup may only be in some way useful with the purpose of bringing about the end of the world (when you need that last drop of enthropy), because there's no way to make it behave reasonably. Opinions?

Note: it looks pretty cool if you don't actually touch anything.

Edit: Dang it - enthropy goes up, order goes down!

supermikhail fucked around with this message at 23:06 on Jan 30, 2014

Zaphod42
Sep 13, 2012

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

supermikhail posted:

I've come to the conclusion that this setup may only be in some way useful with the purpose of bringing about the end of the world (when you need that last drop of enthropy), because there's no way to make it behave reasonably. Opinions?

You mean Entropy?

Even then... What? :wtc:

My best guess at parsing that sentence "I think this code is bad, and its only usefulness could be esoteric entropy for delaying the eventual heat death of the world because I can't get it to work; what do you think?"

I guess that's it?

What's wrong, really? Tell us more if you want real help. If you're just making a funny then okay.

There's nothing inherently absurd about that design.

Zaphod42 fucked around with this message at 22:06 on Jan 31, 2014

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."
Well... :downs:

Yes, entropy (for some reason it looked to me much better with an "h"). The idea was that my design behaves so chaotically, it would be really handy if you wanted to increase entropy just a little bit.

Basically, the problem kind of was that with everything resizable within a scrollpane, if you grow the scrollpane the contents expand, and there is no way to make them shrink, because the scrollpane just creates the scrollbars. Also I think I broke the GUI builder a bit by changing the spaces manually (as in, entering the number) too many times... Oh, yeah, it's only for horizontal resizing that it's broken, but I fixed it by turning it off.

Sagacity
May 2, 2003
Hopefully my epitaph will be funnier than my custom title.
I've been dicking around with Java recently and I ran into a weird problem.

I had defined a JUnit test that did initialization using a setup function that I annotated with @Before. I derived this test class from an abstract superclass that also had a @Before method. In the setup method in my derived class, I explicitly called the superclass' setup method. This is wrong, since JUnit will automatically do this.

However, it worked as expected on Windows, but didn't work on Ubuntu, even though I was running the same Java JDK version.

Apart from clearly being a bug on my end, what could be causing the different behavior on the different OSes? Or should I just chalk it up to 'it's undefined behavior so meh'?

Max Facetime
Apr 18, 2009

See if there is a setting in Junit which makes the tests execute in a fixed order. I'm guessing something like the order of files in a directory listing could have a visible effect. Or if two tests can run concurrently. Hard to say without knowing the circumstances, but it's quite easy to make the test results not reproducible by accident.

Volmarias
Dec 31, 2002

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

Max Facetime posted:

See if there is a setting in Junit which makes the tests execute in a fixed order. I'm guessing something like the order of files in a directory listing could have a visible effect. Or if two tests can run concurrently. Hard to say without knowing the circumstances, but it's quite easy to make the test results not reproducible by accident.

Your tests shouldn't have any order dependencies. If you have to specify the order in which they run, you're going to have a bad time.

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

Sagacity posted:

I've been dicking around with Java recently and I ran into a weird problem.

I had defined a JUnit test that did initialization using a setup function that I annotated with @Before. I derived this test class from an abstract superclass that also had a @Before method. In the setup method in my derived class, I explicitly called the superclass' setup method. This is wrong, since JUnit will automatically do this.

However, it worked as expected on Windows, but didn't work on Ubuntu, even though I was running the same Java JDK version.

Apart from clearly being a bug on my end, what could be causing the different behavior on the different OSes? Or should I just chalk it up to 'it's undefined behavior so meh'?

It is well-defined that the @Before methods of the superclass will be run before the @Before methods of any subclass; however, I have seen weird behavior if your subclass Overrides the superclass's setup method, and both are annotated @Before. ie

Java code:
public abstract class BaseTest {
  @Before
  public void setup() {
    ...
  }
}

public class MyUnitTest extends BaseTest {
  @Before
  @Override
  public void setup() {
    ...
  }
}
In these cases, I just make sure to name the child class's @Before method something different.

Gravity Pike fucked around with this message at 21:46 on Feb 1, 2014

Sagacity
May 2, 2003
Hopefully my epitaph will be funnier than my custom title.

Gravity Pike posted:

however, I have seen weird behavior if your subclass Overrides the superclass's setup method, and both are annotated @Before.
Yeah, that's exactly what the case was. Weird that it happens, but at least it's solved now :)

-Blackadder-
Jan 2, 2007

Game....Blouses.
I'm in my first cs class so this is going to be a quick really basic question.

Can logical operators (&&, ||) be used with String comparison (equals, compareTo)?

For example how would I write something like the following:

code:
while (!response.equals("y")) && (!response.equals("n"))

-Blackadder- fucked around with this message at 05:46 on Feb 2, 2014

lamentable dustman
Apr 13, 2007

🏆🏆🏆

-Blackadder- posted:

I'm in my first cs class so this is going to be a quick really basic question.

Can logical operators (&&, ||) be used with String comparison (equals, compareTo)?

For example how would I write something like the following:

code:
while (!response.equals("y")) && (!response.equals("n"))

Yes but first you need to get your parentheses correct
code:
while ( (!response.equals("y")) && (!response.equals("n")) )

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

The post above this is right, but to be sure: any statement which would evaluate to a boolean value (so, any method which returns boolean, as well as the results of expressions involving the ||, &&, ==, and != binary operators and the ! unary operator) can be used with any logical operator.

-Blackadder-
Jan 2, 2007

Game....Blouses.
:doh:

It's always the little things.

Thanks guys.

Drunkenboxer
Oct 3, 2007

eh?
Hey guys, got one more for you.

I am new to Java so this may seem simple, but my code won't compile, it basically says that every value is undefined.

I am not allowed to use any static methods except for the main

Heres the file in question

code:
//Manager class that coordinates the attack and defend programs
import java.util.Scanner;


public class Manager
{
    public static void main(String [] args)
    {
	 int uhigh = 1;
	 int umed = 1;
	 int ulow = 1;
	 int rounds = 1;
	 int block = 0;
	 int hit = 0;
	 int validinput = 0;
	 String attackhit = "none";
	 String defendhit = "none";

	Attacker att = new Attacker();
	Defender def = new Defender();
	
	new Manager().Userinput();
	att.numattack();
	while (rounds >= 0)
	//compare defend and attack values here in while loop
	//remember to add + 1 to hit and/or miss
	//
	 {
		--rounds;
		attackhit = att.attack;
		defendhit = def.defendai;
		def.setAttackhit(attackhit);
		System.out.println("Round: " + rounds +"      Attacker: " + attackhit + "      Defender: " + defendhit);
		if (attackhit == defendhit)
		    {
			block++;
		    }
		else if (attackhit != defendhit)
		    {
			hit++;
		    }
		attackpattern();
	    }    
   
    
   
   
     
	 //Get user input here
	//round input, hit proportion input
	//Send high, med, low to attacker
    }
    public void Userinput()
    {
	Scanner input = new Scanner (System.in);
	System.out.println("Please enter the number of attack rounds: ");
	rounds = input.nextInt;
	if (rounds >= 0 || rounds < 100)
	    {
		System.out.println("Rounds outside of range, rounds default to 10");
		rounds = 10;
	    }
	System.out.println("Enter the proportion of attacks going high, medium, and low.");
	System.out.println("They must sum to 100%");
	System.out.print("Enter the proportion of attacks going high: ");
	uhigh = input.nextInt;
	System.out.print("Enter the proportion of attacks going medium: ");
	umed = input.nextInt;
	System.out.print("Enter the proportion of attacks going low: ");
	ulow = input.nextInt;
	validinput = uhigh + umed + ulow;
	if (validinput != 100)
	    {
		uhigh = 33;
		umed = 34;
		ulow = 33;
	    }
	att.setHigh (uhigh);
	att.setMed (umed);
	att.setLow (ulow);
	att.setRounds(rounds);
	

     

    }
 
}
Any help would be appreciated, as well any insights into coding practices that I shouldn't be using, or should be doing.

Drunkenboxer
Oct 3, 2007

eh?
So i realized I made a bunch of syntax errors and what not.

I fixed them and got my program to compile without using any other methods but the main method, but this just seems messy and inefficient.

My original question still seems to stand, how to run a non-static method in a static method.

Just ignore the syntax errors for now

leftist heap
Feb 28, 2013

Fun Shoe
Non-static methods in Java are instance methods. You can only call them on an instance of the class for which they're defined. Therefore in order to use them from a static method (be it on the same class or a different class) you need to have an instance of that class available -- either by passing it in or creating it within the static method itself.

This code looks a lot like homework.

Drunkenboxer
Oct 3, 2007

eh?

quote:

This code looks a lot like homework.

This is a homework project, which is why I am asking for clarification and critiques as opposed to straight up answers.

Thanks for the input though.

baquerd
Jul 2, 2007

by FactsAreUseless

Drunkenboxer posted:

This is a homework project, which is why I am asking for clarification and critiques as opposed to straight up answers.

Coding style wise, get some consistent indentation and brace style for blocks (e.g. method, class, if, while). Capitalization quick rules here: http://java.about.com/od/javasyntax/a/nameconventions.htm

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

Drunkenboxer posted:

Hey guys, got one more for you.

I am new to Java so this may seem simple, but my code won't compile, it basically says that every value is undefined.

I am not allowed to use any static methods except for the main

Heres the file in question

code:
code
Any help would be appreciated, as well any insights into coding practices that I shouldn't be using, or should be doing.

I'm having a bit of trouble parsing your intentions out of this code. Do you intend for Userinput to be a method or a class? Your implementation is kind of using it as both. Methods take inputs and return a value. Classes have member variables and methods. You also look to be having some confusion surrounding scope. Variables declared within a method can only be used within that method. Userinput has no way to set (or access) the uhigh value from main.

There are a lot of good ways to solve this problem, but it kind of depends on what Java "tools" you're allowed to use. Are you allowed/expected to create other classes? Do you know about member variables? Are you allowed to access static member variables from within an instance method? (This is generally a bad idea unless you make sure that your code is thread-safe, but it might be expected in your class, as a demonstration of how it can be done.) Are you expected to create an instance of Manager within main?

Drastic Actions
Apr 7, 2009

FUCK YOU!
GET PUMPED!
Nap Ghost
So I'm getting started with Android development :toot:.

I'm looking for a good Oauth2 library to help manage authentication. In .Net land I usually use RestSharp, as it lets me roll my own API urls. Are there any libraries like it? Some people I've talked to recomended Scribe, but I'm not sure I can extend it with the APIs I want to use it with.

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."
I have need of the following clever algorithm:

There is an ArrayList of Entries, wherein each Entry has associated with it a Date which can also be null. I'd like the "oldest" entry from the list, or, if there are several entries with the same Date, a random one from them. Except that they also can belong to another Skipping Collection, in which case look for another entry unless there are only entries belonging to that Skipping Collection. Whew...

I'm thinking about sorting by Date, but how to pick a random one then, especially with nulls (which, I think, should be randomly interspersed with non-skipped entries)?

For clarity, I guess:

code:
class Entry{

    Date date;

    public Entry(){ Date = null; } //created with null, only later set to a particular date; at least right now

    public void setDate(Date date){ this.date = date; }

}

HashMap<Entry, Integer> skippedEntries; //entries are skipped for a number of "turns"

public Entry getNextEntry(ArrayList<Entry> entries){

    ?

}

lamentable dustman
Apr 13, 2007

🏆🏆🏆

Break the problem up into parts. First write the sorting algorithm you want to do. After that add in the random feature and then figure out how you will handle nulls and finally deal with the 2nd list.

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

Couldn't you implement a Comparator that compares by date, but if the dates are equal it randomly returns higher or lower? That way you can just throw a sort on there and get random ordering for the equal dates, and just step through your list. You can make all the nulls sink to one end of the list too, if that's what you want.

How many objects are you working with here? And how often does this run?

Adbot
ADBOT LOVES YOU

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."
I'm expecting around 30 entries tops.

baka kaba posted:

Couldn't you implement a Comparator that compares by date, but if the dates are equal it randomly returns higher or lower?

That's an idea. But... well, I'll have to implement both equals and compareTo, and they're either going to be inconsistent or unintuitive. But it reminds me that I can make a comparator to simplify the program, make Collections find the entry with the oldest date by min (I think)... or, yeah, sort it, then frequency (e: I now know it won't work, something else then), then get a random based on that frequency.

I get to play with so many cool toys. :downs:

Thanks for the ideas, guys (|| gals).

supermikhail fucked around with this message at 21:38 on Feb 9, 2014

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