I'm pretty new to Java, so after several days of trying to figure out how to compare user input to a column in a text file, I am in desperate need of help. I want to be sure that an employee who punches-in has not punched-in once before without punching-out after that. In addition, I would like to be able to ensure that a user cannot punch-out of the system unless they have previously punched-in. I know that I have to split the lines in the text file in order to make them accessible separately, but I don't know how to compare them to user input. Any help is greatly appreciated! My code is as follows:
import java.text.*;
import java.util.*;
import java.io.*;
import java.nio.file.*;
public class TimeClockApp
{
// declare class variables
private static EmployeeDAO employeeDAO = null;
private static TimeClockDAO timeClockDAO = null;
private static Scanner sc = null;
// format date and time / //HH converts hour in 24 hours format (0-23), day calculation
private static DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
public static void main(String[] args) throws Exception
{
// set the class variables
employeeDAO = DAOFactory.getEmployeeDAO();
timeClockDAO = DAOFactory.getTimeClockDAO();
sc = new Scanner(System.in);
int employeeID = 0;
List<Employee> employees = employeeDAO.readEmployees();
List<TimeClock> timePunches = timeClockDAO.readTimePunches();
if(timePunches == null)
{
timePunches = new ArrayList<TimeClock>();
}
// display a welcome message
System.out.println("Welcome to the Punch-In/Punch-Out Screen\n");
// print option menu
System.out.print("Please choose an option below:" + "\n"
+ "I. Punch In" + "\n"
+ "O. Punch Out" + "\n");
String choice = "";
// get input from user
Scanner sc = new Scanner(System.in);
while(choice != null)
{
// get input from user "i" or "o"
while (!choice.equalsIgnoreCase("i") && !choice.equalsIgnoreCase("o"))
{
// it will not continue if user does not enter a valid choice
choice = Validator.getScreenChoice(sc, "Choice: ");
if(!choice.equalsIgnoreCase("i") && !choice.equalsIgnoreCase("o"))
{
System.out.println("Invalid choice. Please try again.");
}
}
System.out.println(); // print a blank line
if(!choice.isEmpty())
{
// create employee object
Employee employee = null;
System.out.println("PUNCH CLOCK");
System.out.println("-----------");
// read employee ID and compare to employee.txt
while(employee == null)
{
employeeID = Validator.getEmployeeID(sc,
"Enter Employee ID: ");
for(Employee e : employees)
{
if(e.getEmployeeID() == employeeID)
{
employee = e;
break;
}
}
}
// if employee ID is valid, have they punched in already?
// if not, try again.
// read timeclock.txt
timeClockDAO.readTimePunches();
if(employeeID == employee.getEmployeeID() && choice.equalsIgnoreCase("o")) // <-- This is where I'm having trouble
{
if(timePunches.contains("i"))
{
if(timePunches.contains(employeeID))
{
System.out.println("Employee " + employeeID + " has already punched in. Please try again.");
}
}
// has employee punched in? If yes, continue. <-- Beginning here, NetBeans ignores this whole deal
for(TimeClock t : timePunches)
{
if(t.getPunchInOrOut() && choice.equalsIgnoreCase("i"))
{
timePunches = t;
break;
}
}
// if employee has not punched in, try again
if(timePunches.contains("i"))
{
if(timePunches.contains(employeeID))
{
System.out.println("Employee " + employeeID + " has not punched in yet. Please try again.");
}
}
} // <-- NetBeans stops ignoring and continues from here
TimeClock newTimePunch = new TimeClock(employeeID, new Date(), choice);
// if employee ID is valid,
// addition of date and time to arraylist/text file
timePunches.add(newTimePunch);
//write to the file
timeClockDAO.writeTimePunch(newTimePunch);
// conditional statement for in/out + formatting
System.out.println("Punch-" + (choice.equalsIgnoreCase("i") ? "In" : "Out") + " Successful!" + "\n"
+ "Date & Time: " + dateFormat.format(new Date()) + "\n"
+ "Employee Name: " + employee.getFirstName() + " " + employee.getLastName() + "\n"
+ "Employee ID: " + employee.getEmployeeID() + "\n");
System.out.println(); // print a blank line
break;
}
else
{
System.out.println("Invalid entry. Please try again.");
}
}
// press enter to continue to the main screen
System.out.printf("Press enter to return to the main screen. ");
sc.nextLine();
System.out.println("Okay, returning to Main Screen. Goodbye!");
System.out.println(); // print a blank line
MainScreenApp.main(args);
}
}
Can I use the timeClockDAO.readTimePunches() portion of my code to read and compare columns in the text file to the user's input since the columns are already split there? The timeClockDAO.readTimePunches() method from the List<TimeClock> timePunches() list is as follows:
#Override
public List<TimeClock> readTimePunches()
{
if(timePunches != null)
return timePunches;
timePunches = new ArrayList<TimeClock>();
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
if(Files.exists(Paths.get(timeClockPath))) // prevent the FileNotFoundException
{
try(BufferedReader in = new BufferedReader(
new FileReader(
new File(timeClockPath))))
{
// read all employees in the file into the array list
String line = in.readLine();
while(line != null)
{
// split text file into columns
String[] columns = line.split(EmployeeTextFile.FIELD_SEP);
/*if(columns.length != 3)
{
System.err.println("Could not read text file for Time Punches.");
return null;
}*/
// employee ID column
int employeeID = Integer.parseInt(columns[0]);
// time stamp column
Date timeStamp;
try
{
timeStamp = dateFormat.parse(columns[1]);
}
catch (ParseException e)
{
System.err.println("Could not parse time stamp: " + columns[1]);
timeStamp = null;
}
// in or out column
String punchInOrOut = columns[2];
timePunches.add(new TimeClock(employeeID, timeStamp, punchInOrOut));
line = in.readLine();
}
}
catch(IOException e)
{
System.out.println(e);
return null;
}
}
return timePunches;
}
Thank you in advance!
The lines if(timePunches.contains("i")) and if(timePunches.contains(employeeID)) won't work since timePunches is an arrayList of TimeClock and unless you use a comparator or implement the Comparable interface, you cannot check if it contains a String value or an Employee value.
As I can assume in your code, you add timePunches to the end of the file so you only need to compare to the last item of your ArrayList to see if the current employee's state is punched in or punched out.
Instead of if(timePunches.contains("i")) and if(timePunches.contains(employeeID)) you should first fill your ArrayList only with your current Employee punches. Then, do something similar to:
if((timePunches.get(timePunches.size()).getPunchedInOrOut.equals("i") && choice.equals("o")) || (timePunches.get(timePunches.size()).getPunchedInOrOut.equals("o") && choice.equals("i"))...
Related
I'm using an arraylist to append inputs and send the arraylist elements to file. However, everytime I exit the program and run it again, the contents in the written in the file becomes empty.
ArrayList<String> memory = new ArrayList<String>();
public void fileHandling() {
try {
FileWriter fWriter = new FileWriter("notes.data");
for (int x = 0; x <= memory.size() - 1; x++) {
fWriter.write(memory.get(x) + '\n');
}
fWriter.close();
} catch (IOException e) {
System.out.println(e);
}
}
public void createNote() {
Scanner insertNote = new Scanner(System.in);
LocalDate todayDate = LocalDate.now();
LocalTime nowTime = LocalTime.now();
String timeFormat = nowTime.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM));
String dateTime = todayDate.toString() + " at " + timeFormat;
while (true) {
System.out.println();
System.out.println("Enter a note");
System.out.print("> ");
String note = insertNote.nextLine();
if (note == null) {
System.out.println("Invalid input! Try again");
break;
} else {
memory.add(note + " /" + dateTime);
fileHandling();
System.out.println("Note is saved!\n");
break;
}
}
I expect the program to save the contents of every input. Then if I exit and run the program again, the contents will go back to the array
Your code currently does the following:
You enter something (X) for the first time:
It gets added to the ArrayList
The ArrayList gets written into the file
Your file now contains: X
You enter something second (Y):
It gets added to the ArrayList (Which now contains: X, Y)
The ArrayList gets written into the file
Your file now contains: X + newline + Y
Your Problem is, that everytime you create a new FileWrite it overwrites your file.
This can be avoided by using the constructor like this:
FileWriter writer = new FileWriter("notes.data", true);
This sets it into the append mode and therefore keeps previous data in the file
You don't need to create a separate Scanner, in method createNote(), in order to get a "note" from the user.
It is usually better to write your code using the interface rather than the specific implementation because then you usually need to change less code if you decide to change the implementation. Hence the type for member variable memory should probably be List rather than ArrayList.
Note that ArrayList may waste memory if the list of "note"s is large. I suggest using LinkedList instead. Alternatively, use an array (rather than a List) and handle expanding the array when adding a "note" as well as reducing the array when removing a "note".
Having an infinite loop, i.e. while (true), which contains a single if-else where both the if block and the else block contain break statements, means that the loop will perform exactly one iteration. May as well remove the while loop – which means also removing the break statements.
Rather than writing the code that generates a timestamp repeatedly, you should adopt the DRY principle and extract that code into a separate method.
The file name should be a constant so as to minimize the amount of code changes you will need to do if you decide to change the file name.
By convention, text files have a filename extension of .txt whereas binary files have the .data extension.
Although you don't need to, I personally prefer to initialize class member variables in the constructor.
The below code is a SSCCE, hence I added a main method. More notes appear after the code.
package Methods;
import java.util.*;
import java.time.format.*;
import java.time.*;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class FileSys {
private static final String FILENAME = "notes.txt";
private static final String CREATE = "C";
private static final String DELETE = "D";
private static final String FIND = "F";
private static final String QUIT = "Q";
private static final String SHOW = "S";
private static final String UPDATE = "U";
Scanner reader;
List<String> memory;
public FileSys() throws IOException {
reader = new Scanner(System.in);
memory = new LinkedList<String>();
loadFile();
}
public void fileHandling() {
Path path = Paths.get(FILENAME);
try (BufferedWriter bw = Files.newBufferedWriter(path,
StandardOpenOption.CREATE,
StandardOpenOption.WRITE);
PrintWriter pw = new PrintWriter(bw)) {
for (String write : memory) {
pw.println(write);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
public void createNote() {
String dateTime = getTimestamp();
System.out.println();
System.out.println("Enter a note");
System.out.print("> ");
String note = reader.nextLine();
memory.add(note + " / " + dateTime);
fileHandling();
System.out.println("Note is saved!");
}
public void searchNote() {
System.out.print("\nEnter note number: ");
try {
int search = reader.nextInt();
reader.nextLine();
System.out.println("\nSearch result:");
int index = memory.indexOf(memory.get(search - 1));
if (index != -1) {
System.out.println("[" + (index + 1) + "]" + " " + memory.get(search - 1));
}
else {
System.out.println("Note number-" + search + " is not found in the collection!");
}
}
catch (IndexOutOfBoundsException e) {
System.out.println("The note number you have entered is invalid!");
}
}
public void updateNote() {
String dateTime = getTimestamp(); // ZonedDateTime.now(ZoneId.systemDefault()).format(dateTimeObj);
System.out.print("\nEnter note number to change: ");
try {
int search = reader.nextInt();
int index = memory.indexOf(memory.get(search - 1));
String updateLine;
if (index != -1) {
System.out.println("\nCurrent note: ");
System.out.println("[" + (index + 1) + "]" + " " + memory.get(search - 1));
System.out.println("\nThe updated note will be: ");
System.out.print("> ");
reader.nextLine();
updateLine = reader.nextLine();
memory.set(index, updateLine + " /" + dateTime);
System.out.print("Note has been updated successfully!\n");
}
else {
System.out.println(search + " is not found in the collection!");
}
}
catch (IndexOutOfBoundsException e) {
System.out.println("The note number you have entered is invalid!");
}
fileHandling();
}
public void deleteNote() {
System.out.print("\nEnter note number to delete: ");
try {
int search = reader.nextInt();
reader.nextLine();
int index = memory.indexOf(memory.get(search - 1));
System.out.println();
if (index != -1) {
System.out.println("[" + (index + 1) + "]" + " " + memory.get(search - 1));
System.out.print("\nDo you want to delete this note? \n[y] or [n]: ");
char delDecision = reader.nextLine().charAt(0);
if (delDecision == 'y' || delDecision == 'Y') {
memory.remove(index);
System.out.println("Note has been deleted successfully!");
System.out.println();
}
else if (delDecision == 'n' || delDecision == 'N') {
System.out.println("Note was not deleted!");
}
else {
System.out.println("Invalid input!");
}
}
else {
System.out.println(search + " is not found in the collection!");
}
}
catch (IndexOutOfBoundsException e) {
System.out.println("The note number you have entered is invalid!");
}
fileHandling();
}
public void displayNote() {
if (memory.size() > 0) {
int counter = 0;
for (String note : memory) {
System.out.printf("%d. %s%n", ++counter, note);
}
}
else {
System.out.println("There are no notes.");
}
}
private String getTimestamp() {
LocalDate todayDate = LocalDate.now();
LocalTime nowTime = LocalTime.now();
String timeFormat = nowTime.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM));
String dateTime = todayDate.toString() + " at " + timeFormat;// ZonedDateTime.now(ZoneId.systemDefault()).format(dateTimeObj);
return dateTime;
}
private void loadFile() throws IOException {
Path path = Paths.get(FILENAME);
if (Files.isRegularFile(path)) {
memory.addAll(Files.readAllLines(path, Charset.defaultCharset()));
}
}
private void showMenu() {
String choice = "";
while (!QUIT.equalsIgnoreCase(choice)) {
System.out.println(CREATE + " - Create note");
System.out.println(DELETE + " - Delete note");
System.out.println(FIND + " - Search notes");
System.out.println(SHOW + " - Show notes");
System.out.println(UPDATE + " - Update note");
System.out.println(QUIT + " - Quit");
System.out.println();
System.out.print("Your choice: ");
choice = reader.nextLine();
if (!choice.isEmpty()) {
choice = choice.substring(0, 1);
choice = choice.toUpperCase();
switch (choice) {
case CREATE -> createNote();
case DELETE -> deleteNote();
case FIND -> searchNote();
case SHOW -> displayNote();
case UPDATE -> updateNote();
case QUIT -> System.out.println("Good bye.");
default -> System.out.println("Invalid: " + choice);
}
}
else {
System.out.println("No selection entered. Retry.");
}
}
}
public static void main(String[] args) {
try {
FileSys fs = new FileSys();
fs.showMenu();
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
Your code does not initially load memory with contents of file notes.txt so I added that in the constructor. Consequently you don't need to append to the file since you simply overwrite it with contents of memory.
The file handling is done using NIO.2 including try-with-resources – which was added in Java 7. There are more NIO.2 examples in the JDK documentation.
Whenever the code throws an unexpected exception, it is nearly always a good idea to print the stack trace.
I have done a code, which reads a file consists a number of employees, salary, and their rankings, based on their rankings how can we add the bonus percent to their salary...
String phrases;
int salary=0;
try {
FileReader in = new FileReader("bonus.txt");
BufferedReader readFile = new BufferedReader(in);
while ((phrases = readFile.readLine()) != null) {
System.out.println(phrases);
double bonus;
if(phrases.contains("1")){
bonus=salary/0.03;
System.out.println("Bonus: " + bonus);
}else if(phrases.contains("2")){
bonus=salary/0.08;
System.out.println("Bonus: " + bonus);
}else if(phrases.contains("3")){
bonus=salary/0.20;
System.out.println("Bonus: " + bonus);
}
// System.out.println();
}
readFile.close();
in.close();
}catch (IOException e) {
System.out.println("Problem reading file.");
System.err.println("IOException: " + e.getMessage());
}
It outputs:
Jame 900000 1
Bonus: 0.0
Jane 60000 2
Bonus: 0.0
Don 866000 3
Bonus: 0.0
I have no idea why
If you have an employeeBonus.txt file like below.
Jame 900000 2
Jane 60000 1
Don 866000 3
I think you will have three tokens as a string so, you can use a stringtokenizer class in order to get a salary and a grade.
At the first line of file is
Jame 900000 2
and the result of encoded string was
Jame%20%20%20%20900000%092
I've finally found the content of text file was mixed with a space and tab character by URL encoding.
So, the usage of this type is as follows,
StringTokenizer stTok = new StringTokenizer(phrase, " \t");
It takes a salary and an identifier of bonus value from third and second token.
name = stTok.nextToken(); //first token
salary = Integer.valueOf(stTok.nextToken()).intValue(); //second token
grade = stTok.nextToken();
[source code]
package com.tobee.tests.inout;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class CheckBounsFromFile {
public static void main(String[] args) {
String name, phrase, grade;
double bonus = 0;
int salary = 0;
BufferedReader readFile = null;
try {
readFile = new BufferedReader(new FileReader("resource/aa/employeeBonus.txt"));
while ((phrase = readFile.readLine()) != null) {
//System.out.println(phrase);
StringTokenizer stTok = new StringTokenizer(phrase, " \t");
name = stTok.nextToken();
salary = Integer.valueOf(stTok.nextToken()).intValue();
grade = stTok.nextToken();
if(grade!= null && !grade.equals(""))
{
if (grade.equals("1")) {
bonus = salary / 0.03;
} else if (grade.equals("2")) {
bonus = salary / 0.08;
} else if (grade.equals("3")) {
bonus = salary / 0.20;
}
System.out.printf("name[%s]salary[%d]Bonus[%f] \n",name, salary, bonus);
}
}
} catch (IOException e) {
System.out.println("Problem reading file.");
System.err.println("IOException: " + e.getMessage());
}
finally
{
try {
readFile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
[result]
name[Jame]salary[900000]Bonus[30000000.000000]
name[Jane]salary[60000]Bonus[750000.000000]
name[Don]salary[866000]Bonus[4330000.000000]
Have a nice day.
The other answers appear to not cater for the fact that your salary variable is always 0, thus, your bonus calculation, which depends on your salary value will always be 0.
Assuming that this: Jame 900000 1 is a sample line from your text file, there are various issues with your code.
The first issue is this: (phrases.equals("1"). If phrase will be equal to the text in the current line you are processing: Jame 900000 1, this statement (and the same for the other two) will never return true, thus the bonus will never be calculated.
The second issue is that you are never extracting the salary value.
You will need to replace this:
while ((phrases = readFile.readLine()) != null) {
System.out.println(phrases);
if(phrases.equals("1")){
With something like this:
while ((phrases = readFile.readLine()) != null) {
System.out.println(phrases);
String[] employeeData = phrases.split("\\t"); //This assumes that your data is split by tabs.
salary = Double.parse(employeeData[1]);
if("1".equals(employeeData[2])) {
bonus = salary * 0.03;
}
...
You check the condition with equals method but your phrases variable contains different value rather than 1,2,3 that's why you get the bonus 0.
if(phrases.contains("1")){
bonus=salary/0.03;
}else if(phrases.contains("2")){
bonus=salary/0.08;
}else if(phrases.contains("3")){
bonus=salary/0.20;
}
or you can get the last parameter with:
phrases.substring(phrases.length()-1, phrases.length())
you can get the third parameter using contains or split method.
Please check this tutorial: https://www.tutorialspoint.com/java/java_string_split.htm
And one more thing your salary is always zero (0). please correct it
I have posted full code here:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
class SubClass{
public static void main(String[] args) {
String phrases;
int salary=0;
try {
FileReader in = new FileReader("bonus.txt");
BufferedReader readFile = new BufferedReader(in);
while ((phrases = readFile.readLine()) != null) {
System.out.println(phrases);
phrases = phrases.trim().replaceAll("[ ]{2,}", " ");
String splitStr [] = phrases.split(" ");
double bonus;
salary = Integer.parseInt(splitStr[1]);
if(splitStr[2].contains("1")){
bonus=salary/0.03;
System.out.println("Bonus: " + bonus);
}else if(splitStr[2].contains("2")){
bonus=salary/0.08;
System.out.println("Bonus: " + bonus);
}else if(splitStr[2].contains("3")){
bonus=salary/0.20;
System.out.println("Bonus: " + bonus);
}
// System.out.println();
}
readFile.close();
in.close();
}catch (IOException e) {
System.out.println("Problem reading file.");
System.err.println("IOException: " + e.getMessage());
}
}
}
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.
I have created an application that allows the user to enter their account number, balance(no more than 99999), and last name. The program will take this information and insert it into a .txt file at a location corresponding to the account number(acct). Here is the code for that:
import java.io.*;
public class NationalBank {
public static void main(String[] args) throws Exception{
InputStreamReader temp = null;
BufferedReader input = null;
try {
temp = new InputStreamReader(System.in);
input = new BufferedReader(temp);
int acct;
double amount;
String name;
RandomAccessFile file = new RandomAccessFile("bank.txt", "rw");
while(true) {
// Asks for input
System.out.println("Enter Account Number (0-9999): ");
acct = Integer.parseInt(input.readLine());
System.out.println("Enter Last Name: ");
name = input.readLine();
System.out.println("Enter Balance ");
amount = Double.parseDouble(input.readLine());
// Making sure account numbers are between 0 and 9999
if(acct >=0 && acct <= 9999) {
file.seek(acct*17);
file.write(truncateName(name));
file.writeBytes(" " +amount);
}
else {
continue;
}
// Asks user if more entries are needed
System.out.println("Enter More? (y/n)");
if (input.readLine().toLowerCase().equals("n"))
break;
}
file.close();
}
catch (Exception e) {
}
}
// Truncate/adding spaces to name until 8 characters
public static byte[] truncateName (String name) {
byte[] result = new byte[8];
for (int i = 0; i < 8; i++)
result [i] = i < name.length () ? (byte)name.charAt (i) : (byte)' ';
return result;
}
}
Now, I am trying to make an application that will write back all of the accounts that have information within them(with last name and balance). I need to display the account number, balance, and last name of those accounts. So far, I have:
import java.io.*;
public class DisplayBank {
public static void main(String[] args) throws IOException {
FileInputStream input = new FileInputStream ("bank.txt");
try {
byte[] record = new byte[17];
while (input.read(record) == 17) {
String name = new String(record, 0, 8);
long bits = 0;
for (int i = 8; i < 17; i++) {
bits <<= 8;
bits |= record[i] & 0xFF;
}
double amount = Double.longBitsToDouble(bits);
System.out.println("Account Number: " + record + " Name: " + name + ", amount: " + amount);
}
}
catch (IOException e) {
}
finally {
input.close();
}
}
}
This currently displays only the name correctly. The balance is incorrect, and I don't know how to get the account number. In order to get the account number, I would need to get the position of name. In order to get the amount, I would need to seek name, offset 9 bytes, then read the next 8 bytes...
If you want to parse a text file that contains last names and amounts similar what you provided:
example provided
LastName 93942.12
What I would do is to try something like the following
public void read_file(){
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("C:\\Users\\Alos\\Desktop\\test.txt");
// Use DataInputStream to read binary NOT text.
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
int record = 0;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
String[] splits = strLine.split("\t");
String LastName = splits[0];
String Amount = splits[1];
System.out.println("Account Number: " + record + " Name: " + LastName + ", amount: " + Amount);
record++;
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
This might not be exactly what you're looking for but please take a look and update your question if you would like something different.
I it's not a homework, I would strongly recommend to use some RDBMS like Derby or MySQL.
I want to use the MaxFriends method to find the person with the most friends. Printing the number of friends from the linked list is easy enough but since I clear it after each iteration of the while loop I don't know how to compare the values at the end...
I think the problem could be simplified if I just found the line with the most 'tokens' or in this case strings. Is there a way to do this?
I'm reading in a text file (to create a linked list).
Text file looks like this:
john, peter, maria, dan, george, sonja
maria, nell, ted, don, matthew, ann, john, george
fred, steve
ann, tom, maria
Code thus far:
import java.util.*;
import java.io.*;
import javax.swing.JFileChooser;
public class Test {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<String>();
LinkData ld1 = new LinkData();
JFileChooser chooser = new JFileChooser(".");
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: ");
// open and read file:
Scanner scanner = null;
try {
scanner = new Scanner(chooser.getSelectedFile());
} catch (IOException e) {
System.err.println(e);
error();
}
if (scanner == null)
error();
while (scanner.hasNextLine()) {
int friendCount = 0;
String line = scanner.nextLine();
Scanner lineScan = new Scanner(line);
lineScan.useDelimiter(", ");
// System.err.println("The line that was scanned: " + line);
String leader = lineScan.next(); {
while (lineScan.hasNext()) {
list.add(lineScan.next());
friendCount++;
}
System.out.println("Friend Leader: " + leader + "\n" +
"\tFriends include: " + list.toString() + "\n" +
"\tNumber of Friends: " + list.size() + "\n");
} list.clear();
}
}
}
private static void error() {
System.err.println("An error has occurred: bad data");
System.exit(0);
}
public void maxFriends() {
}
}
If I understand the problem correctly, you just need to keep track of who has the most friends so far, and compare that to the next candidate for each line. Stuffing everything into a map or heap seems unnecessary.
By the way, the parsing you're doing is very simple and doesn't need a scanner:
String[] friends = line.split(",\\s*");
System.out.printf("%s has %d friends\n", friends[0], friends.length - 1);
I changed portion of your code into somewhat like below:
int maxFriendCount = 0; // added by me
String maxLeader = null; // added by me
while (scanner.hasNextLine()) {
int friendCount = 0;
String line = scanner.nextLine();
Scanner lineScan = new Scanner(line);
lineScan.useDelimiter(", ");
// System.err.println("The line that was scanned: " + line);
String leader = lineScan.next();
while (lineScan.hasNext()) {
list.add(lineScan.next());
friendCount++;
}
// Added by me
if(friendCount > maxFriendCount)
{
maxFriendCount = friendCount;
maxLeader = leader;
}
System.out.println("Friend Leader: " + leader + "\n" +
"\tFriends include: " + list.toString() + "\n" +
"\tNumber of Friends: " + list.size() + "\n");
list.clear();
}
After while loop terminates, you can get the leader with the most friends.
Why not use a Hashmap for storing the information on a per friend basis
Map<String, List<String>> friends = new HashMap<String, List<String>>();
After each iteration use the friends name as the key in the hashmap and then add the linked list to the map as the value.
Then in maxFriends you will be able to go through the keys and get the values and verify which list had the greatest size and thus the most friends.