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.
Related
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.
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 create a program that accepts user input. Based on the sales amount I am requesting the data go to either a low sales txt file or a high sales txt file. When I run the program I receive error Error: Could not find or load main class HighandLowSales. How can it not find or load the main class?
My previous post regarding the if else statement in case you would like to see: How to specify which file to write to?
import java.nio.file.*;
import java.io.*;
import static java.nio.file.StandardOpenOption.*;
import java.util.Scanner;
public class HighandLowSales
{
public static void main(String[] args)
{
Scanner input1 = new Scanner(System.in);
Path highPerformer =
Paths.get("C:\\Users\\C\\Desktop\\IS103 "
+ "Programming Logic\\Week7\\HighSales.txt");
Path lowPerformer =
Paths.get("C:\\Users\\C\\Desktop\\IS103 Programming Logic\\"
+ "Week7\\LowSales.txt");
String delimiter = ",";
String s;
int id;
String firstName;
String lastName;
double currentSales;
final int QUIT = 999;
try
{
Scanner input = new Scanner(System.in);
OutputStream output = new
BufferedOutputStream(Files.newOutputStream(highPerformer, CREATE));
OutputStream output1 = new
BufferedOutputStream(Files.newOutputStream(lowPerformer, CREATE));
BufferedWriter writer = new
BufferedWriter(new OutputStreamWriter(output));
BufferedWriter writer1 = new
BufferedWriter(new OutputStreamWriter(output1));
System.out.print("Enter employee ID number >> ");
id = input.nextInt();
while(id != QUIT)
{
System.out.print("Enter first name for employee #" +
id + " >> ");
input.nextLine();
firstName = input.nextLine();
System.out.print("Enter last name for employee # " +
id + " >> ");
input.nextLine();
lastName = input.nextLine();
System.out.print("Enter current month sales in whole dollar "
+ "for employee #" + id + " >> ");
input.nextLine();
currentSales = input.nextDouble();
s = id + delimiter + firstName + delimiter + lastName + delimiter
+ currentSales;
if (currentSales>1000)
{
writer.write(s);
}
else
{
writer1.write(s);
}
writer.newLine();
writer1.newLine();
System.out.print("Enter next ID number or " + QUIT
+ "to quit");
id = input.nextInt();
}
writer.close();
writer1.close();
}
catch(Exception e)
{
System.out.println("Message: " + e);
}
}
}
The file HighandLowSales.java must be exactly in the same case, not for instance HighAndLowSales.java. Either that or you are not executing the application with the correct class path: java -cp . HighandLowSales. But as it seems you just clicked the jar, I guess it is the case-sensitive nature of java file names (in jars, under Linux, MacOSX).
(Also it is really customary to no longer use the default (=no) package.)
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"))...
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.