i have a block of code that is supposed to ask a question, get input THEN ask the next question. Not only does this code not wait for the first input, it does not allow me to perform the second input. I'm new to java and I have read the chapter on file inputs, repeatedly. However I still don't see why this error is occurring. The two String variables(pword, uname) where created outside of this section of code and the FileWriter and PrintWriter classes need to append data to a file is also present outside the loop as well. Do i need to open and close the file before and after each input? that seems excessive.
for (index = 0; index <= arraylength; index ++)
{
System.out.println("Enter a username..");
uname = keyboard.nextLine();
outputFile.println(uname);
System.out.println("Enter a password..");
pword = keyboard.nextLine();
outputFile.println(pword);
}
this is the full program, updated with the suggestions to use "keyboard.next();" instead of "keyboard.nextLine();"
in my IDE i still get the error to my console
Enter a username.. Enter a password..
when i want it to ask for the username, then take my input, then ask for the password.
import java.util.Scanner;
import java.io.*;
public class Register {
public static void main (String [] args) throws IOException
{
int index ;
int arraylength;
String uname, pword;
Scanner keyboard = new Scanner(System.in);
//create users
System.out.println("How many users would you like to create");
arraylength = keyboard.nextInt();
/*
create a filewriter object, name the registration database, and
create the file using the name of the database.
Pass the filewriter object to the print writer object as an arg
*/
FileWriter fwriter = new FileWriter("database.txt", true);
PrintWriter outputFile = new PrintWriter (fwriter); //constructor
//loop user creation
for (index = 0; index <= arraylength; index ++)
{
keyboard = new Scanner(System.in);
System.out.println("Enter a username..");
uname = keyboard.next(); // create string object
outputFile.println(uname);
keyboard = new Scanner(System.in);
System.out.println("Enter a password..");
pword = keyboard.next();
outputFile.println(pword);
//creat the new file with filewriter so the file is not erased
//write to the new file with printwriter object
}
outputFile.close();
}
}