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
1337JiveTurkey
Feb 17, 2005

OK. The easiest way to do this is to break it up into two problems. First you need to distinguish where the start and end of a parseable command is. If the user is pressing enter after each command, then you really want to just get the next line rather than searching for tokens. There are several ways to do this, but one of the simpler ways is to just take System.in and then wrap it in a InputStreamReader and then a BufferedReader like so:

code:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in);
String nextLine = reader.readLine();
while (nextLine != null) {
  // The split command splits the line into individual tokens
  String[] tokens = nextLine.split("\\s+");
}
After that as the code shows, you can split the individual line up into parts and then you have the number of tokens beforehand and you can look at the first token to tell how many tokens you should expect.

Adbot
ADBOT LOVES YOU

lamentable dustman
Apr 13, 2007

🏆🏆🏆

rileylolz posted:

For class, we've been assigned to make an 8x8 board for various pieces to move around on. I've run into a problem with user input, specifically dealing with how to handle tokens. I'm using Scanner to break up the input, but the problem is the largest command will have 5 tokens and the shortest will only have one. The way it's set up now is that it needs a command that will use all 5 tokens or else it crashes.

code:
		while (sc.hasNext())
		{
			cmd = sc.next();
			i = sc.nextInt();
			j = sc.nextInt();
			token4 = sc.next();
			token5 = sc.next();
			break;
		}
How can I break this up so it checks to see if there are any more tokens in the string before crashing? I tried if(sc.hasNext()) after each one, but it didn't work.

I'm still fairly new to java, any help would be appreciated.

And just an example of what the user input would look like:
"create 4 3 fast flexible" with fast and flexible being different types of pieces. It works fine with a command like that, but crashes with a command like "print"

Lazy way would be to catch the exception and ignore it. The more proper way would be to have a count=0 outside of the switch statement. Then have a switch statement based off what count it is. After the switch increment the count.

You could probably get rid of the loop also with a series of ifs as well. You would check hasNext() and if true whatever equals next()

Brain Candy
May 18, 2006

Slimy posted:

In C++, I'd just have the implementation of getArrayListByType() return a pointer to foo and bar, which I could dereference.

Why bother to use a switch at all? Why don't you use a List<List<Message>>?

zootm
Aug 8, 2006

We used to be better friends.

Slimy posted:

The problem is in clearMessageArray() (check the comment). What I'm really looking for is an implementation of getArrayListByType() that will actually return me something that can be used to modify foo and bar.

In C++, I'd just have the implementation of getArrayListByType() return a pointer to foo and bar, which I could dereference.
As mentioned before you can't really do this in Java, however if you want a lookup table you'd probably be better off just using a data structure that represents what you want; in this case a list (for ints) or a Map<Type,List<Message>> (with a more descriptive enum key if possible - EnumMap would be good at this).

You're just encountering problems because you're attempting to solve the problem using methods idiomatic to C++, it's easily done!

Here's another implementation:
code:
public enum MessageType { FOO, BAR }

private static final Map<MessageType,List<Message>> listsByType = new EnumMap<MessageType,List<Message>>();

// In initialisation or whatever
listsByType.put( MessageType.FOO, new ArrayList<Message>() );
listsByType.put( MessageType.BAR, new ArrayList<Message>() );

/* fill foo and bar with Messages */

private List<Message> getListByType(MessageType type) {
   return listsByType( type );
}

public void clearMessageArray(MessageType type) {
   listsByType.put( type, new ArrayList<Message>() );
}

Brain Candy
May 18, 2006

Since it's static anyway... :
code:
public enum MessageType {
   FOO,BAR;
   
   private final List<Message> messages = new ArrayList<Message>();
}

public void clearMessageArray(MessageType type) {
   type.messsages.clear();
}
:q:

Pivo
Aug 20, 2004


Hi guys, I'm using Eclipse at work to do Java web dev.

The previous programmer left a lot of useless (and now abandoned) poo poo going to System.out. There are thousands of lines of System.out to search through, many of them are valid. But there are also some annoying ones that happen without fail every 10-15 seconds and result in 09:37:45,585 INFO [STDOUT] null. Very useful. Is there any way I can set a breakpoint on System.out.println?

I figure if I had the JDK source code loaded, I could set a breakpoint on entry to that method, but I don't.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

Pivo posted:

Hi guys, I'm using Eclipse at work to do Java web dev.

The previous programmer left a lot of useless (and now abandoned) poo poo going to System.out. There are thousands of lines of System.out to search through, many of them are valid. But there are also some annoying ones that happen without fail every 10-15 seconds and result in 09:37:45,585 INFO [STDOUT] null. Very useful. Is there any way I can set a breakpoint on System.out.println?

I figure if I had the JDK source code loaded, I could set a breakpoint on entry to that method, but I don't.

You can't Ctrl+Click into the method and see its source? I just have the standard 1.6 JDK and plain-jane Eclipse 3.4 and I can enter all of Java's standard classes.

Pivo
Aug 20, 2004


TRex EaterofCars posted:

You can't Ctrl+Click into the method and see its source? I just have the standard 1.6 JDK and plain-jane Eclipse 3.4 and I can enter all of Java's standard classes.

Nope... Maybe the source search path isn't correct. Let me see if the files are actually on my system.

Lysidas
Jul 26, 2002

