Find line in .txt file with most data - java

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.

Related

Retrieve lines in txt file and append new inputs from the user java

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.

how do I get data from a text file and save it into a string?

How do I get data from a text file and save it into a string?
For example, my text file has the numbers 1, 4, 5, 6, 8, and 10.4. These numbers can be on the same line or on separate lines. I want to concatenate them into a string, like so: 1 4 5 6 8 10.4
import java.io.File;
import java.io.FileNotFoundException;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Scanner;
public class f {
public static void main(String args[]) {
int count = 0;
double totalcount = 0;
double average = 0;
Scanner read = new Scanner(System.in);
Scanner file;
String input = "";
String test = "";
double[] array1 = new double[100];
while (true) {
System.out.println("Enter name of file or enter quit to exit");
input = read.next();
if (input.equalsIgnoreCase("quit")) {
break;
}
try {
file = new Scanner(new File(input));
if (!file.hasNextLine()) {
System.out.println(input + " file is empty");
}
while (file.hasNext()) {
totalcount = totalcount + file.nextDouble();
count++;
}
while (file.hasNext()) {
test = test + (" ") + file.next();
}
System.out.println("bla" + test);
average = totalcount / count;
DecimalFormat df = new DecimalFormat("#.###");
df.setRoundingMode(RoundingMode.CEILING);
System.out.println("\nCount: " + count);
System.out.println("Total: " + df.format(totalcount));
System.out.println("Average: " + df.format(average));
System.out.println();
} catch (FileNotFoundException e) {
System.out.println(input + " doesn't exist");
}
}
}
}
My code does not work correctly.
Your code is working fine, the problem is, you trying to access content of your file two times.after first while loop , the hasnext() method will return false.because you already accessed all the element in first while loop.
so it will not execute -
while (file.hasNext()) {
test = test + (" ") + file.next();
}
Other than that your code is fine.
if you want store it in string also then do small modification in your first while loop as below-
while (file.hasNext()) {
Double d=file.nextDouble();
test = test + (" ")+d;
totalcount = totalcount + d;
count++;
}
I think this will give you what you want.
Hello i think below code will be useful for you ,as per your question i have txt file with data , first i am getting the location of file & then i am trying to get the content , at last i am printing it to the console
File f = new File("D:\\temp.txt");
String content11 = FileUtils.readFileToString(f);
System.out.println(content11);

Exception : java.lang.ArrayIndexOutOfBoundsException

I am getting this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at JavaProject.main(JavaProject.java:70)
Here is the code:
try
{
PrintWriter writer = new PrintWriter("Gamer Report Data.txt");
writer.println("Player: " + gamerName);
writer.println();
writer.println("-------------------------------");
String[] report = gamerReport.split(gamerReport, ':');
writer.println("Game:" + ", score=" + report[1] + ", minutes played=" + report[2] + report[3]);
writer.close();
} catch (IOException e)
{
System.err.println("File does not exist!");
}
I believed it to be something related to my for loop, but I have had no luck changing it around.
import java.util.Scanner;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.io.PrintWriter;
public class JavaProject {
private static char[] input;
#SuppressWarnings("null")
public static void main(String[] args) {
for (int b = 1; b < 100; b++) {
// this is making the code loop 100 times
int hrs, mins;
int[] gameCount;
int[] minutesPlayed = new int[100];
String gamerName, gamerReport;
// Main data storage arrays
String[] gameNames = new String[100];
int[] highScores = new int[100];
Scanner Scan = new Scanner(System.in);
// formatting for output and input
System.out.println("////// Game Score Report Generator \\\\\\\\\\\\");
System.out.println(" ");
// user enters name and then moves to next line
System.out.println("Enter Your Name");
gamerName = Scan.nextLine();
// user is given an example of input format
System.out.println("Input Gamer Information " + "Using Format --> Game : Achievement Score : Minutes Played");
System.out.println(" ");
System.out.println("Game : Achievement Score : Minutes Played");
gamerReport = Scan.nextLine();
String[] splitUpReport; // an array of string
splitUpReport = gamerReport.split(":"); // split the text up on the colon
int i = 0;
// copy data from split text into main data storage arrays
gameNames[i] = splitUpReport[0];
highScores[i] = Integer.parseInt(splitUpReport[1].trim());
minutesPlayed[i] = Integer.parseInt(splitUpReport[2].trim());
// output to file
try
{
PrintWriter writer = new PrintWriter("Gamer Report Data.txt");
writer.println("Player: " + gamerName);
writer.println();
writer.println("-------------------------------");
String[] report = gamerReport.split(gamerReport, ':');
writer.println("Game:" + ", score=" + report[1] + ", minutes played=" + report[2] + report[3]);
writer.close();
} catch (IOException e)
{
System.err.println("File does not exist!");
}
}
}
public static char[] getInput() {
return input;
}
public static void setInput(char[] input) {
JavaProject.input = input;
}
}
There are two problems with your code:
1)
String[] report = gamerReport.split(gamerReport, ':');
should be
String[] report = gamerReport.split(":");
as you did with splitUpReport (not sure why you're splitting again actually).
2) Arrays are zero-indexed, so the print statement should look like this:
writer.println("Game:" + ", score=" +report[0] +", minutes played="+ report[1] + report[2]);
The error in your code is being caused by this code in the try block:
String[] report = gamerReport.split(gamerReport, ':');
You are actually trying to split the gamerReport string using itself as a regex, with a limit of 58, which is the numerical value of the colon.
The result of this split is 2 empty String elements, which correspond to the match happening before and after the regex, which is the string itself.
The ArrayIndexOutOfBounds exception is happening when you try to access the third element from this array:
To fix your problem, just define the report array as follows:
String[] report = gamerReport.split(':');
As #shmosel pointed out, you might also want to change your array indices here as well:
writer.println("Game:" + ", score=" + report[0] +", minutes played="+ report[1] + report[2]);

