Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Help with program

If someone could please help with this program. i get it to have me enter the first line of text and then ask for additional items correctly, but when i say for additional items it skips the next input line and goes straight to asking me if I want to enter more items again.

import java.io.*; // uses the java io library for the

import java.util.*; // BufferedReader class

public class week5_701

{

public static void main(String [] args)

{

PrintWriter outputStream=null;
try

{
outputStream= new PrintWriter(new FileOutputStream("shoppinglist.txt"));
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file shoppinglist.txt");
System.exit(0);
}
int items;
String line=null;
System.out.println("This program will put items in your shopping list");
Scanner keyboard= new Scanner(System.in);
boolean numbersLeft= true;
int moreitems=1;
while (numbersLeft)
{
System.out.println("Enter the next item");
line=keyboard.nextLine();
System.out.println("Would you like to enter more items, enter 1 for yes or 0 for no");
moreitems=keyboard.nextInt();
if (moreitems==0)
{
numbersLeft=false;
System.exit(0);
}
else
numbersLeft=true;
}

}
}
[1921 byte] By [mikem699] at [2007-11-11 10:25:01]
# 1 Re: Help with program
there is content in the buffer which is read as a "line" [the "Enter" which the user has pushed - the nextInt method will read only the int and leaves the rest of the "line" in the input buffer]. Try adding a keyboard.nextLine() statement after the nextInt() statement to flush the buffer.
nspils at 2007-11-11 22:31:31 >