John Diefenbaker is a madman who thinks he's John Diefenbaker.
Pillbug

Slimy posted:

The problem is in clearMessageArray() (check the comment). What I'm really looking for is an implementation of getArrayListByType() that will actually return me something that can be used to modify foo and bar.

In C++, I'd just have the implementation of getArrayListByType() return a pointer to foo and bar, which I could dereference.
getArrayListByType() does return a reference that you can modify. Reassigning it, though, doesn't do anything.

What's wrong with doing
code:
getArrayListByType(whatever).clear();
?


EDIT:

Pivo posted:

Nope... Maybe the source search path isn't correct. Let me see if the files are actually on my system.
Make sure (in the global setup) that Eclipse is using the JDK instead of the JRE. One comes with source, one doesn't. I've found that new Eclipse installations usually default to a JRE.

Pivo
Aug 20, 2004


Lysidas posted:

EDIT:
Make sure (in the global setup) that Eclipse is using the JDK instead of the JRE. One comes with source, one doesn't. I've found that new Eclipse installations usually default to a JRE.

Heh, was just coming back to say I did exactly this and it fixed it.

Thanks

lmao zebong
Nov 25, 2006

NBA All-Injury First Team
i haven't written code for a couple months, so forgive me if im doing something incredibly stupid. what im trying to do is populate an array with all different random numbers. here is my code:
code:
	
public void populateArray()
{
        Random generator = new Random();
	int index = 0;
		
	while(index < 10)
	{	
		int rnd = generator.nextInt(10) + 1;
	
		if( !includes(array, rnd) );
		{
			array[index] = rnd;
			index++;
		}
	}
}
	
public boolean includes(int array[], int number)
{
	int index = 0;
	for(int i = 0; i < array.length; i++)
	{
		 if(array[i] == number)
		 {
			 return true;
		 }
	}
	return false;
}
however, the output is still giving me repeats inside my array. by using print statements, it looks like regardless of what includes() returns, index is incremented regardless and the number is added to the array. what am i doing wrong?

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
code:
		if( !includes(array, rnd) );
Look at that line very closely.

lmao zebong
Nov 25, 2006

NBA All-Injury First Team
god. loving. damnit. thanks man.

1337JiveTurkey
Feb 17, 2005

That can be painfully slow if the number of items increases much beyond where it is. If you're looking for a shuffled list of numbers, then this should be what you need:
code:
List<Integer> shuffled = new ArrayList<Integer>();
for (int i = 0; i < length; i++) {
  shuffled.add(i+1);
}
Collections.shuffle(shuffled);

Pivo
Aug 20, 2004


Lysidas posted:

EDIT:
Make sure (in the global setup) that Eclipse is using the JDK instead of the JRE. One comes with source, one doesn't. I've found that new Eclipse installations usually default to a JRE.

As a follow-up, it looks like a class called Logger intercepts stdout so the JDK println is never even called. And, of course, I don't have the source code for the logger. Honestly I've never done webdev in Java before this, anyone have any good links for a quick rundown of logging systems in JBoss? Nearly half of our server logs are [STDOUT] null and the logger logging messages about the logger.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

Pivo posted:

As a follow-up, it looks like a class called Logger intercepts stdout so the JDK println is never even called. And, of course, I don't have the source code for the logger. Honestly I've never done webdev in Java before this, anyone have any good links for a quick rundown of logging systems in JBoss? Nearly half of our server logs are [STDOUT] null and the logger logging messages about the logger.

Do you know the package Logger is in? I'll bet it's log4j or Apache Commons' Logger.

Pivo
Aug 20, 2004


TRex EaterofCars posted:

Do you know the package Logger is in? I'll bet it's log4j or Apache Commons' Logger.

You're quick on the draw mang. I'll have to get back to you on that, but I know it's not log4j from my experience with red5.


The "logger logging about the logger" is like this:
code:
2008-02-28 17:57:51,703 DEBUG [com.arjuna.ats.arjuna.logging.arjLogger] Periodic recovery - second pass <Thu, 28 Feb 2008 17:57:51>
2008-02-28 17:57:51,703 DEBUG [com.arjuna.ats.arjuna.logging.arjLogger] AtomicActionRecoveryModule: Second pass
2008-02-28 17:57:51,703 DEBUG [com.arjuna.ats.txoj.logging.txojLoggerI18N] [com.arjuna.ats.internal.txoj.recovery.TORecoveryModule_6] - TORecoveryModule - second pass
2008-02-28 17:57:51,703 DEBUG [com.arjuna.ats.jta.logging.loggerI18N] [com.arjuna.ats.internal.jta.recovery.info.secondpass] Local XARecoveryModule - second pass
Looks like this was a bug report for the JBoss guys and all they did was lower the severity of the messages, but I didn't set up our production, I don't know where the minimal severity is set. When did simple logs become so complicated!

I'm not at work right now so I don't have any additional info, but I sure would like to clean up our logs since I'm the one who sifts through 'em.

1337JiveTurkey
Feb 17, 2005

JBoss uses the Log4J logging framework. You can find the configuration file for it in the config directory of your server. If you're just looking for calls to System.out, just make a subclass of PrintStream that wraps the real/current System.out and sends everything to it instead. Remember: System.out isn't final so you can replace it with whatever you want. You can set a breakpoint there or you can just create a Throwable, getStackTrace() it and get the second element. That's got the class, method, file name and line number (if you compiled those in) for whatever printed to System.out.

