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
Mulloy
Jan 3, 2005

I am your best friend's wife's sword student's current roommate.
I've run into a strange problem I don't seem to have a ready answer to.

For the sake of simplicity our instructor gave us a class (Keyboard) to handle file input and capturing entries from a keyboard. I've used this class before, but for some reason I can not use it and I'm not experienced enough to resolve it. Basically I get a "cannot find symbol" error when I try to compile even a small portion of it which should be functional. The Keyboard.java and Keyboard.class files are in the same directory, and I've tried both NetBeans and the command line compiler but both hate me. I've also tried using this same code as a new class in a project where the Keyboard is working properly.

Here's the Code that's giving me grief:

code:
package studentevaluation;

public class StudentEvaluation {

    public static void main(String[] args) {

        Keyboard k;
        k = new Keyboard();

        char selection;
        selection = k.readChar();

    }



}
I tried to check the classpath, path in windows, etc... as that's what most google results indicated but I'm stuck.

Adbot
ADBOT LOVES YOU

Shavnir
Apr 5, 2005

A MAN'S DREAM CAN NEVER DIE

Mulloy posted:

I've run into a strange problem I don't seem to have a ready answer to.

For the sake of simplicity our instructor gave us a class (Keyboard) to handle file input and capturing entries from a keyboard. I've used this class before, but for some reason I can not use it and I'm not experienced enough to resolve it. Basically I get a "cannot find symbol" error when I try to compile even a small portion of it which should be functional. The Keyboard.java and Keyboard.class files are in the same directory, and I've tried both NetBeans and the command line compiler but both hate me. I've also tried using this same code as a new class in a project where the Keyboard is working properly.

Here's the Code that's giving me grief:

code:
package studentevaluation;

public class StudentEvaluation {

    public static void main(String[] args) {

        Keyboard k;
        k = new Keyboard();

        char selection;
        selection = k.readChar();

    }



}
I tried to check the classpath, path in windows, etc... as that's what most google results indicated but I'm stuck.

What package is Keyboard.java in?

Mulloy
Jan 3, 2005

I am your best friend's wife's sword student's current roommate.

Shavnir posted:

What package is Keyboard.java in?

Well, you learn something new everyday, that was it. Though why I haven't run into this in any of the five previous assignments using this same file I have no idea, but I never bothered to check either, so.

Thanks!

huge sesh
Jun 9, 2008

covener posted:

applications like java don't calculate checksums for IP headers, the host network stack does. Wireshark shows you its invalid because your network card offloads it, which isn't until after wireshark sees it on the way out.

The failure to encode a space in a URI sounds surprising for java. Can you illustrate with a short program?

code:
class Test
{
  public static void main(String[] args)
  {
    try 
    {
      new URL("http://www.host.com/should work/").openStream();
    } catch (MalformedURLException mue) {
      System.out.println("checked exception; doesn't get thrown");
    } catch (IOException ioe) {
      System.out.println("also doesn't get thrown");
    }
  }
}

huge sesh
Jun 9, 2008

Normally the escaped URL won't show up in the console, I had to be running it as an applet in Firefox to see it. I guess there's maybe a verbose log level to trigger, I don't know how. E: I've set up an applet here if you want to see: http://www.gametape.info/static_media/java/url.html

huge sesh fucked around with this message at 06:55 on Aug 30, 2009

zootm
Aug 8, 2006

We used to be better friends.
From the URL API docs:

quote:

The URL class does not itself encode or decode any URL components according to the escaping mechanism defined in RFC2396. It is the responsibility of the caller to encode any fields, which need to be escaped prior to calling URL, and also to decode any escaped fields, that are returned from URL.
Use URLEncoder.encode to encode first. Also in general you might want to look into using Apache HTTPClient for HTTP in Java, it's a lot more featureful (although with that can come much painful configuration).

zootm fucked around with this message at 10:57 on Aug 30, 2009

covener
Jan 10, 2004

You know, for kids!

zootm posted:

From the URL API docs:

Use URLEncoder.encode to encode first. Also in general you might want to look into using Apache HTTPClient for HTTP in Java, it's a lot more featureful (although with that can come much painful configuration).

+1 on httpclient (and hopefully you have enough use for it to wrap it with something a little easier to use!)

Careful with URLEncoder.encode() as it does not URI encode the string you pass, it uses a "similar" specification for mime form data. IOW it doesn't no the significance of what needs to be encoded, and how, in a scheme, path, parameters, etc. The most obvious deviation is that it will encode spaces into "+" outside of the query string in a URI which is not appropriate. WebSphere actually has an APAR in modern releases for doing this in the web container.

