How do I make my cancel button function - java

I realized I made an infinite loop and everytime I enter that loop, my cancel button doesn't function and the dialog box continuously pops up.
Here's the code
String buffer = " "; //Input a string into console
boolean badInput = true;
boolean badInput2 = true;
String idNum = ""; //ask for id number
String skill = ""; // ask for skill number
int skillInt = 0; // skill is an int
//prompt user for file location
File loc = new File(JOptionPane.showInputDialog(null, "Please provide the file location: "));
RandomAccessFile store = new RandomAccessFile(loc, "rw");
//prompt user for a command
String cmd = "start";
int recLocation = 0;
while(cmd.compareToIgnoreCase("end")!=0){ //stay in program (loop) until end command is given
cmd = JOptionPane.showInputDialog(null, "Please input a command (new, old or end): ");
//creating new entry
if(cmd.compareToIgnoreCase("new")==0){
while(badInput){ //keep them in loop until they give the input in the right format
idNum = JOptionPane.showInputDialog(null, "Please input an ID number (1 - 20): ");
// else JOptionPane.CANCEL_OPTIONsetDefaultCloseOperation(JOptionPane.EXIT_ON_CLOSE);
try{
//corresponding int for ID number, which becomes the record location
//if number is not 1-20, code below
recLocation = Integer.parseInt(idNum);
if(recLocation<1 || recLocation>20){
System.out.println("Please check that your number is between 1 and 20.");
}else{
badInput = false;
break;
}
}
catch(NumberFormatException NF){ // if input isnt a number
System.out.println("Please check that your number is in the correct format.");
}
}
//ask for names
String pName = JOptionPane.showInputDialog(null, "Please input a player name: ");
String tName = JOptionPane.showInputDialog(null, "Please input a team name: ");
//ask for skill level
while(badInput2){ //keep them in the loop until they give the input in the right format
skill = JOptionPane.showInputDialog(null, "Please input a skill level (0 - 99): ");
try{
//corresponding int for skill number, to check if in the right format
skillInt = Integer.parseInt(skill);
if(skillInt<0 || skillInt>99){
System.out.println("Please check that your number is between 0 and 99.");
}else{
badInput2 = false;
break;
}
}
catch(NumberFormatException NF){ //exception or error thrown if input is not in correct format
System.out.println("Please check that your number is in the correct format.");
}
}
String date = JOptionPane.showInputDialog(null, "Please input today's date (ex: 25Jun2014): ");
//formatting id number
if (idNum.length() < 2){
idNum = idNum+buffer;
}
//formatting player name
if (pName.length() > 26){
pName = pName.substring(0, 26);
} else {
while(pName.length() < 26){
pName = pName+buffer;
}
}
//formatting team name
if (tName.length() > 26){
tName = tName.substring(0, 26);
} else {
while(tName.length() < 26){
tName = tName+buffer;
}
}
//formatting date
if (date.length() > 9){
date = date.substring(0, 9);
} else {
while(date.length() < 9){
date = date+buffer;
}
}
//formatting skill
if (skill.length() < 2){
skill = skill+buffer;
}
//create full, identifying string
String fullRecord = idNum + " " + pName + tName + skill + " " + date;
store.seek((RECORD_LENGTH+2) * (recLocation-1));
store.writeUTF(fullRecord);
//reset booleans
badInput = true;
badInput2 = true;
}
//accessing old entry
if(cmd.compareToIgnoreCase("old")==0){
idNum = JOptionPane.showInputDialog(null, "Please input an ID number (1 through 20): ");
recLocation = Integer.parseInt(idNum);
store.seek((RECORD_LENGTH+2)*(recLocation-1));
String fullRecord = store.readUTF();
//interpret information from full string
try
{idNum = fullRecord.substring(0, 5);
String pName = fullRecord.substring(5, 31);
String tName = fullRecord.substring(31, 57);
skill = fullRecord.substring(57, 62);
String date = fullRecord.substring(62, 71);
System.out.println("ID: "+idNum+" NAME: "+pName+" TEAM: "+tName+" SKILL: "+skill+" DATE: "+date);
}
catch(StringIndexOutOfBoundsException S){
System.out.println("No record found at that location.");
}
}
// JOptionPane.showMessageDialog(null, "good bye");
}
Sorry if I didn't format this right. It's my first time. I was wondering how I could get the cancel button to exit the loop. I tried using if (cmd == null) System.exit(0); but that doesn't seem to function. I'm really novice at java and I have little experience so bear with me please.