edit: If you find the Log4J config file, you can filter specific packages IIRC so you can at least shut those ones that constantly spam poo poo in debug mode up.

Pivo
Aug 20, 2004


Hah. Remote Desktop to the rescue... It IS log4j!

Thanks a lot. Coming from primarily PHP and Python, stuff's so different over here!

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.
Hey Pivo, a really good Java tip I have for you is to ALWAYS google for the names of classes or messages displayed when programs throw stack frames. I just googled for "com.arjuna.ats.arjuna.logging.arjLogger" and found a whole bunch of people who asked the same question you did about excessive logging, right on the first page.

Pivo
Aug 20, 2004


Hey TRex, guess what page of Google I pulled that log-quote from? Oh and by the way, my question was only tangentially related to the topic of those particular log entries!

I work for a company that provides online tutoring to children in need. We tutor adults, as well. Would you be interested in learning about our services? Our English tutors are phenomenal!

Pivo fucked around with this message at 04:27 on Feb 21, 2009

Slimy
Jun 13, 2001
Thanks for the responses. As to why the code was written the way it was, I have no idea. I just went in to fix a bug, and was hoping to modify as little code as possible (which would have been the method I tried to use, had there been a Java equivalent). However, I ended up biting the bullet, and re-implementing it as a List of ArrayList<Message>'s.

And, Jesus Christ, did that simplify the class. Nearly every method in that class has a switch statement based on 'type' (of which there were 5, not the 2 I had in my example), all with nearly identical code.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

Pivo posted:

Hey TRex, guess what page of Google I pulled that log-quote from? Oh and by the way, my question was only tangentially related to the topic of those particular log entries!

I work for a company that provides online tutoring to children in need. We tutor adults, as well. Would you be interested in learning about our services? Our English tutors are phenomenal!

Kid, I can't read your mind. I thought those were the actual log messages your program generated. Maybe if you were concise about the problem, we wouldn't be having this little exchange.

In any event, gently caress you. If you're gonna act like a noob and then get all bent out of shape when someone gives you a tip, perhaps you should learn how to solve simple problems like this on your own.

Kerris
Jul 12, 2006
Don't you fucking dare compliment a woman's voice on the forums, you fucking creepy stalker.

Pivo posted:

Hey TRex, guess what page of Google I pulled that log-quote from? Oh and by the way, my question was only tangentially related to the topic of those particular log entries!

I work for a company that provides online tutoring to children in need. We tutor adults, as well. Would you be interested in learning about our services? Our English tutors are phenomenal!
I bet you that most people who read your post thought that those logs were from your very own program.

torneh
Jul 12, 2006
Hello all,

I'm having some difficulties with some extremely basic Java programming.

This is regarding creating your own class and using a driver with it.

Here's a zip containing all the files regarding this program...

http://bioshacker.googlepages.com/project2.zip

I don't even know if I have my class (GiftOrder.java) completed correctly. It compiled correctly, but I'm just not sure if I did calcSubTotal, calcTax, or calcOrderTotal correctly.

I definitely have no clue what question 5 and 6 (within Project2.java) want from me. What's the command to get the invoice to display? I can't figure it out. Ugh.

I'll post the code here as well. The first code is the class, GiftOrder.java, and the second code is the driver, Project2.java.

Thanks to anyone who is willing to help.

code:
/**********************************************************************
 * File name: GiftOrder.java
 * Project name: Project2
 *
 * Creator's name and email:   | [email]bioshacker@gmail.com[/email]
 * Course-Section: CSCI1250-201
 * Creation Date  : Feb 14, 2009
 * Date of last modification: Feb 14, 2009
 */
 
import java.text.DecimalFormat; //necessary for displaying currency amounts to 2 decimal places
 
/**********************************************************************
  * Name:  Wes Edens
  * Class Name: GiftOrder<br>
  * Class Purpose: To keep track of the various aspects of an order, calculating the various costs and creating an invoice.<br>
  *
  * <hr>
  * Date created: Feb 14, 2009<br>
  * Date last modified: Feb 14, 2009
  * @author Kellie Price
  */
  
public class GiftOrder
{
	// ********************** CLASS ATTRIBUTES ***************************

private int numBoxesOfBows;
private int numBoxesOfRibbons;
private int numRollsWrappingPaper;
private char shippingOption;



	
	// ********************** CONSTRUCTOR(S) *****************************
	
	/**********************************************************************
	 * Method Name: GiftOrder <br>
	 * Method Purpose: no-arg constructor to initialize all class attributes <br>
	 *
	 * <hr>
	 * Date created: Feb 14 2009<br>
	 * Date last modified: Feb 14, 2009
	 *
	 * <hr>
	 * Notes on specifications, special algorithms, and assumptions:
	 *   uses calls to the set methods to initialize the class attributes
	 *
	 * <hr>
	 */

	public GiftOrder()
	{
		numBoxesOfBows = 0;
		numBoxesOfRibbons = 0;
		numRollsWrappingPaper = 0;
		shippingOption = 'P';
	}



	 // ************************* SETTERS **********************************
	