covener fucked around with this message at 13:55 on Aug 30, 2009

zootm
Aug 8, 2006

We used to be better friends.

covener posted:

Careful with URLEncoder.encode() as it does not URI encode the string you pass, it uses a "similar" specification for mime form data. IOW it doesn't no the significance of what needs to be encoded, and how, in a scheme, path, parameters, etc. The most obvious deviation is that it will encode spaces into "+" outside of the query string in a URI which is not appropriate. WebSphere actually has an APAR in modern releases for doing this in the web container.
Yikes, I forgot about that, good call. In any case, the problem here is that URL expects a properly-formed URL, and one is not being supplied.

Max Facetime
Apr 18, 2009

As in the OP's case the invalid URL is being used internally by Java, instead of switching to another HTTP library another option would be to use HttpURLConnection and handling the redirection manually. It's pretty easy:

1) Create the connection: (HttpURLConnection) new URL("http://somepath").openConnection() is guaranteed to work.
2) Disable redirection: .setInstanceFollowRedirects(false)
3) Check the response code: .getResponseCode()
4) Get and fix the real location: .getHeaderField("Location").replace(' ', '+')
5) Make a normal connection with the fixed URL.

zootm
Aug 8, 2006

We used to be better friends.

tkinnun0 posted:

As in the OP's case the invalid URL is being used internally by Java, instead of switching to another HTTP library another option would be to use HttpURLConnection and handling the redirection manually. It's pretty easy:

1) Create the connection: (HttpURLConnection) new URL("http://somepath").openConnection() is guaranteed to work.
2) Disable redirection: .setInstanceFollowRedirects(false)
3) Check the response code: .getResponseCode()
4) Get and fix the real location: .getHeaderField("Location").replace(' ', '+')
5) Make a normal connection with the fixed URL.
If you've got to deal with a very limited number of possible response codes, that's probably enough.

tohveli
Nov 25, 2007

♪ オー マリア
I'm new to Java, and I'm trying to figure out how to pass objects as const to methods.

Say I have code like this:
code:
class SetPrinter {
	public void print( Set set ) {
		System.out.println( "Printing out a set with " + set.size() + " items:" );
		Iterator iter = set.iterator();
		int index = 0;
		while( iter.hasNext() ) {
			System.out.println( "item #" + index++ + ": " + iter.next() );
		}
		System.out.println();
		// line below added by an evil person
		set.clear(); // muahahah
	}
};

class Main {
	public static void main( String[] args ) {
		TreeSet set = new TreeSet();
		set.add( 3 ); set.add( 8 );

		SetPrinter sp = new SetPrinter();
		sp.print( set ); // expected result: prints 3,8
		set.add( 5 );
		sp.print( set ); // expected result: prints 3,8,5
                                 // in reality: prints 5 due to print() clearing the Set
	}
};
In Main.main(), I'm expecting the method SetPrinter.print() not to modify the set I pass in, however some malicious employee decided to add a line that modifies the object passed to SetPrinter.print() function. Is there a way to prevent this by passing the Set as const or by some means, to disallow the use of methods that modify the object?

In C++ this could be easily solved with const parameters and const methods, i.e.
code:
void SetPrinter::print( const Set &set ) { ... }
const_iterator Set::iterator() const { ... }
In C++ this is called const correctness.

How do I do this in Java?

tohveli fucked around with this message at 16:23 on Sep 1, 2009

csammis
Aug 26, 2003

Mental Institution
You write JUnit tests to ensure that calling the print method doesn't alter the set :colbert:


And the first Google hit on "java const correctness"

quote:

There is no way to declare that you will not modify the object pointed to by a reference through that reference in Java. Thus there are also no const methods. Const-correctness cannot be enforced in Java, although by use of interfaces and defining a read-only interface to your class and passing this around, you have a means to ensure that you can pass your objects around the system in a way they cannot be modified.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
If you know ahead of time that the item will be altered, why not just send it a temporary copy?

Janitor Prime fucked around with this message at 16:44 on Sep 1, 2009

tohveli
Nov 25, 2007

♪ オー マリア

MEAT TREAT posted:

If you know ahead of time that the item will be altered, why not just send it a temporary copy?

The thing is you can never know if it will be altered. What if I don't have the source code for SetPrinter? Also creating a copy of the whole object would be very inefficient, especially if working with large datasets.


