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
Hidden Under a Hat
May 21, 2003

Tamba posted:

yourDialog.setUndecorated(true);

(and I think you need to do this before it is displayed/set visible)

edit: http://download.oracle.com/javase/6/docs/api/java/awt/Dialog.html#setUndecorated%28boolean%29

Well I actually want the borders to show in the final version otherwise it looks like garbage. Is there a way to find the extra width/height that an OS will add with decorations?

Adbot
ADBOT LOVES YOU

Tamba
Apr 5, 2010

I can't test it here, but you could try getInsets() and read the fields of the object it returns.
http://download.oracle.com/javase/6/docs/api/java/awt/Insets.html

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
Hidden Under a Hat: Seriously, just use setPreferredSize() on the content pane of the window or whatever top level component is inside it. When you pack the window it will size itself to give the content pane the right amount of space and then add the decorations around the edges.

Volguus
Mar 3, 2009

Hidden Under a Hat posted:

I'm having trouble with JDialog window sizing. In Netbeans, I size the dialog the way I want it to fit my components, but when I actually run the program, the OS adds this extra crap to it like blue trim borders, which takes up the space where my components should be and pushes them off the screen forcing me to manually resize it to see them. How can I fix this issue or at least find out the size of the extra crap that Windows is adding so I can compensate for it?

You dont. You set the size of your dialog to whatever you feel you need (300x400, 500x400, 800x600, whatever). Using layout managers (use gridbaglayout if the layout is complex) everything will just fall into place.

And don't, please do not, use a designer to make a UI in swing. it's not worth the time wasted and the headaches. Check out this tutorial, is very good: http://download.oracle.com/javase/tutorial/uiswing/layout/gridbag.html .

Always (in swing) code your ui by hand. It's the best way to keep your sanity (somewhat) intact.

Hidden Under a Hat
May 21, 2003

rhag posted:

You dont. You set the size of your dialog to whatever you feel you need (300x400, 500x400, 800x600, whatever). Using layout managers (use gridbaglayout if the layout is complex) everything will just fall into place.

And don't, please do not, use a designer to make a UI in swing. it's not worth the time wasted and the headaches. Check out this tutorial, is very good: http://download.oracle.com/javase/tutorial/uiswing/layout/gridbag.html .

Always (in swing) code your ui by hand. It's the best way to keep your sanity (somewhat) intact.

Yah I've definitely realized it's something I need to learn so that is on my plate next. Unfortunately I need to get a piece of software running and looking good by mid-November but after that I'm going to code my own layouts.

iscis
Jan 8, 2007
im the coolest guy you know
Yo I'm trying to write a class that counts the number of even, odd and zero digits in an input, and can't figure out what's wrong with my code; the program never terminates for whatever reason.

code:
import java.util.*;

public class digitReader {
	public static void main(String[] args) {
		int oddCount = 0, evenCount = 0, zeroCount = 0;
		int value, digit;
		Scanner scan = new Scanner(System.in);
		System.out.println("Enter an integer value:");
		value = scan.nextInt();
		value = value < 0 ? -value : value;
		if (value == 0)
			zeroCount++;
		while (value > 0) {
			digit = value % 10;
			if (digit == 0)
				zeroCount++;
			else if (digit % 2 == 0)
				evenCount++;
			else
				oddCount++;
			value = value % 10;
		}
		System.out.println("Number of even digits: " + evenCount);
		System.out.println("Number of odd digits: " + oddCount);
		System.out.println("Number of zero digits: " + zeroCount);
	
	}
}

baquerd
Jul 2, 2007

by FactsAreUseless

iscis posted:

Yo I'm trying to write a class that counts the number of even, odd and zero digits in an input, and can't figure out what's wrong with my code; the program never terminates for whatever reason.

It's never too soon to learn about debuggers and how they can help you step through a program. They'll help you learn to analyze where things go wrong without using them too.

Hint: is "value = value % 10" really what you want to do?

Also, and this is a personal style thing: use braces everywhere because they help avoid confusion. You don't have a problem with this code and that issue, but your code looks naked and weird to me.