	/**********************************************************************
	 * Method Name: setNumBoxesOfBows <br>
	 * Method Purpose: sets the numBoxesOfBows attribute to value passed in the parameter <br>
	 *
	 * <hr>
	 * Date created: Feb 14, 2009<br>
	 * Date last modified: Feb 14, 2009
	 *
	 * <hr>
	 * Notes on specifications, special algorithms, and assumptions:
	 *   n/a
	 *
	 * <hr>
	 *   @param numberOrdered - the number of boxes of bows
	 */

	public void setNumBoxesOfBows(int newNumBoxesOfBows)
		{
			numBoxesOfBows = newNumBoxesOfBows;
		}



	 
	 

	 
	/**********************************************************************
	 * Method Name: setnumBoxesOfRibbons <br>
	 * Method Purpose: sets the numBoxesOfRibbons attribute to value passed in the parameter <br>
	 *
	 * <hr>
	 * Date created: Feb 14, 2009<br>
	 * Date last modified: Feb 14, 2009
	 *
	 * <hr>
	 * Notes on specifications, special algorithms, and assumptions:
	 *   n/a
	 *
	 * <hr>
	 *   @param numberOrdered - the number of boxes of ribbons
	 */

	
	public void setNumBoxesOfRibbons(int newNumBoxesOfRibbons)
		{
			numBoxesOfRibbons = newNumBoxesOfRibbons;
		}

	
	
	
	
	
	/**********************************************************************
	 * Method Name: setNumRollsWrappingPaper <br>
	 * Method Purpose: sets the numRollsWrappingPaper attribute to value passed in the parameter <br>
	 *
	 * <hr>
	 * Date created: Feb 14, 2009<br>
	 * Date last modified: Feb 14, 2009
	 *
	 * <hr>
	 * Notes on specifications, special algorithms, and assumptions:
	 *   n/a
	 *
	 * <hr>
	 *   @param numberOrdered - the number of rolls of wrapping paper
	 */

	
	
	
	public void setRollsWrappingPaper(int newRollsWrappingPaper)
		{
			numRollsWrappingPaper = newRollsWrappingPaper;
		}

	
	
	
	
	
	/**********************************************************************
	 * Method Name: setShippingOption <br>
	 * Method Purpose: sets the shippingOption attribute to value passed in the parameter <br>
	 *
	 * <hr>
	 * Date created: Feb 14, 2009<br>
	 * Date last modified: Feb 14, 2009
	 *
	 * <hr>
	 * Notes on specifications, special algorithms, and assumptions:
	 *   n/a
	 *
	 * <hr>
	 *   @param option - the selected shipping option
	 */

	
	public void setShippingOption(char newShippingOption)
		{
			shippingOption = newShippingOption;
		}
	
	
	
	
	
	// ************************** GETTERS *********************************
	
	/**********************************************************************
	 * Method Name: getNumBoxesOfBows <br>
	 * Method Purpose: returns the value stored in the numBoxesOfBows attribute <br>
	 *
	 * <hr>
	 * Date created: Feb 14, 2009<br>
	 * Date last modified: Feb 14, 2009
	 *
	 * <hr>
	 * Notes on specifications, special algorithms, and assumptions:
	 *   n/a
	 *
	 * <hr>
	 *   @return int - the number of boxes of Bows
	 */

	public int getNumBoxesOfBows()
	{
		return numBoxesOfBows;
	}
	
	
	
	
	
	
	/**********************************************************************
	 * Method Name: getNumBoxesOfRibbons <br>
	 * Method Purpose: returns the value stored in the numBoxesOfRibbons attribute <br>
	 *
	 * <hr>
	 * Date created: Feb 14, 2009<br>
	 * Date last modified: Feb 14, 2009
	 *
	 * <hr>
	 * Notes on specifications, special algorithms, and assumptions:
	 *   n/a
	 *
	 * <hr>
	 *   @return int - the number of boxes of ribbons
	 */

	public int getNumBoxesOfRibbons()
	{
		return numBoxesOfRibbons;
	}
	
	
	
	
	
	
	
	/**********************************************************************
	 * Method Name: getNumRollsWrappingPaper <br>
	 * Method Purpose: returns the value stored in the numRollsWrappingPaper attribute <br>
	 *
	 * <hr>
	 * Date created: Feb 14, 2009<br>
	 * Date last modified: Feb 14, 2009
	 *
	 * <hr>
	 * Notes on specifications, special algorithms, and assumptions:
	 *   n/a
	 *
	 * <hr>
	 *   @return int - the number of rolls of Wrapping Paper
	 */

	
	
	
	public int getNumRollsWrappingPaper()
	{
		return numRollsWrappingPaper;
	}
	
	
	
	
	
	
	
	
	/**********************************************************************
	 * Method Name: getShippingOption <br>
	 * Method Purpose: returns the value stored in the shippingOptions attribute <br>
	 *
	 * <hr>
	 * Date created: Feb 14, 2009<br>
	 * Date last modified: Feb 14, 2009
	 *
	 * <hr>
	 * Notes on specifications, special algorithms, and assumptions:
	 *   n/a
	 *
	 * <hr>
	 *   @return char - the shipping option
	 */

	
	
	public int getShippingOption()
	{
		return shippingOption;
	}
	
	
	
	
	
	// ******************** OTHER CLASS METHODS *************************
	