So I saw it's possible to work around this by using separate read-only and read-write interfaces, but I'm not exactly sure how, but I can imagine it adding a lot more code and complexity. Here is a bug report at bugs.sun.com, but it's marked as WONTFIX :-( What shall I do now?

I guess writing unit tests is one way to check for it, but you can never be sure with that approach unless your unit tests are really well done.

tohveli fucked around with this message at 16:52 on Sep 1, 2009

Max Facetime
Apr 18, 2009

Use Collections.unmodifiableSet(set).

tohveli
Nov 25, 2007

♪ オー マリア

tkinnun0 posted:

Use Collections.unmodifiableSet(set).

Well the Set thing was just an example. I have my own classes I pass, how do I make them unmodifiable?

Volguus
Mar 3, 2009
As stated above: using interfaces.

don't give access to the actual collection (if you want to protect a collection), but instead provide an interface, with getObjectAt(index) type of functions. Or...getIterator(), etc.
The code will not become much more complicated:
code:
 public interface ListHandler{
   public Object getObjectAt(int index);
   public Iterator getIterator();
 }

 public class ArrayListHandler implements ListHandler{
  ...here do your stuff+ implement the 2 methods
 }

 ...
Then, whenever you need to pass the ArrayListHandler to a method, or return it from some method, don't pass the object but the interface.
Such as:

code:
 public class MyFactory{
  public ListHandler getMyListHandler(){
  ArrayListHandler handler=new ArrayListHandler();
   handler.addObject(new Integer(1));
   handler.addObject(new Integer(2));
   return handler;
  }
 }
As you can see, whoever calls the getMyListHandler() method will only get the interface, and as such, only access to the provided read-only methods.

Of course, what you cannot do, is prevent that person from casting to the implementation. That...you cannot help it. But they will get burned when you change the implementation of the same interface :).

Vandorin
Mar 1, 2007

by Fistgrrl
edit: Just going to ask my teacher.

Vandorin fucked around with this message at 20:13 on Sep 1, 2009

JingleBells
Jan 7, 2007

Oh what fun it is to see the Harriers win away!

Vandorin posted:

I've got a problem just compiling my code. I wrote it in class, and on those computers it ran fine, but when I try to run it on mine, it gives me the error "cannot find symbol - method drawRectangle (int, int)"

I can't get any of it to compile as I'm missing the SimpleTurtle and SimplePicture classes, what else is in the Guzdial package?

Max Facetime
Apr 18, 2009

tohveli posted:

Well the Set thing was just an example. I have my own classes I pass, how do I make them unmodifiable?

The same principle applies. You can wrap it in an unrelated class that provides a read-only view.

Outlaw Programmer
Jan 1, 2008
Will Code For Food
Defensive copying is as good as you're going to get here. Even if you use an unmodifiable view, if your Collection is full of mutable objects malicious client code can still gently caress with the elements themselves.

Don't be afraid of copying or cloning objects, especially if its the only way to enforce that your program is correct. It doesn't matter if your code is lightning fast if it produces the wrong results, after all!

zootm
Aug 8, 2006

We used to be better friends.

Outlaw Programmer posted:

Defensive copying is as good as you're going to get here. Even if you use an unmodifiable view, if your Collection is full of mutable objects malicious client code can still gently caress with the elements themselves.

Don't be afraid of copying or cloning objects, especially if its the only way to enforce that your program is correct. It doesn't matter if your code is lightning fast if it produces the wrong results, after all!
Yep, this is pretty much it. Also it's worth noting that favouring immutable objects will avoid this sort of problem in a lot of cases in general.

const correctness always seemed like a neat idea to me, but I'm led to believe it's often neglected or undermined in practice. Making it actually impossible to modify objects is a close analogue which sidesteps the issue in any case.

Kaltag
Jul 29, 2003

WHAT HOMIE? I know dis ain't be all of it. How much of dat sweet crude you be holdin' out on me?
What the hell is going on?

I can't get a JPopupMenu to only show up when you right click. I understand this is refered to the 'windows look and feel' but I can't get it to take. I know that the BasicPopupMenuUI refers to the windows look and feel for popup menus, but like I said, won't do it.

code:
popUp = new JPopupMenu();

popUp.setUI(new BasicPopupMenuUI()); //this doesn't work

BasicPopupMenuUI wlf = new BasicPopupMenuUI(); 
wlf.installUI(popUp); //neither does this

popUp.setUI(wlf); //what the gently caress!?!?

menuItem = new JMenuItem("Create Spectrograms...");
menuItem.addActionListener(new MenuItemListener());
popUp.add(menuItem);
Maybe I have to implement this in my actionlistener?