iscis
Jan 8, 2007
im the coolest guy you know

baquerd posted:

It's never too soon to learn about debuggers and how they can help you step through a program. They'll help you learn to analyze where things go wrong without using them too.

Hint: is "value = value % 10" really what you want to do?

Also, and this is a personal style thing: use braces everywhere because they help avoid confusion. You don't have a problem with this code and that issue, but your code looks naked and weird to me.

Wow what a terrible, simple mistake, I need to go to bed. Thanks for the help/tips though

iscis
Jan 8, 2007
im the coolest guy you know
I hate to keep turning to ya'll, but this has been driving me crazy all day. What is wrong with my for loop?
code:

import java.util.*;
public class evenSum {
		public static void main(String[] args) {
		int value;
		int sum=0;
		Scanner scan= new Scanner(System.in);
		System.out.println("Enter a positive value:");
		value = scan.nextInt();
		if (value<2)
		System.out.println("Value must be greater than two");
		for(int sum=0; sum<=value; sum+2;) {
			System.out.println("The sum of the even integers between 2 and" +value);
			System.out.print("is: " +sum);
					}
	
		}

}
\
I'm trying to print the sum of the even integers between 0 and an input

baquerd
Jul 2, 2007

by FactsAreUseless

iscis posted:

I hate to keep turning to ya'll, but this has been driving me crazy all day. What is wrong with my for loop?

You've got duplicate definitions in the same scope on "sum" and you're missing an assignment operator in the increment portion of your for loop. And your code needs a healthy dose of auto formatting. Does this actually compile? Do you use an IDE?

Alterian
Jan 28, 2003

I think you would need to have it sum+=2 or sum=sum+2 to work right.

Max Facetime
Apr 18, 2009

iscis posted:

I hate to keep turning to ya'll, but this has been driving me crazy all day. What is wrong with my for loop?

I'm trying to print the sum of the even integers between 0 and an input

Heh, this the wrong way to ask this question, because the only correct answer that can be given is:

I guess it doesn't work like you intended. (Also it's indented all wrong.)

You want a bunch of integers and a sum from those integers. One of those doesn't depend on getting the other working as intended, so you can do that part first.

So let me ask you: how did you intend it to work and how does the way it works now differ from what you intended?

cenzo
Dec 5, 2003

'roux mad?
Anyone familiar with Hibernate know if you can use an Example to query a many-to-one relationship using the "one" side of the relationship?

I have two tables/classes, Foo and Bar. Every record in Foo there is a FK to the PK of the associated record in Bar. I'm trying to use Example and Criteria to get all the Foo records that are linked to matching records of Bar, in this case where Bar's distinguishedName field is "herpderp"

Something like this (assuming session management is in place):
code:
public Collection fetchByExample(){
     Foo foo = new Foo();
     foo.setVoided(false);
     Bar bar = new Bar();
     bar.setDistinguishedName("herpderp");
     bar.setVoided(false);
     foo.setBar(bar);
     Example ex = Example.create(foo)
          .excludeZeroes(); 
     Criteria crit = session.createCriteria(Foo.class)
          .add(ex);
     Collection foosByBar = crit.list();
     return foosByBar;
}

Hibernate mapping:

<hibernate-mapping>
    <class name="com.xxx.yyy.domain.Foo"
        table="FOO" >
...
    	<many-to-one 
    		name="bar" 
    		column="BAR_ID"
            class="com.xxx.yyy.domain.Bar" 
            cascade="all" 
            lazy="false"
            fetch="join"/>
    </class>
</hibernate-mapping>
I've tried this code but it only limits the results based on the Foo class members (this example: Foo records not voided), and the show sql makes no reference to the distinguished_name column. I guess that I'm really looking for is a property or something for the hibernate mapping or config file that will force it to look at ALL the fields across associations.

cenzo fucked around with this message at 21:03 on Oct 27, 2011

Max Facetime
Apr 18, 2009

I haven't used Example queries, but when querying annotated classes you have to call createCriteria each time you want to navigate an association with a join.

Hibernate docs posted:

You can even use examples to place criteria upon associated objects.