Java: How do I compare user input to columns in text file?

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"))...

Prompting to print all of that type, and calculate the total of that type

I have a file that is needed to be read:
public static int start_program1(int rcount,int[]reservation_code,int[]fl_number,String[]last_name,String[]first_name,String[]seat_type,double[]seat_cost)
{
String newLine;
try
{
//define a file valuable for Buffered read
BufferedReader Reservation_file = new BufferedReader(new FileReader("reservationx.dat"));
//read lines in file until there are no more lines in the file to read
while ((newLine = Reservation_file.readLine()) != null)
{
//there is a "#" between each data item in each line
StringTokenizer delimiter = new StringTokenizer(newLine,"#");
rcount=rcount+1;
reservation_code[rcount] = Integer.parseInt(delimiter.nextToken());
fl_number[rcount] = Integer.parseInt(delimiter.nextToken());
last_name[rcount] =delimiter.nextToken();
first_name[rcount] =delimiter.nextToken();
seat_type[rcount] =delimiter.nextToken();
seat_cost[rcount] = Double.parseDouble(delimiter.nextToken());
}//while loop
Reservation_file.close();
}//end try
catch (IOException error)
{
//there was an error on the file writing
System.out.println("Error on file read " + error);
}//error on read
return rcount;
}//end start_system1
The file being read (reservations.dat) is simply below: (Wasn't sure of an easier way to post this)
(reservation code#flight number#last name#first name#seat type#seat cost)
1189#1234#Smith#James#coach#299.99#
1190#9876#Jones#Marie#coach#150.00#
1191#2000#Atkins#John#first#789.00#
1192#1000#Gallo#James#first#465.00#
1193#4567#Marion#Kevin#business#300.00#
1194#4444#Johnson#Greg#business#765.99#
1195#8888#Brown#Andrew#first#567.39#
1196#4567#Green#Eric#coach#234.00#
1197#9876#Thomas#Chris#business#1900.99#
1198#7777#Hilling#Cara#first#876.76#
1199#2222#Cole#James#coach#256.99#
1200#9281#Bartko#Grant#business#896.00#
1201#2000#Best#Curtis#first# 543.99#
1202#1000#Campbell#Nicholas#coach#287.00#
1203#4444#Dietz#Merrialyce#coach# 219.00#
1204#9281#Duran#Alexander#business#690.00#
1205#2892#Gurung#Suraj#first# 789.99#
1206#7777#Kumpfmiller#Ryan#first#278.99#
1207#4444#Mccomb#David#coach#451.99#
1208#8888#Mclain#Jaime#coach#199.00#
1209#9876#Mullen#Matthew#coach#189.00#
1210#1234#Nguyen#Tommy#coach#299.00#
1211#1234#Ossler#Aimee#coach#300.00#
1212#7777#Polenavitch#Michael#coach#198.99#
1213#2222#Raymond#Chase#first#908.99#
1214#2222#Rosales#David#coach#216.99#
1215#2892#Schwartz#Dustin#business#987.00#
1216#4444#Short#Samuel#coach#245.99#
1217#8888#Soltis#Josh#coach#178.00#
1218#1234#Webster#Ronald#business#892.00#
1219#1234#Wielock#William#first#589.00#
1220#2892#Bonelli#Andrew#coach#178.00#
1221#4444#Bright#Adam#coach#235.00#
1222#9876#Clymer#Jesse#coach#568.00#
1223#4444#Costello#Michael#coach#200.00#
1234#7777#Currin#Sean#business#908.00#
1225#1000#Farrar#Gary#first#588.00#
1226#1000#Finn#Lynn#business#799.00#
1227#4567#Freise#Brian#coach#254.00#
1228#4567#Huang#Pao-Jen#coach# 199.00#
1229#4567#Kamani#Nelson#coach#150.00#
1230#2000#Loughner#Ryan#coach#175.00#
1231#2000#Menzies#Adam#coach#199.00#
1232#1234#Neupane#Kiran#coach# 135.00#
1233#1234#Nickel#Brandon#first#999.00#
1234#7777#Ropchack#Joseph#first#899.00#
1235#7777#Whitten#Walter#coach#786.99#
1236#4444#Woods#Mary#coach#299.00#
1237#4444#Xing#Zhenli#coach#126.00#
Here is the method, doing the calculation in question:
public static void seat_value(int rcount,int[]reservation_code,int[]fl_number,String[]last_name,String[]first_name,String[]seat_type,double[]seat_cost)
{
int i;
double total=0;
String search_seat = "";
String output = "Enter the Seat Type you are searching for";
search_seat = JOptionPane.showInputDialog(null,
output, " ",
JOptionPane.QUESTION_MESSAGE);
for (i = 0; i <=rcount; ++i) {
//CHECK IF coach, first, or business
if(seat_type[i].equals("coach"))
{
total=total+seat_cost[i];
}
if (seat_type.equals("first"))
{
total=total+seat_cost[i];
}
if(seat_type.equals("business"))
{
total=total+seat_cost[i];
}
}
System.out.println("The total for " +search_seat+ " = " +total);
}
My issue in detail is this: Whenever I have it prompt for a type ("coach", "first", "business")
I cannot figure out how to get it to print ALL reservations of THAT type & TOTAL COST of THAT type?
CURRENTLY GETTING: 2051.97 8900.94 8094.45
ACTUAL TOTALS: 7230.93 8295.11 8138.98
COACH FIRST BUSINESS
PS, you will obviously call these methods
Hope this is explains it well.
Well in this loop:
for (i = 0; i <=rcount; ++i) {
//CHECK IF coach, first, or business
if(seat_type[i].equals("coach"))
{
total=total+seat_cost[i];
}
if (seat_type[i].equals("first"))
{
total=total+seat_cost[i];
}
if(seat_type[i].equals("business"))
{
total=total+seat_cost[i];
}
}
you add the cost to the same total every single time regardless of the seat type. So you will end up with the total of all the seats each time.
Basically heres what you are doing in english:
I am going to go through each customer. For each customer, I will do the following:
If their seat type is coach, add it to the total.
If their seat type is first, add it to the total.
If their seat type is business, add it to the total.
Basically, you are adding every customers ticket price to the total because every customer will satisfy one of the three conditions you are testing.
You should replace the three if statements with the following:
if(seat_type[i].equals(search_seat)) {
total += seat_cost[i];
System.out.println( reservation_code[i] + "," + fl_number[i] + "," + last_name[i] + "," + first_name[i] + "," + seat_type[i] + "," + seat_cost[i]);
}

Categories

Resources