code:
public class MenuItemListener implements ActionListener
{
	MenuItemListener(){}

	public void actionPerformed(ActionEvent actevent) 
        {
	    String cmd = actevent.getActionCommand();
	    if (cmd.equalsIgnoreCase("Create Spectrograms...")) 
	    {
	    	System.out.println("GOING TO CREATE SPECGRAMMIES");
	    }
	}
}
Java gui work is not my thing, I usually do C and data processing poo poo so feel free to berate me.

yatagan
Aug 31, 2009

by Ozma

Kaltag posted:

Java gui work is not my thing, I usually do C and data processing poo poo so feel free to berate me.

Check out this bad boy:
http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html#popup

Kaltag
Jul 29, 2003

WHAT HOMIE? I know dis ain't be all of it. How much of dat sweet crude you be holdin' out on me?

yeah I've read over that like a million times already

I already have the popupmenu showing up its just that I don't want it to show up when i left click, maybe i wasnt clear

Kaltag fucked around with this message at 21:42 on Sep 3, 2009

Volguus
Mar 3, 2009
I'm not really sure how to answer this, since they give in there example code and explanation about how it all works out. It can't be better, imo.

What exactly do you try to accomplish?

the example clearly gives you:

- How to create a popup menu and add items to it.
- How to display the said popup menu when the user right-clicks on a component (in that example, both "output" and "menuBar" got the popupListener).

I saw from your code that you are creating the popup menu. and added items to it. And you have an actionlistener created, but it doesn't seem to do anything (no showing the menu). Nor do you seem to add said listener to a component for it to be actually called.
So, i cant really say what's missing unless you'll tell more.

Edit:
ooo, so its showing up, but on both clicks. I see now.
The "e.isPopupTrigger()" line is essential in this case.

Kaltag
Jul 29, 2003

WHAT HOMIE? I know dis ain't be all of it. How much of dat sweet crude you be holdin' out on me?

rhag posted:

The "e.isPopupTrigger()" line is essential in this case.

That's all I needed to hear.

popUp.setUI(new BasicPopupMenuUI()); sets the windows look and feel, causing isPopUpTrigger to be true only when there is a right click. I only had to modify my actionlistener that added to my menuItem to include the line

code:
if(e.isPopupTrigger())
    popUp.show(e.getComponent(), e.getX(), e.getY());
and it works just great.

I'm guessing unless you set the UI to be new BasicPopupMenuUI() then e.isPopupTrigger will always be true, by default.

Thanks rhag!

VV right again

Kaltag fucked around with this message at 14:33 on Sep 4, 2009

Volguus
Mar 3, 2009

Kaltag posted:

That's all I needed to hear.

popUp.setUI(new BasicPopupMenuUI()); sets the windows look and feel, causing isPopUpTrigger to be true only when there is a right click. I only had to modify my actionlistener that added to my menuItem to include the line

code:
if(e.isPopupTrigger())
    popUp.show(e.getComponent(), e.getX(), e.getY());
and it works just great.

I'm guessing unless you set the UI to be new BasicPopupMenuUI() then e.isPopupTrigger will always be true, by default.

Thanks rhag!

That should not be the case. You should not have to set the UI, since that should be set by the current Look&Feel.
You do have a line (at the beggining of your main function, before creating & showing your main frame window), like this:
UIManager.setLookAndFeel("some L&F class")?

Usually, I just use the platform's L&F, and that can be accomplished easily by:
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); Or, just use the Metal L&F :UIManager.getCrossPlatformLookAndFeelClassName().

I don't remember ever having e.isPopupTrigger() being true on both mouse buttons. I'm guessing that happens in your case because you didn't set the UI. I hope.

Anyhow, you're welcome.

Cosmopolitan
Apr 20, 2007

Rard sele this wai -->
For some reason, NetBeans is ridiculously slow. I by no means have a crappy computer, and NetBeans hangs for about 4 seconds whenever I so much as open the options. Has anyone else experienced this, or is it something wrong with my computer?

Eclipse seems faster, but its interface doesn't really make any sense. It took me 5 minutes to figure out how to add a source file to a project, and I had to go to the source file's directory and drag it in.

And one thing that both IDEs did is if you name your source file anything but "Main", it has to ask you what the main class is the first time you run it. Is there any way around this?

yatagan
Aug 31, 2009

by Ozma

Anunnaki posted:

And one thing that both IDEs did is if you name your source file anything but "Main", it has to ask you what the main class is the first time you run it. Is there any way around this?