	/**********************************************************************
	 * Method Name: calcShipping <br>
	 * Method Purpose: calculates and returns the shipping cost<br>
	 *
	 * <hr>
	 * Date created: Feb 14, 2009<br>
	 * Date last modified: Feb 14, 2009
	 *
	 * <hr>
	 * Notes on specifications, special algorithms, and assumptions:
	 *   shipping charge is  based upon the selected shipping rate.  If an invalid shipping rate
	 *   has been selected, it will default to Priority shipping
	 *
	 * <hr>
	 *   @return double - the shipping charge
	 */

	public double calcShipping()
	{
		final double OVERNIGHT_RATE = 8.00; 	//cost for overnight shipping
		final double TWODAY_RATE = 6.00;		//cost for two-day shipping
		final double PRIORITY_RATE = 4.00;		//cost for priority shipping
		double shipCost;	//cost of shipping - assigned based on the selected rate
		
		//determine the rate based upon which shipping option was selected
		switch (shippingOption)
		{
			case 'O' : 	//overnight shipping
			case 'o' :
						shipCost = OVERNIGHT_RATE;
						break;
			case 'T' : 	//two-day shipping
			case 't' :
						shipCost = TWODAY_RATE;
						break;
			case 'P':	//priority
			case 'p':
			default:	//invalid option was selected -  will be given the priority shipping rate
						shipCost = PRIORITY_RATE;
						break;
		}//end switch (ShippingOption)
		
		return shipCost;
	}//end calcShipping
	
	
	
	/**********************************************************************
	 * Method Name: calcSubTotal <br>
	 * Method Purpose: calculates and returns the subtotal cost of the items - not including shipping <br>
	 *
	 * <hr>
	 * Date created: Feb 14, 2009<br>
	 * Date last modified: Feb 14, 2009
	 *
	 * <hr>
	 * Notes on specifications, special algorithms, and assumptions:
	 *  
	 *
	 * <hr>
	 *   @return double - the calculated sub total (not including shipping)
	 */

	public double calcSubTotal()
	{
		
		final double numBoxesOfBows = 10.00;
		final double numBoxesOfRibbons = 15.00;
		final double numRollsWrappingPaper = 5.00;
	
		return numBoxesOfBows + numBoxesOfRibbons + numRollsWrappingPaper;
	}	
	
	
	
	
	
	
	
	
	
	
	
	/**********************************************************************
	 * Method Name: calcTax <br>
	 * Method Purpose: calculates and returns the tax on the subtotal of the items - not including shipping <br>
	 * The tax rate is a constant 10%
	 * <hr>
	 * Date created: Feb 14, 2009<br>
	 * Date last modified: Feb 14, 2009
	 *
	 * <hr>
	 * Notes on specifications, special algorithms, and assumptions:
	 *
	 *
	 * <hr>
	 *   @return double - the calculated sales tax
	 */

	
	public double calcTax()
	{
		final double tax = 0.10;
		final double numBoxesOfBows = 10.00;
		final double numBoxesOfRibbons = 15.00;
		final double numRollsWrappingPaper = 5.00;
	
		return (numBoxesOfBows + numBoxesOfRibbons + numRollsWrappingPaper) * tax + (numBoxesOfBows + numBoxesOfRibbons + numRollsWrappingPaper) ;
	}	
	
	
	
	
	
	
	
	
	/**********************************************************************
	 * Method Name: calcOrderTotal <br>
	 * Method Purpose: calculates and returns the total, including shipping <br>
	 *
	 * <hr>
	 * Date created: Feb 14, 2009<br>
	 * Date last modified: Feb 14, 2009
	 *
	 * <hr>
	 * Notes on specifications, special algorithms, and assumptions:
	 *   order total is calculated as the subtotal + tax + shipping charge
	 *
	 * <hr>
	 *   @return double - the total cost (subtotal + tax + shipping)
	 */

	
	
	public double calcOrderTotal()
	{
		final double tax = 0.10;
		return shippingOption + (numBoxesOfBows + numBoxesOfRibbons + numRollsWrappingPaper) * tax + (numBoxesOfBows + numBoxesOfRibbons + numRollsWrappingPaper) ;
		}
	
	
	
	
	
	
	
	/**********************************************************************
	 * Method Name: createInvoice <br>
	 * Method Purpose: creates the invoice and returns it to be displayed by the calling method <br>
	 *
	 * <hr>
	 * Date created: Feb 14, 2009<br>
	 * Date last modified: Feb 14, 2009
	 *
	 * <hr>
	 * Notes on specifications, special algorithms, and assumptions:
	 *   creates the invoice as one String and returns the string to be displayed by the calling method
	 *
	 * <hr>
	 *   @return String - the invoice
	 */