List results = session.createCriteria(Cat.class)
.add( Example.create(cat) )
.createCriteria("mate")
.add( Example.create( cat.getMate() ) )
.list();

So I guess you'll have to make multiple Examples and tie them together in the Criteria.

cenzo
Dec 5, 2003

'roux mad?
Thanks so much, that did it. I tried creating another criteria of Bar.class instead of the field name. Changed that to the string "parentBar" and I'm filtering correctly.

Thanks again!

Harold Ramis Drugs
Dec 6, 2010

by Y Kant Ozma Post
I'm trying to set up an if-loop to look for certain lines of text on an input file. The file looks like this in wordpad:
code:
3
2
R P
S R
3
P P
R S
S R
1
P R
What I've been doing is setting up a temporary string variable using the ".nextLine();" operation, and then trying to compare that temp string to one of my defined values, such as "R P". It's not recognizing them though, and I think it's because there might be some hidden characters somewhere in there, such as newlines or carriage returns, making the temp string look like "\rR P\n" or something else. When I'm using the .nextLine function to set the value of a temporary string, what specifically is the string getting set to?

Edit: Durf, totally solved my own problem. Don't use x == y to compare strings, use x.equals(y)

Harold Ramis Drugs fucked around with this message at 04:01 on Oct 29, 2011

pliable
Sep 26, 2003

this is what u get for "180 x 180 avatars"

this is what u fucking get u bithc
Fun Shoe

Harold Ramis Drugs posted:

Edit: Durf, totally solved my own problem. Don't use x == y to compare strings, use x.equals(y)

Pffffffft, amateur. Yeah, that's definitely tripped me up a few times, but once you learn...it's so valuable.

Always use the equals() methods to compare your strings, kiddies.

No Safe Word
Feb 26, 2005

pliable posted:

Pffffffft, amateur. Yeah, that's definitely tripped me up a few times, but once you learn...it's so valuable.

Always use the equals() methods to compare your strings, kiddies.

Always use equals() to compare everything but primitive types

pliable
Sep 26, 2003

this is what u get for "180 x 180 avatars"

this is what u fucking get u bithc
Fun Shoe

No Safe Word posted:

Always use equals() to compare everything but primitive types

And references :).

Sab669
Sep 24, 2009

Why is equals() better than ==? I'm a huge noob at all of this... and in related news! The reason why I came to this thread.