If you only have one class with a main method in the current project, I seem to recall Eclipse usually picks right up on it. You're looking for "import" to add existing source files to a project. Eclipse is very nice once you find your way around it, very full featured with plenty of plugin capabilities.

Cosmopolitan
Apr 20, 2007

Rard sele this wai -->
How do you do input from the console to multiple variables? In C++, you would do something like cin >> var1 >> var2;, but even my professor told me you have to just write one input command for each variable. Somehow I doubt this.

Edit: Just to clarify, I'm asking here because I haven't been able to find a clear answer with Google. :)

Cosmopolitan fucked around with this message at 00:07 on Sep 13, 2009

JingleBells
Jan 7, 2007

Oh what fun it is to see the Harriers win away!

Anunnaki posted:

How do you do input from the console to multiple variables? In C++, you would do something like cin >> var1 >> var2;, but even my professor told me you have to just write one input command for each variable. Somehow I doubt this.

Edit: Just to clarify, I'm asking here because I haven't been able to find a clear answer with Google. :)
At uni our textbook provided a class called EasyIn, MindProd's java site has a good example of it

huge sesh
Jun 9, 2008

I'm looking for a way to link a scripting language to a signed applet in such a way that it runs inside the normal unsigned applet sandbox. Can I just compile to two separate jars, sign one and link at runtime to get the behavior I want?

nanerpuss
Aug 6, 2005

voudrais-tu une banane, mon amie?
whoops

butts

nanerpuss fucked around with this message at 20:36 on Sep 16, 2009

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
You do know that this is the Java and not the javascript thread right?

nanerpuss
Aug 6, 2005

voudrais-tu une banane, mon amie?

MEAT TREAT posted:

You do know that this is the Java and not the javascript thread right?

I do now! :3
My bad.

Cosmopolitan
Apr 20, 2007

Rard sele this wai -->
I seem to be having a lot of trouble just trying to use 64-bit Java. My browsers don't detect it, I had to scour the internet to find 64-bit installations of IDEs, etc. Is it just not worth it? I mean, there have to be some developers who make 64-bit Java programs..? im dum

Edit: VVVVVVV
No, this wasn't a troll, thanks for the answers. I'm coming from two semesters of C++, it slipped my mind that Java was an interpreted language. :doh: Thanks.

Cosmopolitan fucked around with this message at 23:57 on Sep 18, 2009

Volguus
Mar 3, 2009

Anunnaki posted:

I seem to be having a lot of trouble just trying to use 64-bit Java. My browsers don't detect it, I had to scour the internet to find 64-bit installations of IDEs, etc. Is it just not worth it? I mean, there have to be some developers who make 64-bit Java programs..?

Umm....is this a troll?
In the 0.01% chance that it isn't, here are some answers:

Eclipse has a jdk x86_64 version. Dunno about other IDEs.
Nobody writes 64-bit Java programs . The...concept doesn't really make sense. You write a java program that program will run on the i586 and 64-bit JVMs. On any OS.
Browsers: the browser has to be a 64 bit browser with a 64-bit java plugin to be able to run applets using the 64-bit JRE. I don't think firefox comes in the 64-bit flavour. IE does i think, never really cared.

Your java program won't ever really know if its running in a 64-bit JRE, nor should it care.

Mill Town
Apr 17, 2006

Anunnaki posted:

I seem to be having a lot of trouble just trying to use 64-bit Java. My browsers don't detect it, I had to scour the internet to find 64-bit installations of IDEs, etc. Is it just not worth it? I mean, there have to be some developers who make 64-bit Java programs..? im dum

Edit: VVVVVVV
No, this wasn't a troll, thanks for the answers. I'm coming from two semesters of C++, it slipped my mind that Java was an interpreted language. :doh: Thanks.

Java is actually compiled, not interpreted. It's just that it's compiled to platform-independent bytecode that's executed on a virtual machine which may be running on a 16, 32 or 64 bit platform.

(Yes, I have run Java on a 16 bit platform before. Specifically, an embedded JVM on a Hitachi H8 on a Lego brick :cool:)

Adbot
ADBOT LOVES YOU

Cosmopolitan
Apr 20, 2007

Rard sele this wai -->

Mill Town posted:

Java is actually compiled, not interpreted. It's just that it's compiled to platform-independent bytecode that's executed on a virtual machine which may be running on a 16, 32 or 64 bit platform.

(Yes, I have run Java on a 16 bit platform before. Specifically, an embedded JVM on a Hitachi H8 on a Lego brick :cool:)

My CS teacher's been telling me it's a "hybrid." v:shobon:v

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