	public String createInvoice()
	{
		//display dollar amounts to 2 decimal places
		DecimalFormat formatter = new DecimalFormat("##0.00"); 	
		
		//create a string to be returned containing the entire invoice
		String Invoice =   "\t2009 Gift ORDER INVOICE \n\n\n"
							+ "\n\t " + numBoxesOfBows + " Bows"
							+ "\n\t " + numBoxesOfRibbons + " Ribbons "
							+ "\n\t " + numRollsWrappingPaper + " Wrapping Paper"
							+ "\n\n"
							+ "\n\t Subtotal: $" + formatter.format(calcSubTotal())
							+ "\n\t Shipping: $" + formatter.format(calcShipping())
							+ "\n\t ______________"
							+ "\n\t Total Due: $" + formatter.format(calcOrderTotal())
							+ "\n\n\nThank you for placing your order!";
							
		return Invoice;
	}//end createInvoice
	
}//end GiftOrder class

	
code:
/**********************************************************************
 * File name: Project2.java
 * Project name: Project2
 *
 * Creator's name and email: Dr. Gene Bailey (c) Spring 2009  [email]baileyg@etsu.edu[/email]
 * Course-Section: CSCI1250-???
 * Creation Date  : Feb 14, 2009
 * Modified by:  PUT YOUR NAME HERE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
 * Date of last modification: Feb 14, 2009
 */
 
import java.text.DecimalFormat; //necessary for displaying currency amounts to 2 decimal places
import java.util.Scanner;

public class Project2
{
	public static void main(String[] args)
	{
		int iNumBows = 0;						//number of boxes of bows the user desires
		int iNumRibbons=0;						//number of boxes of ribbons the user desires
		int iRollsWrappingPaper=0;				//number of rolls of wrapping paper the user desires
		char cShippingOption;				//type of shipping user wants
		String strInput;						//string used to get character input from the user
		Scanner keyboard = new Scanner(System.in);
				//create a keyboard object to obtain user data from the keyboard

	//1. instantiate a Gift Order object here called   myOrder
	
	GiftOrder myOrder = new GiftOrder();	
		
	//2. Prompt the user with a welcome screen and let them know they can order bows, ribbons, and wrapping paper
	
	System.out.println("Hello, Welcome to my store! I specialize in bows, ribbons, and wrapping paper.");	
		
		
	//2. Get the number of boxes of bows user wants. Remember to prompt the user
	
	System.out.println("How many boxes of bows do you wish to purchase?");	
		iNumBows = keyboard.nextInt();
		
		
	//3. Get the number of boxes of ribbons the user wants. Remember to prompt the user
		
		System.out.println("How many boxes of ribbons do you wish to purchase?");	
		iNumRibbons = keyboard.nextInt();
		
		
	//4. Get the number of rolls of wrapping paper user wants. Prompt the user.
		
		System.out.println("How many boxes of wrapping paper do you wish to purchase?");	
		iRollsWrappingPaper = keyboard.nextInt();
		
	//What kind of shipping do you want?. I have written the code here for you.
		System.out.print("\n\nShipping options: "
						 +  "\n\n\t For Priority  (4.00)  enter P "
						 +  "\n\n\t For Two-Day   (6.00)  enter T "
						 +  "\n\n\t For Overnight (8.00)  enter O: ");
		strInput = keyboard.nextLine();
		strInput=keyboard.nextLine();
		cShippingOption=strInput.charAt(0);
		
	//5. Use the appropriate methods to set all of the values for the GiftOrder object instantianted above
		
		
		
		
		
	//6.  Display the invoice using the appropriate method of the GiftOrder object instantiated above.
	
		 myOrder.createInvoice();



		
	//7. Display a message to the user to thank them for shopping with us.
	
	
	
	
	
		}// end of main
}//end of Project2

Flamadiddle
May 9, 2004

Question 6 is just asking you to use the set methods for bows, ribbons and whatever to the iNumBows as captured from the user. Once these are run then the invoice can be calculated based on the class variables.

The calculateInvoice() method returns a string. You know how to output a string to screen, so just output the return value of calculateInvoice().

Vermillion
May 22, 2002
We have several different web applications at work in which we use custom tags. In each application, we have a tld file, and the associated java code.

The problem is that in a lot of cases, the tags are exactly the same across all the applications, so the code has been copied from application to application. I would like to have a single custom tag library that can be accessed from all the different applications. However, all the custom-tag documentation and examples that I find just show how to do it by sticking a tld into the web-inf folder of the application you're going to use it from.

I'm assuming that I can create an external tag library, since Struts and JSTL are external. Can anyone point me in the right direction to figure out how to do this?

8ender
Sep 24, 2003

clown is watching you sleep
We're going to move to Java for our web development here at the office and I've just finished taking a boatload of Java courses over the past two months. My head is spinning.

We're on Oracle for the backend and using JDeveloper as our IDE. What I can't decide on is the multitude of frameworks both for the model and view parts of our work.

For the front end I like JSF but right now it seems to involve a lot of "magic" and I'm not sure how flexible it'll be. We do some odd things in our web app right now because the data we need to show is complex. Struts looks neat but everyone seems to think its going by the wayside. Oracle ADF on JSF looks like ASP.

On the back end I'm still trying to figure out exactly what the difference is between TopLink and EJB 3.0, aside from a better GUI in JDeveloper for the former. Oracle BC looks neat but again gives me that unsettling feeling that we'd be locking into the Oracle game for another decade.

I'm really stuck here picking out the best. For some history, our web applications were all developed by myself using Oracle PL/SQL. Its a procedural language using packages compiled into the DB and its required me to hand build pretty much everything from scratch, including a sort of homebrew MVC framework. I feel like some sort of old timey watch maker compared to the massive amount of tools that JavaEE is offering.

Any ideas?

Ghotli
Dec 31, 2005

