
-----------------------------------
Sevenheartz
Thu Feb 05, 2009 9:41 pm

Working with Do while loops
-----------------------------------
Alright so... I haven't done ANY Java for an entire year so I've basically forgotten everything. This is an Intro Assignment that was given to us to just recap things... but I have a slight issue that I'm not sure how to fix at all. The situation is simple enough: ask questions and have the user enter data... However, when I use a do while loop, it seems to skip the first part. Let me get the code first:

import java.util.Scanner;

/** The "IntroAssignment" class.
 * Enters the name, price, and quantity on hand for one or more products, as well
 * as to output the product with the highest total value and the overall total value.
 */

public class IntroAssignment {

	/**
	 * @param args
	 */
	public static void main(String

I've found that the problem is with String product = keyboard.nextLine();. When the user enters Y in order to loop the program, it simply skips this piece of code and leaves the product name as just " ", and starts with askin how much is the unit price. I thought of using keyboard.next();, but not only would that not read everything if there was a space involved (i.e. "Large Items"), but it'd give me an error if I tried anything with a space. Sorry if my explanation isn't too clear. To better explain this, here's the output I get:

Please enter the name of the next product: Item
Please enter the unit price for Item: $4
How many Item do you have on hand?: 4
You have 4 Item @ $4.00 for a total value of $16.00
Do you have anymore products? (y/n): y

Please enter the name of the next product: Please enter the unit price for : $

If anyone could help me out, it would be great. Thanks.

-----------------------------------
DemonWasp
Fri Feb 06, 2009 8:52 am

RE:Working with Do while loops
-----------------------------------
The problem here is that you're mixing calls to next() and nextLine() incorrectly. What happens is that when you type in the "Y" for "I have more items", it's only getting the next() token, which is "Y" without a newline character. When you call nextLine() to get the product name again, it sees that there's still some information available in the Scanner and returns the "remainder of the line", as per its specification...though in this case that means just the newline character.

You should change the next() call to be a nextLine(), but you will also need to add a call to nextLine() immediately after the nextInt() call, as you need that to suck up the newlines remaining in the Scanner after entering the integer.

-----------------------------------
Sevenheartz
Fri Feb 06, 2009 2:08 pm

RE:Working with Do while loops
-----------------------------------
Got it working now. Thanks for the help!