I'm taking a Design Patterns course that uses Java, but I'm much more comfortable with the .net framework (specifically C#).

Trying to write a try-catch statement to verify some input from the user. Unlike a try-catch from what I'm used to, this REQUIRES some sort of error to throw- I can't just print out my own error message.

Basically

code:
try{
    difficulty = kb.nextInt();
} 
catch{
    System.out.println("Error: only enter 1-3");
}
I guess I'm not sure what the most "proper" way of doing this is?

e; Looks like I've just got to make my own class that interfaces* Exception?
*Is that the proper term? I can never keep abstract/interface/whatever else straight :(

Sab669 fucked around with this message at 00:45 on Oct 31, 2011

Ensign Expendable
Nov 11, 2008

Lager beer is proof that god loves us
Pillbug
The difference between .equals() and == is that the first compares the contents of the class, whereas the second compares their references. "a".equals("a") will return true, but "a"=="a" will return false, since those are two different String objects.

Also, in Java, you need an Exception for a try-catch. You don't need to make your own Exception class, really. The word you're thinking of is "extends".
code:
try
{
}
catch (Exception e)
{
}

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Sab669 posted:

Why is equals() better than ==? I'm a huge noob at all of this... and in related news! The reason why I came to this thread.

Unlike C#, Java doesn't support overloading of operators - while in C# you might overload the == operator on a class to mean something sensible for that class, in Java the == operator has a fixed meaning across everything.

When using == on a primitive value type, it checks if they are the same value, as we expect. But when using it on a reference type (i.e. anything that's actually a class), the == operator checks for reference equality - that is, whether both parameters refer to the exact same thing. So if you have two strings, they might both say "bob", but if they're two different objects at two different places in memory, == will say that they're different.

Sometimes you want to check reference equality - but most of the time it's value equality that you're interested in, so you should be using equals().


Ensign Expendable posted:

The difference between .equals() and == is that the first compares the contents of the class, whereas the second compares their references. "a".equals("a") will return true, but "a"=="a" will return false, since those are two different String objects.

This might not be the best example - try the following:

code:
public static void main (String[] args) throws java.lang.Exception
{
        System.out.printf("equals(): %b\n", "a".equals("a"));
        System.out.printf("==: %b\n", "a" == "a");
}
The java compiler performs interning on string literals, which means that no matter how many times you write "a" in your code, only one string actually gets emitted (and so, of course, reference equality 'works').

This makes it even more annoying to debug issues caused by == if you don't know what's going on - your program works fine with hardcoded inputs, but as soon as you switch it to taking input from the user, it breaks.

Jabor fucked around with this message at 01:13 on Oct 31, 2011

pliable
Sep 26, 2003

this is what u get for "180 x 180 avatars"

this is what u fucking get u bithc
Fun Shoe

Sab669 posted:

Why is equals() better than ==? I'm a huge noob at all of this... and in related news! The reason why I came to this thread.

It's not a matter of being "better" than one another. You're simply comparing two different things.

== is used to compare primitive types, or references. That's all it should be used for. The .equals() methods of classes is meant to compare the data within the object. So for example, you have two String objects (call them a and b), and both have "hello" in them. String has various data in it; it doesn't JUST contain the string "hello". In order to directly compare the strings, you need to call the .equals() method. So to properly compare a's "hello" and b's "hello", you call a.equals(b);

Sab669 posted:

Trying to write a try-catch statement to verify some input from the user. Unlike a try-catch from what I'm used to, this REQUIRES some sort of error to throw- I can't just print out my own error message.

Basically

code:

try{
difficulty = kb.nextInt();
}
catch{
System.out.println("Error: only enter 1-3");
}

I guess I'm not sure what the most "proper" way of doing this is?

e; Looks like I've just got to make my own class that interfaces* Exception?
*Is that the proper term? I can never keep abstract/interface/whatever else straight

If you want to be terrible about it, you can just write:

code:
try {
   difficulty = kb.nextInt();
} catch (Exception ex) {
   ex.printStackTrace();
   System.out.println(ex.getMessage());
   System.out.println("Error: only enter 1-3");
}
But, you should be more specific and probably use whatever kb.nextInt() throws (which I'm guessing is the Scanner method).

code:
Throws:
    InputMismatchException - if the next token does not match the Integer regular expression, or is out of range 
    NoSuchElementException - if input is exhausted 
    IllegalStateException - if this scanner is closed
Catch one of those bitches and do proper error output or correction, etc.

Sab669
Sep 24, 2009

Right right, thanks for the quick responses.

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.
I have a sprite,

that I want to tint with Color(210, 190, 0, 100) RGBA, and have it come out looking like this:

(not exactly like this, just close)

That one is being created by C#/XNA's SpriteBatch.Draw. I've got no idea how XNA does the tinting.

My very hacky code results in the following:

which is obviously wrong because I don't know what I'm doing. Not only is it not coming even close, I had to put a workaround in to prevent it from making the transparency turn black-yellow.
XNA is obviously using an actual artistic drawing method but I've got no idea what it's doing, and I can't find a way to reproduce it.
Also tried using ColorTintFilter, but it has the same result as my code, though at least it handles transparency.
None of the overlay modes in Photoshop seem to match it either.

Any idea what I should be looking for?

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
It actually looks fairly similar to Photoshop's "Overlay" mode.

Paolomania
Apr 26, 2006

Aleksei Vasiliev posted:

I have a sprite,

that I want to tint with Color(210, 190, 0, 100) RGBA, and have it come out looking like this:

(not exactly like this, just close)

That one is being created by C#/XNA's SpriteBatch.Draw. I've got no idea how XNA does the tinting.

My very hacky code results in the following:

which is obviously wrong because I don't know what I'm doing. Not only is it not coming even close, I had to put a workaround in to prevent it from making the transparency turn black-yellow.
XNA is obviously using an actual artistic drawing method but I've got no idea what it's doing, and I can't find a way to reproduce it.
Also tried using ColorTintFilter, but it has the same result as my code, though at least it handles transparency.
None of the overlay modes in Photoshop seem to match it either.

Any idea what I should be looking for?

What you want is Photoshop's "overlay" mode and I'm pretty sure XNA's tint is a simple multiplicative effect. The last time I did something similar I had to implement my own shader that simulated the Photoshop "overlay" operation.

from here:
if (Base > ½) R = 1 - (1-2×(Base-½)) × (1-Blend)
if (Base <= ½) R = (2×Base) × Blend

Mobius
Sep 26, 2000
I am trying to teach myself about web services. I have successfully built a working service, client, and .jsp-driven UI. I did this with Eclipse, Axis2, Tomcat 7, and Java 7.

The basic flow is that the user visits the .jsp and submits a form with input data. The JSP forwards the "request" object to the Java client. The Java client consumes the web service and submits the user input. The service connects to a SQL Server database via JDBC to retrieve information, which is displayed back to the user.

This all works perfectly over HTTP, but now I want to secure the process, and this is where I'm running into problems. I'm able to create a cert and get Tomcat to use it. I can connect to the web UI via HTTPS and submit the form and get data back just fine. The problem is that this is only securing the front-end. The web service client code is still connecting to the service via HTTP in the background.

According to this page, all I really need to do to enable my service for connections via SSL is to update the axis2.xml file and include a new "transportReceiver" node for HTTPS. I did that and regenerated my client code to use the secure endpoint. It doesn't work.

I have configured Tomcat to listen on ports 8081 for http and 8443 for https. But after changing axis2.xml to match, and starting up Tomcat, I get the following:

quote:

[INFO] Listening on port 8443
[ERROR] Terminating connection listener org.apache.axis2.transport.http.server.DefaultConnectionListener@16d60567 after 10retries in 0 seconds.
java.net.BindException: Address already in use: JVM_Bind
at java.net.DualStackPlainSocketImpl.bind0(Native Method)
at java.net.DualStackPlainSocketImpl.socketBind(Unknown Source)
at java.net.AbstractPlainSocketImpl.bind(Unknown Source)
at java.net.PlainSocketImpl.bind(Unknown Source)
at java.net.ServerSocket.bind(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
at org.apache.axis2.transport.http.server.DefaultConnectionListener.run(DefaultConnectionListener.java:80)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

I have tried changing the port number in axis2.xml (for example, to 8445), and that sort of works. The server is able to start cleanly, but eventually, the same errors start showing up. For example, when I retrieve the WSDL, I see the error. If I try to actually use the service when on port 8445, I get the following error:

quote:

org.apache.axis2.AxisFault: Connection has been shutdown: javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?

I can only assume this is because Tomcat is configured to handle HTTPS on 8443, not 8445, but I honestly don't know.

If I leave the port as 8443 and ignore the errors at startup, I get the following message when I connect to the service:

quote:

org.apache.axis2.AxisFault: Connection has been shutdown: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

I followed these steps to try to get it to recognize my certificate, but when importing it into my JRE7 keystore, I get the following:

quote:

keytool error: java.lang.Exception: Certificate reply and certificate in keystore are identical

Basically, that cert is already there. Which makes sense, because it's the one that Tomcat is already using successfully.

So, I'm pretty clueless at this point. I'm really not sure what I'm supposed to be doing. Any general guidance, or a link to a step-by-step how-to would be really helpful.

But for a specific question... What, exactly, am I doing when I set the transportReceiver nodes in axis2.xml? Am I telling it what ports Tomcat is running on and that it should use, or does Axis2 have its own servers that will start on those ports? It seems to be the latter, but that doesn't make a whole lot of sense to me.

Mobius fucked around with this message at 20:54 on Nov 5, 2011

RitualConfuser
Apr 22, 2008

Mobius posted:

Am I telling it what ports Tomcat is running on and that it should use, or does Axis2 have its own servers that will start on those ports? It seems to be the latter, but that doesn't make a whole lot of sense to me.
I believe you're correct that it seems like that latter is what's happening but you want the former since you're deploying in Tomcat (instead of running standalone). In the axis2.xml config, is the class attribute of the transportReceiver set to AxisServletListener like in that article you linked to?

e: Basically, you'd want the request to go Client -> Tomcat -> Axis2, but based on your post, Axis2 is starting up its own HTTP server so the request would actually go Client -> Axis2. So, you need a way to tell Axis2 to use its container (Tomcat) to handle the HTTPS requests instead of starting up its own server, and the transportReceiver config seems to be the way to go about that. Some useful info here.

RitualConfuser fucked around with this message at 22:27 on Nov 5, 2011

Mobius
Sep 26, 2000

RitualConfuser posted:

I believe you're correct that it seems like that latter is what's happening but you want the former since you're deploying in Tomcat (instead of running standalone). In the axis2.xml config, is the class attribute of the transportReceiver set to AxisServletListener like in that article you linked to?

e: Basically, you'd want the request to go Client -> Tomcat -> Axis2, but based on your post, Axis2 is starting up its own HTTP server so the request would actually go Client -> Axis2. So, you need a way to tell Axis2 to use its container (Tomcat) to handle the HTTPS requests instead of starting up its own server, and the transportReceiver config seems to be the way to go about that. Some useful info here.

Ahh, good call, that was it! Both my HTTP and HTTPS entries were set to use SimpleHTTPServer instead of AxisServletListener. I updated both to use AxisServletListener, and that got rid of the "Address already in use" errors. On a side note, it looks like the only reason raw HTTP ever worked for me is because axis was configured to listen for it on 8080. So I think it was starting up its own process for it all along. Now, both are listening through the container, like I expected.

BUT

I'm now consistently getting the "unable to find valid certification path to requested target" error. :(

But this is progress, nonetheless.

RitualConfuser
Apr 22, 2008

Mobius posted:

I'm now consistently getting the "unable to find valid certification path to requested target" error. :(

But this is progress, nonetheless.
First step would be to turn on SSL debug on the client side to see what's really going on. It would also be easy to just create a new keystore using keytool, import your cert into it, and explicitly set javax.net.ssl.trustStore to the path of that keystore.

Mobius
Sep 26, 2000

RitualConfuser posted:

First step would be to turn on SSL debug on the client side to see what's really going on. It would also be easy to just create a new keystore using keytool, import your cert into it, and explicitly set javax.net.ssl.trustStore to the path of that keystore.

Thanks for the tip on SSL Debug, I'll definitely get some use out of that in the future.

As for the certificate problem, it was me misunderstanding the distinction between a keystore and a truststore. Explicitly setting the truststore in the code worked, but then it clicked for me that the JVM defaults to a different file for its trust store -- one other than my keystore.

So, I imported my certificate into JAVA_HOME\lib\security\cacerts instead of USER_HOME\.keystore, and now it works transparently, without having to explicitly set the truststore in code. This is actually what the instructions I linked to were doing, but I didn't follow them to the letter because I didn't realize the keystore and truststore were separate.

Thanks for the help!

Mobius fucked around with this message at 17:27 on Nov 6, 2011

Akarshi
Apr 23, 2011

Alright SA, I've been having loads of trouble with this homework. It's pretty long and convoluted so I'll just link to the assignment....the text files are provided on the site if people need to look at them: http://www.cis.upenn.edu/~cis110/hw/hw06/index.html

Right now I am on Step 2 and stuck on randomly choosing from the three items associated with the treasure class, checking to see if they start with "tc". I can extract the treasure class from the monster.txt file and I have the monster. This is my method for finding the treasure class:
code:
public static void getTreasureClass(Monster monGet)
    throws FileNotFoundException{
    Random rand = new Random();
    String tc=monGet.getTreasureClass();
    Scanner file=new Scanner(new File ("TreasureClassEx.txt"));
    System.out.println(tc);
    while(!file.next().equals(tc)){
        file.next();
        }
    tc=file.next();
    if (tc.startsWith("tc:")){

    }
    else {
        System.out.println("test");
        }   
    }
I know that is extremely incomplete, but I would appreciate some tips on where to go next in terms of randomly choosing from the three items, or if my code is bad. Thanks in advance everyone.

ShardPhoenix
Jun 15, 2001

Pickle: Inspected.

Akarshi posted:

Alright SA, I've been having loads of trouble with this homework. It's pretty long and convoluted so I'll just link to the assignment....the text files are provided on the site if people need to look at them: http://www.cis.upenn.edu/~cis110/hw/hw06/index.html

Right now I am on Step 2 and stuck on randomly choosing from the three items associated with the treasure class, checking to see if they start with "tc". I can extract the treasure class from the monster.txt file and I have the monster. This is my method for finding the treasure class:
code:
public static void getTreasureClass(Monster monGet)
    throws FileNotFoundException{
    Random rand = new Random();
    String tc=monGet.getTreasureClass();
    Scanner file=new Scanner(new File ("TreasureClassEx.txt"));
    System.out.println(tc);
    while(!file.next().equals(tc)){
        file.next();
        }
    tc=file.next();
    if (tc.startsWith("tc:")){

    }
    else {
        System.out.println("test");
        }   
    }
I know that is extremely incomplete, but I would appreciate some tips on where to go next in terms of randomly choosing from the three items, or if my code is bad. Thanks in advance everyone.
Load the relevant items into a list first, then select a random index from the list.

Akarshi
Apr 23, 2011

We haven't learned about lists or arrays yet in our class. Thanks though, I managed to figure out how to do it anyways.

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

Has anyone here worked with JavaFX? If so, what is it meant to be? I tried a tutorial that drew some blended circles and moved them, but I don't understand what it's really designed to do (well.)

lamentable dustman
Apr 13, 2007

ðŸÂ†ðŸÂ†ðŸÂ†

carry on then posted:

Has anyone here worked with JavaFX? If so, what is it meant to be? I tried a tutorial that drew some blended circles and moved them, but I don't understand what it's really designed to do (well.)

I think it was Java's product to compete with Adobe Air but it never caught on.

ShardPhoenix
Jun 15, 2001

Pickle: Inspected.

Akarshi posted:

We haven't learned about lists or arrays yet in our class. Thanks though, I managed to figure out how to do it anyways.
I remember being in the same spot. I was working on a side project when I first started learning programming. I had a loop that made a bunch of objects, but then I could figure out how to "get them back" later in the program. Later in the course we learned about lists and arrays and was all "ooohhh" :v:.

tyang209
Feb 17, 2007
Totally confused by this compiler error. I'm using DrJava and Eclipse and I'm pretty sure it's an error with something within Dr Java.

Code Snippet

quote:

public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);

System.out.print("name of input file: ");
String inputName = console.next(); //error lines
System.out.print("name of output file: ");
String outputName = console.next();
System.out.print("school to extract: ");
String school = console.next();

[line: 22]
Error: next() is an ambiguous invocation. It matches both next() and next()


I can't use next() without getting this error and the program should compile. This should compile as I grabbed this off my course website as an example program and it did compile on Dr Java for Mac but I'm getting that ambiguous invocation error on my PC. Totally confused as to why. Could anyone drop some knowledge on me?

Adbot
ADBOT LOVES YOU

pliable
Sep 26, 2003

this is what u get for "180 x 180 avatars"

this is what u fucking get u bithc
Fun Shoe

tyang209 posted:

Totally confused by this compiler error. I'm using DrJava and Eclipse and I'm pretty sure it's an error with something within Dr Java.

Code Snippet



I can't use next() without getting this error and the program should compile. This should compile as I grabbed this off my course website as an example program and it did compile on Dr Java for Mac but I'm getting that ambiguous invocation error on my PC. Totally confused as to why. Could anyone drop some knowledge on me?

Post the entire code, including your import statements. And for gods sake, use the [code] BBcode, man.

EDIT: Also, on another note, you should probably do some error checking via a try/catch or calling hasNext().

pliable fucked around with this message at 10:08 on Nov 10, 2011

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