what am art?
art am what?
what.
I recently spent some time trying to figure this out for myself. In the end I decided to go with Spring and Hibernate as the frameworks I was going to learn. As far as I can tell it looks like Spring solves a lot of the problems inherent in ejb3. Just about everywhere I looked hibernate had much more adoption than toplink. The main reason for my decision is the speed at which development could occur with spring and the fact that both products seem to have a large following out there on the net. Basically I know I can get help with hibernate. Toplink? Not so much.

Edit: I've only scratched the surface of the available java frameworks. I come from a ruby on rails background where development speed, ease of use, and the community are a big deal. I looked for these qualities when delving in to the java world.

Ghotli fucked around with this message at 02:22 on Mar 4, 2009

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

Ghotli posted:

Edit: I've only scratched the surface of the available java frameworks. I come from a ruby on rails background where development speed, ease of use, and the community are a big deal. I looked for these qualities when delving in to the java world.

I'm gonna sound like a broken record but Grails is Java's answer to ROR... unless you just want to run ROR on JRuby.

Ghotli
Dec 31, 2005

what am art?
art am what?
what.
I've actually read quite a bit about grails and jruby and in my opinion both technologies just aren't mature enough yet. I've tried my hand at both and it seemed like I couldn't find help when I ran into road blocks. Either the documentation was shotty (or missing) or the blog and irc communities of people actively hacking away and solving problems in each framework were too small to yield good google results.

Frankly I think both technologies will be great when they get more large scale support. To a certain extent this has already happened with jruby. The documentation has been much better since Sun decided to invest money in it's development. With the upcoming releases of jruby 1.2, rails 2.3, and ruby 1.9 it's looking like each project has done alot to support the others. I think this will in turn foster a larger community of people using the technology. I've been considering trying my hand at deploying some of my apps to glassfish or jboss. I tried this about 8 months ago and ran into a ton of problems. I hear it's much easier these days.

In the end I went with spring because of these kinds of shortcomings. It seemed like it had the most active community around one of the more well thought out modern java frameworks. That and I found lots of job postings looking for spring/hibernate experience. It seemed like a worthy framework to invest in these days. Not something that's going to go away anytime soon.

8ender
Sep 24, 2003

clown is watching you sleep
Thank you for the feedback. Assuming that I'd have to stick with JDeveloper and lie close to the warm bosom of Oracle approved technologies, which would you choose for the view: JSF or Struts+JSP?

JulianD
Dec 4, 2005
I'm writing a program which is supposed to read a "maze" of characters in from a file and try to navigate it. The maze has two different character types, one of which is considered a valid path, the other a "wall". I've written the entire program, but when I go to test it, the method I wrote to navigate the maze doesn't do what I need it to; I know this because when a cell in my maze array has been visited, the value stored there is replaced by a 3, and at the end, if the cell is part of the valid path from the top left corner to the bottom right corner, the value stored in that cell is supposed to be replaced by a 7 (all the cells in the valid path become 7 via backtracking). The code for the navigating method and my main method are below.

code:
// Begins traverseMaze to navigate our maze array
  public boolean traverseMaze(int rows, int cols)
  {
    // The if statement determines if a wall is present in the cell
    // or if the cell has already been visited
    if (mazeArray[rows][cols] == wall1 || mazeArray[rows][cols] == 3)
    {
      mazeArray[rows][cols] = '3';
      return false;
    }
    // If our current location is the final cell of the array, we're done.
    else if (mazeArray[rows][cols] == mazeArray[numrows - 1][numcols - 1])
    {
      mazeArray[rows][cols] = '7';
      return true;
    }
    // If the cell is a path, the method will attempt to move on to
    // the next cell one row down.
    else if (mazeArray[rows][cols] == path1)
    {
      // The if statement verifies that the one row down is in our array
      // bounds.
      if (rows + 1 <= numrows - 1)
      {
        traverseMaze(rows + 1, cols);
      }
    }
    // If moving down one row fails, we try moving one column to the right.
    else if (traverseMaze(rows + 1, cols) == false)
    {
      // The if statement verifies that one column to the right is in our 
      // array bounds.
      if (cols + 1 <= numcols)
      {
        traverseMaze(rows, cols + 1);
      }
    }
    // If moving one column to the right fails, we try moving one row up.
    else if (traverseMaze(rows, cols + 1) == false)
    {
      // The if statement verifies that one row up is in our array bounds.
      if (rows - 1 >= 0)
      {
        traverseMaze(rows - 1, cols);
      }
    }
    // If moving one row up fails, we try moving one column left.
    else if (traverseMaze(rows - 1, cols) == false)
    {
      // The if statement verifies that one column left is in our array bounds.
      if (cols - 1 >= 0)
      {
        traverseMaze(rows, cols - 1);
      }
    }
    // If everything fails, there is no path.
    else
    {
      return false;
    }
    
    if (mazeArray[rows][cols] == path1)
    {
      return true;
    }
    else
    {
      return false;
    }
  }
  
  public static void main(String[] args) throws IOException
  {
    numrows = 5;
    numcols = 5;
    wall1 = 'A';
    path1 = 'B';
    
    Maze m1 = new Maze(5, 5, 'A', 'B');
    
    m1.fillMaze();
    
    m1.printMaze();
    
    m1.traverseMaze(0, 0);
    
    System.out.println();
    
    m1.printMaze();
  }