First I'd suggest using equalsIgnoreCase as your String comparison instead of compareIgnoreCase: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equalsIgnoreCase(java.lang.String)
while(!cmd.equalsToIgnoreCase("end")) {
Then if one of the JOptionPane.showInputDialog()'s returns null which would mean they'd cancelled, you could have an if statement that sets the cmd string to "end". I think though you should probably try to simplify the loop because it's got a lot in it all in the one block. That makes it hard to debug.

Related

Error while using attempting to use replace(). Not sure if syntax is correct. Am I using it correctly, because right now my program will not run

I'm getting this error in Eclipse while trying to make a login system with the user data in another file. The error is "The method replace(String, String) is undefined for the type Scanner". Here is my source code:
import java.io.*;
import java.util.*;
import java.lang.*;
public class Login {
private Formatter x;
private Scanner y;
Scanner input = new Scanner(System.in);
public void addRecord() {
String permission;
int confirmFailed = 0;
int existsAlready = 0;
int invalid = 0;
String username = null;
System.out.println("The following questions will be entered into the user database.");
try {
do {
do {
System.out.println("What do you want the username to be?");
username = input.nextLine();
if(username.equalsIgnoreCase("create new account")) {
System.out.println("That user name is invalid, please try again.");
invalid = 1;
}
} while(invalid == 1);
y = new Scanner(new File("C:\\Users\\jonat\\OneDrive\\Documents\\eclipse-workspace\\Roll Die with Login\\Users\\" + username + ".txt"));
System.out.println("That username has already been taken. Please enter a different name.");
existsAlready = 1;
}while(existsAlready == 1);
y.close();
}catch(FileNotFoundException e) {
System.out.println("Thanks. What is your first name?");
String firstName = input.nextLine();
System.out.println("Thanks. What is your last name?");
String lastName = input.nextLine();
System.out.println("Ok " + firstName + ", what do you want your password to be?");
String password = input.nextLine();
System.out.println("Your entry has been created. Have fun!");
try {
x = new Formatter("C:\\Users\\jonat\\OneDrive\\Documents\\eclipse-workspace\\Roll Die with Login\\Users\\" + username + ".txt");
} catch (Exception e1) {
System.out.println("Error!");
}
x.format("Username: %s\nFirst Name: %s \nLast Name: %s \nPassword: %s \nPermissions: %s\nBalance: %s\n\n",username,firstName,lastName,password,"User", "20");
}
x.close();
}
public void mainMenuLogin(){
String loginUsername;
int invalid = 0;
String loginPassword;
do {
invalid = 0;
System.out.println("Welcome to the Casino. Please enter your username to log in. Type 'create new account' to make a new account");
loginUsername = input.nextLine();
if (loginUsername.equalsIgnoreCase("create new account")) {
addRecord();
}
try {
String passwordText;
y = new Scanner(new File("C:\\Users\\jonat\\OneDrive\\Documents\\eclipse-workspace\\Roll Die with Login\\Users\\" + loginUsername + ".txt"));
System.out.println("Username found! Please enter the password for the user: " + loginUsername);
loginPassword = input.nextLine();
y.nextLine();
y.nextLine();
y.nextLine();
passwordText = y.nextLine();
/*line with error*/ String password = y.replace("Password: ", "");
System.out.println(password);
if(password == "Password: " + loginPassword) {
System.out.println("Access Granted");
}
} catch (FileNotFoundException e) {
String yesNo;
invalid = 0;
System.out.println("Username not found in the database. Would you like to create a new account?");
yesNo = input.nextLine();
if(yesNo.equalsIgnoreCase("yes") || yesNo.equalsIgnoreCase("y")) {
invalid = 0;
addRecord();
} else {
if(yesNo.equalsIgnoreCase("no") || yesNo.equalsIgnoreCase("n")) {
System.out.println("Then please try again.");
invalid = 1;
}else {
System.out.println("You entered something invalid. Try again.");
invalid = 1;
}
}
}
}while(invalid == 1);
}
}
I am also looking for any other tips on how to make my code more efficient, but for now, I just need this program to run. My user file is named Wyld_Python.txt. Which I know, is a generic name, but please, no hate. The text file is as follows:
Username: Wyld_Python
First Name: Jonathan
Last Name: M
Password: Wyld_Python123
Permissions: Admin
Balance: 20
Thanks in advance for all the help!
Jonathan

addPerson (adds to an array) method isnt working, what's wrong?

I'm a student working on a project, and I have a method takes a Person, adds it to the array (Admits[]) and writes the array to file. The method currently does not do this, as the numSoFar value does not increase and the person is not saved to the array. (either that or i made a mistake in my tester class) I put coding of both classes below, and hope someone can point me in the direction of what i am doing wrong. As this is a school project please try not to be too specific actually, just tell me some suggestions as to why my coding may not work. I don't want to pass off someone else's work as my own; i just need a new set of eyes to see what I haven't.
Coding in my Database class
//adds a Person to the Database
public void addPerson(Person admit)
{
for(int i = 0; i < numSoFar; i++)//i = -1 when admit's alpabetical spot in Database has been located
{
if((i == numSoFar-1) || (i == numSoFar))//there is no Person in this index, so this is the end of the database
{
Admits[i] = admit;
numSoFar = numSoFar + 1;
}
else
{
if(Admits[i].getLN().compareTo(admit.getLN()) == -1)//last name comes before last name of Person at index i
{
Person current= Admits[i];
Admits[i] = admit;
while(i <= numSoFar)
{
Person next = Admits[i+1];
Admits[i+1] = current;
current = next;
i++;
}
numSoFar++;
}
else
{
if(Admits[i].getLN().equalsIgnoreCase(admit.getLN()))//admit and Person at index i have the same last name
{
if(Admits[i].getFN().compareTo(admit.getFN()) == -1)
{
Person current= Admits[i];
Admits[i] = admit;
while(i < numSoFar)
{
Person next = Admits[i+1];
Admits[i+1] = current;
current = next;
i++;
}
numSoFar++;
}
else
{
if(Admits[i].getFN().equalsIgnoreCase(admit.getFN())) //admit and Person at index i are the same person
{
Scanner in = new Scanner(System.in);
System.out.println("There is already a person with this name in the database.");
int c = 0;
while(c != 1 || c != 2)
{
System.out.println("If you would like to keep that person, enter '1', and if you would like to replace him/her with the person entered, enter 2.");
if(c == 2)
{
Admits[i] = admit;
}
}
}
}
}
}
}
}
this.writeToFile();
}
This is the coding to add a new person in my tester (i stopped after case 1
Person[] Admits = new Person[5000];
Database dB = new Database(Admits);
dB.fillFromFile();//fills array with info from text file
Scanner in = new Scanner(System.in);
String c = "0";
System.out.println("Hello, and thank you for using the Notre Dame admitted students friend-finder");
while(!c.equals("6")) //Menu for user to traverse, is exited when user enters a 6
{
System.out.println("Please pick the desired action from one of the options below and enter its number.");
System.out.println(" 1: Enter info for a new admitted student and check matches");
System.out.println(" 2: Change info for an admitted student already in the database");
System.out.println(" 3: Delete an admitted student from the database");
System.out.println(" 4: Log in as an admitted student to check matches");
System.out.println(" 5: View contact info for a certain person in the database");
System.out.println(" 6: Exit the program");
c = in.next();
switch(c)
{
case "1": //create new student and check matches
System.out.println("Enter your first name:");
String firstName = in.next();
System.out.println("Enter your last name:");
String lastName = in.next();
System.out.println("Enter your gender:");
String gen = in.next();
Person p = new Person(lastName, firstName, gen);
//String chracteristics
System.out.println("Are you an a. introvert or b. extrovert? (enter a or b):");
String traitIntroExtro = in.next();
while(!(traitIntroExtro.equalsIgnoreCase("a") || traitIntroExtro.equalsIgnoreCase("b")))
{
System.out.println("Invalid choice.Please re-enter your choice:");
traitIntroExtro = in.next();
}
if(traitIntroExtro.equalsIgnoreCase("a"))
{
p.setTraitIntroExtro("Introvert");
}
else
{
p.setTraitIntroExtro("Extrovert");
}
There above coding is basically repeated with different variables, but as there are many i will cut to the end of case 1
//facebook url to contact matches with
System.out.println("Please enter the url of your facebook profile page:");
String url = in.next();
p.setFacebookUrl(url);
dB.addPerson(p);
p.fillMatches(dB);
boolean first = dB.first();
if(first == true)//the database only has one person in it
{
System.out.println("You are currently the only person in the database.");
}
else//the database has atleast one person in it
{
System.out.println("Your top 2 most compatible people currently in the data base are:");
System.out.println(p.getMatches().getHead().getPerson() + ", who can be found at " + p.getMatches().getHead().getPerson().getFacebookUrl());
if(dB.getNumSoFar() == 2)
{
System.out.println("This is the only other person in the database.");
}
else
{
System.out.println(p.getMatches().getHead().getNextNode().getPerson() + ", who can be found at " + p.getMatches().getHead().getNextNode().getPerson().getFacebookUrl());
}
}
break;
Let's take a look at the case you're adding a Person to the end of the array (as you would if there were no entries yet):
for(int i = 0; i < numSoFar; i++)
{
if((i == numSoFar-1) || (i == numSoFar))
{
Admits[i] = admit;
numSoFar = numSoFar + 1;
}
else
{ /* doesn't matter */ }
}
Your for loop is never going to exit: if i = numSoFar-1, then each iteration of the for loop will increment both i and numSoFar by 1 and as such i < numSoFar will always be true.
Also, a comment mentions that i will be -1. I don't see any place where you assign i other than by deceleration and increment, so how could it ever be -1?
Finally, once you've got a working version I'd suggest posting your code over at the Code Review Stack Exchange. There are some non-functional issues out of scope for here on Stack Overflow that I'd point out there (such as the else { if (...) {...} } vs else if (...) {...} mentioned in the comments).

Java writing to file method writes nothing from arraylist

So here's the problem: File gets created, first line of text gets written, but the text within the logic loop of for>if>while doesn't write: PassengerSeats.println(nRowNum +cSeatLetter +" " +sPassengerName);
Here's the main method code in question:
else if (nMainChoice == 4) {
System.out.print("Please enter a flight number: ");
nMainFlight = input.nextInt();
input.nextLine();
System.out.println("Please enter a date of departure: ");
System.out.print("Month: (i.e For January, enter 1): ");
sMonth = input.nextLine();
System.out.print("Day: (i.e for the 15h, enter 15): ");
sDay = input.nextLine();
System.out.print("Year: (i.e for 2015, enter 15): ");
sYear = input.nextLine();
sDate = sMonth +"/" +sDay +"/" +sYear;
System.out.println(sDate);
PrintManifest newManifest = new PrintManifest(TicketsList,
FlyersList, nMainFlight, sDate, sMonth, sDay, sYear);
And here's the PrintManifest code it refers to:
public PrintManifest(ArrayList<Tickets> TicketsListing, ArrayList<Flyers> FlyersListing,
int nFlightID, String sFlightDate, String sFMonth, String sFDay,
String sFYear) throws Exception{
String sFlightManifest = "DataFiles/Manifest-nFlightID-sFMonth-sFDay-sFYear.txt";
File FlightManifest = new File(sFlightManifest);
PrintWriter PassengerSeats = new PrintWriter(FlightManifest);
PassengerSeats.println("Flight manifest for #" +nFlightID +" on " +sFlightDate);
for (nCount = 0; nCount < TicketsListing.size(); nCount++) {
if (nFlightID == TicketsListing.get(nCount).getFlightNumber()
&& sFlightDate == TicketsListing.get(nCount).getDate()) {
nRowNum = TicketsListing.get(nCount).getRow();
cSeatLetter = TicketsListing.get(nCount).getSeat();
while (TicketsListing.get(nCount).getFlyerID() != FlyersListing.get(nCountFly).getID()) {
nCountFly++;
} //End while loop
sPassengerName = FlyersListing.get(nCountFly).getFirst() +" "
+FlyersListing.get(nCountFly).getLast();
PassengerSeats.println(nRowNum +cSeatLetter +" " +sPassengerName);
} //End if
} //End for loop
PassengerSeats.close();
And a sample of the data it's pulling from TicketsList, which is already parsed and stored within an arraylist:
19836;1258;1359;1/2/15;A;5;A
19837;1215;1359;1/2/15;A;6;C
19838;1245;438;1/11/15;M;15;F
19839;1129;1014;1/5/15;M;17;F
19840;1139;703;1/11/15;M;14;C
19841;1353;689;1/11/15;F;3;D
19842;1296;1014;1/2/15;F;4;F
The boolean expression
sFlightDate == TicketsListing.get(nCount).getDate()
will always evaluate to false, which means nothing in your if statement will execute. The equals method should be used to evaluate string equality, like this
sFlightDate.equals(TicketsListing.get(nCount).getDate())
because it compares the contents of the strings. The == operator compares the object pointer, which will always be different in this case.

I can't print things into outfile

I can't seem to print what I want to print to the "transaction-list.txt" file. It did however create the file, but it prints nothing into it when the program is running. It suppose to worked seamlessly, just don't know why.
Here's my code:
final String acc_name= "Edward";
final int acc_num=123456;
final int acc_password=456789;
boolean quit = false;
int i;
PrintWriter outFile = new PrintWriter("transaction-list.txt");
outFile.println("HELLO!");
//to output timestamp
String timestamp = new java.text.SimpleDateFormat("MM/dd/yyyy h:mm:ss").format(new Date());
//System.out.print(timestamp);
//ask user to key in the account number and password and stores it into acc_num and acc_password variables
String stringAcc_num = JOptionPane.showInputDialog("Please enter your account number: ");
int Acc_num = Integer.parseInt(stringAcc_num);
String stringAcc_password = JOptionPane.showInputDialog("Please enter your account password: ");
int Acc_password = Integer.parseInt(stringAcc_password);
while (Acc_num != acc_num || Acc_password != acc_password){
for (i = 1; i <= 2; i++) {
String error = "YOUR ACCOUNT NAME AND YOUR ACCOUNT PASSWORD IS NOT A MATCH!!";
JOptionPane.showMessageDialog(null, error, "ALERT!", JOptionPane.ERROR_MESSAGE);
stringAcc_num = JOptionPane.showInputDialog("Please enter your account number: ");
Acc_num = Integer.parseInt(stringAcc_num);
stringAcc_password = JOptionPane.showInputDialog("Please enter your account password: ");
Acc_password = Integer.parseInt(stringAcc_password);
if (Acc_num == acc_num && Acc_password == acc_password)
break;
}//end for
if (i > 2){
JOptionPane.showMessageDialog(null, "NO MORE TIRES!", "ALERT!", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}//end if
}//end while
if (Acc_num == acc_num && Acc_password == acc_password){
//to read the data from port-account.txt file
Scanner readFile = new Scanner (new FileReader("port-account.txt"));
//to create a txt file name "transaction-list.txt"
//PrintWriter outFile = new PrintWriter("transaction-list.txt");
int current_balance = readFile.nextInt();
do{
//to pop out a message box
String stringOption = "1. Transfer an account" + "\n2. List recent transactions" + "\n3. Display account details and current balance" + "\n4. Quit" + "\nPlease enter a number base on the following options above.";
//to convert String into Int and stores it into "option"
int option = Integer.parseInt(JOptionPane.showInputDialog(null, stringOption, "Menu options", JOptionPane.INFORMATION_MESSAGE));
switch(option){
case 1:
String Case1 = JOptionPane.showInputDialog("Please enter an amount to transfer: ");
int amount_transfered = Integer.parseInt(Case1);
int newCurrent_balance = current_balance - amount_transfered; //data from port-account.txt - user input amount
JOptionPane.showMessageDialog(null, timestamp + "\nAmount transfered: $"+amount_transfered + "\nCurrent Balance: $"+newCurrent_balance, "Amount transfer complete!", JOptionPane.INFORMATION_MESSAGE);
//print it to transaction-list.txt file
outFile.println("Current Balance: $" + newCurrent_balance);
break;
case 2:
System.out.print("testing123! testing123!");
break;
case 3:
JOptionPane.showMessageDialog(null, "\nAccount Name: "+acc_name + "\nAccount Number: "+acc_num + "\nCurrent Balance: $"+current_balance, "Account Details", JOptionPane.INFORMATION_MESSAGE);
break;
case 4:
System.exit(0);
break;
default:
JOptionPane.showMessageDialog(null, "The number you have input is invalid. Please try again.", "ERROR", JOptionPane.INFORMATION_MESSAGE);
}//end switch
}/*end do*/ while (!quit); //repeat do loop while "!quit"(not quit).
outFile.close();
readFile.close();
}//end if
}
}
Call flush() on your outFile.
While the javadoc for Writer tells us that close() calls flush() first, the code in BufferedWriter#close() (which the underlying Writer of PrintWriter) doesn't actually flush the buffer (as opposed to BufferedWriter#flush()).
So in essence you only write to a buffer, which doesn't necessarily invoke writing to the actual OS output stream, which doesn't get flushed on writer closure.
Get rid of System.exit() call.
You should also note that if you exit via a System.exit() call (generally a bad practice) at one of your switch branches, even close() is not called.
NB
You could easily have solved this yourself if you created a Minimal, Complete and Verifiable Example first (which would in essence be a unit test for your file writing code). You also would not be downvoted for a long excerpt of code which is largely irrelevant to the problem you're experiencing.

Issue with writing and reading from file

I am in a situation where I want to write something(writing employee details with punchin & punchout) to a file and read it back(to show as a report of who all the employees punchedin & punchedout).
package Test;
import java.io.*;
import java.text.*;
import java.util.*;
public class Test {
public static void main(String[] args) throws IOException {
String lastName = "";
String firstName = "";
String choice = "y";
String customerChoice = "x";
int empid = 0;
Scanner sc = new Scanner(System.in);
int currentIndex;
File file = new File("E:/output.txt");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
int[] punchedArray;
punchedArray = new int[100];
// System.out.println(t);
while (!customerChoice.equalsIgnoreCase("d") && customerChoice != "invalid" && choice.equalsIgnoreCase("y")) {
customerChoice = getValidCustomerChoice(sc);
if (customerChoice.equalsIgnoreCase("a")) {
// System.out.println("In Create Customer");
System.out.print("Enter your first name: ");
firstName = sc.next();
System.out.print("Enter your last name: ");
lastName = sc.next();
System.out.println(firstName + lastName + "with employee id" + empid);
//System.out.println(firstNameArray[newEmployeeIndex] + " " + lastNameArray[newEmployeeIndex] + " your employee ID is: " + employeeIDArray[newEmployeeIndex]);
empid++;
//sc.next();
}
if (customerChoice.equalsIgnoreCase("b")) {
System.out.println("Welcome to the punch in/out screen"+"\n");
System.out.print("Enter your employee ID: ");
currentIndex = Integer.parseInt(sc.next());
if (punchedArray[currentIndex] == 0)
{
System.out.println("You are now punched in");
punchedArray[currentIndex] = 1;
}
else if (punchedArray[currentIndex] == 1)
{
System.out.println("You are now punched out");
punchedArray[currentIndex] = 0;
}
System.out.print(firstName + " "+ lastName + " "+ "your employee ID is " + currentIndex + " and your clock date and time is: " + " "+ cal.getTime() +"\n");
String content = firstName + lastName + empid + cal.getTime();
bw.write(content);
bw.newLine();
bw.close();
}
if (customerChoice.equalsIgnoreCase("c")) {
System.out.print("Welcome to the report screen." + "\n");
System.out.print("Enter your selection (I = individual report or A= all employees):" + "\n");
customerChoice = sc.next();
if (customerChoice.equalsIgnoreCase("i")) {
System.out.println("In Individual Report");
} else if (customerChoice.equalsIgnoreCase("a")) {
System.out.println("In Consoldated Report");
}
}
if(customerChoice.equalsIgnoreCase("d"))
{
//bw.close();
break;
}
}
}
public static String getValidCustomerChoice(Scanner sc) {
String customerChoice = "";
// sc.nextLine();
boolean isValid = false;
int invalidCounter = 0;
System.out.print("Enter your selection (a= Add New Employee, b = Punch in/out, c= Report, d = Exit):");
while (isValid == false && invalidCounter < 3) {
customerChoice = sc.next();
if (!customerChoice.equalsIgnoreCase("a")
&& !customerChoice.equalsIgnoreCase("b") && !customerChoice.equalsIgnoreCase("c") && !customerChoice.equalsIgnoreCase("d") && !customerChoice.equalsIgnoreCase("I") && !customerChoice.equalsIgnoreCase("A")) {
System.out.println("Invalid choice. Try again.\n");
invalidCounter++;
} else {
isValid = true;
}
sc.nextLine();
}
if (invalidCounter >= 3) {
System.out.println("Invalid three times. Program Exiting.\n");
return "invalid";
}
return customerChoice;
}
}
At line[75] bw.write(content) I am writing to a file called "output.txt"(I also want to add timestamp to those employees whom I wrote to file). But somehow the data is not going into the file, I am sure that I am making a mistake somewhere in closing that and I want to read from the same file which I wrote. Can someone please suggest me where I am going wrong?
Adding more details:
run:
Enter your selection (a= Add New Employee, b = Punch in/out, c= Report, d = Exit):a
Enter your first name: Sa
Enter your last name: Ka
SaKawith employee id0
Enter your selection (a= Add New Employee, b = Punch in/out, c= Report, d = Exit):b
Welcome to the punch in/out screen
Enter your employee ID: 0
You are now punched in
Sa Ka your employee ID is 0 and your clock date and time is: Sun Jun 08 20:19:42 EDT 2014
Enter your selection (a= Add New Employee, b = Punch in/out, c= Report, d = Exit):a
Enter your first name: Ka
Enter your last name: Ma
KaMawith employee id1
Enter your selection (a= Add New Employee, b = Punch in/out, c= Report, d = Exit):b
Welcome to the punch in/out screen
Enter your employee ID: 1
You are now punched in
Ka Ma your employee ID is 1 and your clock date and time is: Sun Jun 08 20:19:42 EDT 2014
Enter your selection (a= Add New Employee, b = Punch in/out, c= Report, d = Exit):c
Welcome to the report screen.
Enter your selection (I = individual report or A= all employees):
a
In Consoldated Report
Enter your selection (a= Add New Employee, b = Punch in/out, c= Report, d = Exit):BUILD STOPPED (total time: 1 minute 8 seconds)
So,when I go now to E drive of my Pc I just see a file named output.txt(latest modified time) but there's nothing in it. I tried to close my buffer after the loop but no luck with it. Also, Please advise on reading the data which I wrote to the file
Please advise!
Thanks
I'm not sure if I understand your issue, but like this, you can only write to the file once, since you close it after writing to it. Instead, you can use the flush() method to ensure the contents are written to the file.
Consider reading the documentation at http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html.
In my test it works fine . but change bw.close(); to bw.flush(); Because the outputstream will be closed after first input. and att second input you got an exception
Right off the bat I'd suggest trying to replace your file name with E:\output.txt. I believe windows file paths use backslashes.

Categories

Resources