I believe the problem lies in my if statements in the traverseMaze method. When I check to see if the value in the maze at a given index is a wall or a path, for example I wrote

code:
mazeArray[rows][cols] == wall1
but I believe the equivalency I've set up there is incorrect. When I run the program, the value in the cell of my array in the top left corner becomes 7, but nothing else does, and nothing is replaced by a 3, so it doesn't seem like the method is actually navigating anything. Does anyone have any insight?

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
First, you're checking if the value in the current cell is equal to the value in the final cell, not whether the coordinates are equal. Second, your algorithm is wrong for several reasons. Third, this function will overflow the stack on long solution paths, even if you patch the algorithm to work.

Digital Spaghetti
Jul 8, 2007
I never gave a reach-around to a spider monkey while reciting the Pledge of Alligence.
I'm working on an Android app for reading books that are encrypted text files.

The files are encoded using 256bit AES, however in the examples I can find, when opening the file they read the file bit by bit - and the app just sits there while loading the file (the file is around 600Kb)

I'm wondering, is there a more efficient way to do this?

code:
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bookview);
		setPreferences(this.getSharedPreferences("bookone", MODE_PRIVATE));
		setEncryptionKey(getPreferences().getString("encryption_key", ""));
		String m_StorageState = Environment.getExternalStorageState();
		if (m_StorageState.contentEquals(Environment.MEDIA_MOUNTED) && 
getEncryptionKey() != "") {
			
			try {
				InputStream fis = getAssets().open("book");
				byte[] foo = 
hexStringToByteArray(getEncryptionKey());
				SecretKeySpec secretKey = new SecretKeySpec(foo, 
ENCRYPTION_KEY_TYPE);
				Cipher decrypt = 
Cipher.getInstance(ENCRYPTION_METHOD);
				decrypt.init(Cipher.DECRYPT_MODE, secretKey);
				CipherInputStream cis = new CipherInputStream(fis, 
decrypt);
				
				Log.i("Cypher", cis.toString());
				String foo2 = "";
			    byte[] b = new byte[8];
			    int i = cis.read(b);
			    while (i != -1) {
			    	foo2 += new String(b);
			        i = cis.read(b);
			    }			    
			    TextView view = (TextView)findViewById(R.id.textview);
			    view.setText(foo2);
			    
			    cis.close();				
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NoSuchPaddingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvalidKeyException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		} else {
			new AlertDialog.Builder(OpenBook.this)
			.setTitle("SD Card Not Mounded")
			.setMessage("Currently I cannot access the SD card.  
Please check and try again")
			.setNeutralButton("Close", new DialogInterface.OnClickListener(){
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			}).show();
		}
		
		
	}

Moon Whaler
Jul 1, 2007

I have a question about Java nanoTime. I'm trying to use it to measure the running time of some code and most of the time it returns a value around 130,000, but sometimes it returns values around 3,750,000 or -3,750,000. I'm running a dual core processor on windows and my only theory is that the dual core is messing up the nanoTime call somehow. Any ideas on what is happening/how to fix it?

dancavallaro
Sep 10, 2006
My title sucks

Moon Whaler posted:

I have a question about Java nanoTime. I'm trying to use it to measure the running time of some code and most of the time it returns a value around 130,000, but sometimes it returns values around 3,750,000 or -3,750,000. I'm running a dual core processor on windows and my only theory is that the dual core is messing up the nanoTime call somehow. Any ideas on what is happening/how to fix it?

nanoTime makes no guarantees about the *accuracy* of the time, only the *precision*. Meaning, you can't use System.nanoTime() to actually get an accurate measure of the current time, but the difference between two calls to nanoTime is the most precise elapsed time measurement possible in Java.

Moon Whaler
Jul 1, 2007

dancavallaro posted:

nanoTime makes no guarantees about the *accuracy* of the time, only the *precision*. Meaning, you can't use System.nanoTime() to actually get an accurate measure of the current time, but the difference between two calls to nanoTime is the most precise elapsed time measurement possible in Java.

Yeah but telling me my program finishes 3ms before it starts seems a little off

Edit: Yeah, i'm subtracting the time before from the time after, it just sometimes gives negative results

Moon Whaler fucked around with this message at 06:17 on Mar 5, 2009

a cat
Aug 8, 2003

meow.
I'm trying to write a program which can deal out five card poker hands to two players, evaluate them according to the rules of poker and determine the winner. I don't really care about optimization or anything, I just want it to work and not contain any programming atrocities. I realize there are some extremely efficient/complex ways to do this better, but I'm doing it as a learning project.

I'm having a real hard time getting it to determine the winner when two hands are the same rank and it comes down to kickers to determine the winner. I'm having trouble coming up with even a gross brute force type algorithm to do all this.

Here are two of the classes I'm having trouble with:
http://pastebin.com/m2d9aca3d

I'm really new at programming and especially new at java. I'm not really sure what the best ways set things up are when it comes to using class methods or object methods and all that.

Any help would be greatly appreciated!

Adbot
ADBOT LOVES YOU

csammis
Aug 26, 2003

Mental Institution

Moon Whaler posted:

Yeah but telling me my program finishes 3ms before it starts seems a little off

Edit: Yeah, i'm subtracting the time before from the time after, it just sometimes gives negative results

Is it possible that the data type you're using to store the nanoTime result (or the subtraction result) is overflowing and wrapping?

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