Using ObservaleList to add element into ListView - java

I am having the problem with adding an array to ObservableList the use it to add that array into ListView. When I compiled, I got NullPointerException. This exception occurs when I call the listAllItems() method. If I do not use the GUI control, instead of using switch-statement and letting the user choose the option, then there are no exception occur at the run time. Could someone help me figure out what happen? Thanks
Requirement
Create a LibraryGUI class
◦ This class should have a Library object as one of its fields. In the LibraryGUI constructor
you will need to call the library constructor method to initialize this field and then call its
open() method to read in the items from the data file.
◦ Use a JList to display the contents of the library. Use the setListData method of the JList
class together with the listAllItems method of the Library class to keep the list current with
the library contents.
import javax.swing.JOptionPane;
public class MediaItem {
/*Fields*/
private String title;
private String format;
private boolean onLoan;
private String loanedTo;
private String dateLoaned;
/*Default Constructor - Initialize string variables for null and boolean variable for false*/
public MediaItem()
{
title = null;
format = null;
onLoan = false;
loanedTo = null;
dateLoaned = null;
}
/*Parameterized Constructor*/
public MediaItem(String title, String format)
{
this.title = title;
this.format = format;
this.onLoan = false;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
public boolean isOnLoan() {
return onLoan;
}
public void setOnLoan(boolean onLoan) {
this.onLoan = onLoan;
}
public String getLoanedTo() {
return loanedTo;
}
public void setLoanedTo(String loanedTo) {
this.loanedTo = loanedTo;
}
public String getDateLoaned() {
return dateLoaned;
}
public void setDateLoaned(String dateLoaned) {
this.dateLoaned = dateLoaned;
}
/*Mark item on loan*/
void markOnLoan(String name, String date){
if(onLoan == true)
JOptionPane.showMessageDialog(null,this.title + " is already loaned out to " + this.loanedTo + " on " + this.dateLoaned);
else {
onLoan = true;
loanedTo = name;
dateLoaned = date;
}
}
/*Mark item return*/
void markReturned(){
if(onLoan == false)
JOptionPane.showMessageDialog(null, this.title + " is not currently loaned out");
onLoan = false;
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JOptionPane;
import javafx.scene.control.TextInputDialog;
public class Library extends MediaItem {
/*Fields*/
private ArrayList<MediaItem> itemsList = new ArrayList<>();
public ArrayList<MediaItem> getItemsList() {
return itemsList;
}
public void setItemsList(ArrayList<MediaItem> itemsList) {
this.itemsList = itemsList;
}
public int displayMenu()
{
Scanner input = new Scanner(System.in);
System.out.println("\nMenu Options \n"
+"\n1. Add new item\n"
+"\n2. Mark an item as on loan\n"
+"\n3. List all item\n"
+"\n4. Mark an item as returned\n"
+"\n5. Quit\n"
+"\n\nWhat would you like to do?\n");
int choices = input.nextInt();
while (choices < 1 || choices >5)
{
System.out.println("I'm sorry, " + choices + " is invalid option");
System.out.println("Please choose another option");
choices = input.nextInt();
}
return (choices);
}
public void addNewItem(String title, String format)
{
MediaItem item = new MediaItem(); // the object of item
/*Use the JOptionPane.showInputDialog(null,prompt) to let the user input the title and the format
* store the title and the format to the strings and pass it to the parameter of addNewItem(String, String) method
* title and format will go through the loop if title already exited let the user input another title and format
* Using the same method JOptionPan.ShowInputDialog and JOptionPane.showMessage()
*/
boolean matches = false;
for(int i = 0; i< itemsList.size(); i++){
if(title.equals(itemsList.get(i).getTitle())){
String newTitle = JOptionPane.showInputDialog(null, "this " + title + " already exited. Please enter the title again");
String newFormat = JOptionPane.showInputDialog(null, "Enter the format again");
item = new MediaItem(newTitle,newFormat);
itemsList.add(item);
matches = true;
}
}if(!matches){
item = new MediaItem(title,format);
itemsList.add(item);
}
}
public void markItemOnLoan(String title, String name, String date)
{
boolean matches = false;
for(int i = 0; i < itemsList.size(); i++)
{ if (title.equals(itemsList.get(i).getTitle()))
{
itemsList.get(i).markOnLoan(name,date);
matches = true;
}
}
if (!matches)
{
JOptionPane.showMessageDialog(null,"I am sorry. I couldn't find " + title + " in the library");
}
}
public String[] listAllItems()
{
String[] list = new String[itemsList.size()];
for (int n = 0; n < itemsList.size(); n++)
{
if(itemsList.get(n).isOnLoan() == true)
list[n] = itemsList.get(n).getTitle() + " (" + itemsList.get(n).getFormat() + " ) loaned to " + itemsList.get(n).getLoanedTo() + " on " + itemsList.get(n).getDateLoaned();
else
list[n] = itemsList.get(n).getTitle() + " (" + itemsList.get(n).getFormat() + ")";
if(list[n] == null){
String title = "title ";
String format = "format ";
String loanTo = "name ";
String date = "date ";
list[n] = title + format + loanTo + date;
}
}
return list;
}
public void markItemReturned(String title)
{
boolean matches = false;
for( int i = 0; i < itemsList.size(); i++)
{
if(title.equals(itemsList.get(i).getTitle()))
{
matches = true;
itemsList.get(i).markReturned();
}
}
if(!matches)
{
JOptionPane.showMessageDialog(null,"I am sorry. I couldn't find " + title + " in the library");
}
}
public void deleteItem(String title){
boolean matches = false;
for(int i = 0; i < itemsList.size(); i++){
if(title.equals(itemsList.get(i).getTitle())){
itemsList.get(i).setTitle(null);
itemsList.get(i).setFormat(null);
itemsList.get(i).setDateLoaned(null);
itemsList.get(i).setLoanedTo(null);
itemsList.get(i).setOnLoan(false);
}
}
if(!matches)
JOptionPane.showMessageDialog(null,"I am sorry. I couldn't find " + title + " in the library");
}
public void openFile(){
Scanner input = null;
try{
input = new Scanner(new File("library.txt"));
Scanner dataInput = null;
MediaItem item = new MediaItem();
int index = 0;
String title = " ";
String format = " ";
String date = " ";
String onLoanTo = " ";
Boolean onLoan = false;
Boolean checkString= false;
Boolean checkBoolean = false;
itemsList = new ArrayList<>();
while(input.hasNextLine()){
dataInput = new Scanner(input.nextLine());
dataInput.useDelimiter("-");
while(input.hasNext()){
Boolean dataBoolean = dataInput.nextBoolean();
String dataString = dataInput.next();
if(index == 0){
item.setTitle(dataString);
title = item.getTitle();
checkString = true;
}else if(index == 1){
item.setFormat(dataString);
format = item.getFormat();
checkString= true;
}else if(index == 2){
item.setOnLoan(dataBoolean);
checkBoolean = true;
}else if(index == 3){
item.setLoanedTo(dataString);
checkString = true;
}else if(index == 4){
item.setDateLoaned(dataString);
checkString = true;
}else {
if(checkString == false)
throw new Exception("Invalid data " + dataString);
if(checkBoolean == false)
throw new Exception("Invalid data " + dataBoolean);
}
index++;
itemsList.add(new MediaItem(title,format));
}
index = 0;
title = " ";
format = " ";
date = " ";
onLoan = false;
onLoanTo = " ";
checkString= false;
checkBoolean = false;
}
}catch(Exception ex){
JOptionPane.showMessageDialog(null, ex.getMessage());
}finally{
if(input != null){
try{
input.close();
}catch(NullPointerException ex){
JOptionPane.showMessageDialog(null,"Error: File can not be closed");
}
}
}
}
public void saveFile(){
PrintWriter output = null;
try{
output = new PrintWriter(new File("library.txt"));
for(int i = 0; i < itemsList.size(); i++){
output.println(itemsList.get(i).getTitle() + "-" + itemsList.get(i).getFormat()+ "-" + itemsList.get(i).isOnLoan() + "-"
+ itemsList.get(i).getLoanedTo() + "-" + itemsList.get(i).getDateLoaned());
}
}catch(FileNotFoundException e1){
JOptionPane.showMessageDialog(null,"Could not find the data file. Program is exiting.");
}catch(IOException e2){
JOptionPane.showMessageDialog(null, "Something went wrong with writing to the data file.");
}catch(Exception e3){
JOptionPane.showMessageDialog(null,"Something went wrong.");
}
finally{
if( output != null){
try{
output.close();
System.exit(0);
}catch (NullPointerException e4){
JOptionPane.showMessageDialog(null, "Error: File can not be closed");
}
}
}
}
}
enter code here
import java.util.ArrayList;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
public class LibraryGUI extends Application{
private ListView<String> listView;
private Library library;
private Button btAdd, btCheckIn, btCheckOut, btDelete;
public void LibraryGUI(){
library = new Library();
library.openFile();
}
public void start(Stage primaryStage) throws Exception {
listView = new ListView<>();
//Add all item in the listAllItem() method to the list view
String[] list = library.listAllItems();
int length = library.getItemsList().size();
for (int i = 0; i < length; i++)
{
ObservableList<String> element = FXCollections.observableArrayList( list[i].toString());
listView.setItems(element);
}
listView.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
btAdd = new Button(" Add");
btCheckIn = new Button(" CheckIn ");
btCheckOut = new Button(" CheckOut ");
btDelete = new Button(" Delete ");
FlowPane flowP = new FlowPane();
listView.setPrefSize(400, 275);
btAdd.setPrefSize(100, 25);
btAdd.setAlignment(Pos.BOTTOM_LEFT);
btCheckIn.setPrefSize(100, 25);
btCheckIn.setAlignment(Pos.BOTTOM_LEFT);
btCheckOut.setPrefSize(100, 25);
btCheckOut.setAlignment(Pos.BOTTOM_LEFT);
btDelete.setPrefSize(100,25);
btDelete.setAlignment(Pos.BOTTOM_LEFT);
flowP.getChildren().addAll(listView,btAdd,btCheckIn,btCheckOut,btDelete);
Scene scene = new Scene (flowP,400,300);
primaryStage.setTitle("Calculator");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Code for Switch-Statement
import java.util.Scanner;
public class Code8 {
public static void main(String[] args) {
MediaItem newItem = new MediaItem();
Library library = new Library();
Scanner in = new Scanner(System.in);
int option = 0;
while (option != 5)
{
option = library.displayMenu();
switch(option)
{
case 1:
System.out.print("What is the title? ");
String newTitle = in.nextLine();
newItem.setTitle(newTitle);
System.out.println("What is the format? ");
String newFormat = in.nextLine();
newItem.setFormat(newFormat);
library.addNewItem(newTitle, newFormat);
break;
case 2:
System.out.println("Which item (enter the title)? ");
newTitle = in.nextLine();
newItem.setTitle(newTitle);
System.out.println("Who are you loaning it to? ");
String name = in.nextLine();
newItem.setLoanedTo(name);
System.out.println("When did you loan it to them? ");
String date = in.nextLine();
library.markItemOnLoan(newTitle, name, date);
break;
case 3:
String[] list = library.listAllItems();
int length = library.getItemsList().size();
for (int i = 0; i < length; i++)
{
System.out.println(list[i].toString());
}
break;
case 4:
System.out.println("Which item (enter the title)? ");
newTitle = in.nextLine();
newItem.setTitle(newTitle);
library.markItemReturned(newTitle);
break;
case 5:
System.out.println("Goodbye");
break;
}// switch statement
}//while statement
} //main method
}

Related

How to solve problem with list's constructor of static function in Java?

I have problem with putting values to my list in static switch. I have seen this can be easier done with String[] but for educational reasons please see my logical code to help me see where the problem is.
Bulding a String of this list is so easy, surely the problems is somewhere with filling my list with data but still can't see how to solve it.
When I try to print data nothing shows every time:(
package Loop2_hospital;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Scanner;
import java.util.stream.Stream;
public class Hospital {
public static void main(String[] args) {
List<Patient> listToDisplay = new ArrayList<>();
boolean exit = false;
Scanner in = new Scanner(System.in);
do {
System.out.println("0 - wyjście z programu, 1 - dopisanie pacjenta, 2 - wyświetlenie listy zapisanych pacjentów.");
int nr = in.nextInt();
isExit(listToDisplay, nr, exit);
} while (exit != true);
}
public static void isExit(List<Patient> listToDisplay, int nr, boolean exit) {
int actualPatientsNumber = 0;
int MaxPatientsAmount = 10;
Hospital ref3 = new Hospital();
Patient patient = new Patient();
switch (nr) {
case 0:
exit = true;
break;
case 1:
Scanner in2 = new Scanner(System.in);
System.out.println("Podaj imię pacjenta ");
String name = in2.nextLine();
System.out.println("Podaj nazwisko pacjenta");
String secondName = in2.nextLine();
System.out.println("Podaj PESEL pacjenta");
int PEELER = in2.nextInt();
if (actualPatientsNumber < MaxPatientsAmount){
actualPatientsNumber++;
Patient tmp = new Patient(name, secondName, PEELER);
listToDisplay.add((tmp));}
break;
case 2:
display(listToDisplay);
break;
default:
System.out.println("Podaj właściwy nr przy wyborze operacji");
break;
}
}
public static void display(List<Patient> listToDisplay) {
if(listToDisplay != null){
StringBuilder words = new StringBuilder();
for (Patient one : listToDisplay){
words.append(one);
}
System.out.println(words);
}
// final String d = listToDisplay.toString();
// System.out.println(d);
// Stream.of(listToDisplay).peek(System.out::println);
// System.out.println("Zapisani pacjenci: ");
// for (int i = 0; i < actualPatientsNumber; i++) {
// System.out.println(listToDisplay.get(i).getName() + " " + listToDisplay.get(i).getSecondName() + " nr PESEL: " + listToDisplay.get(i).getPEEL_NR());
}
}
package Loop2_hospital;
public class Patient {
String name;
String secondName;
int PEELER;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSecondName() {
return secondName;
}
public void setSecondName(String secondName) {
this.secondName = secondName;
}
public int getPEEL_NR() {
return PEELER;
}
public void setPEEL_NR(int PEEL_NR) {
this.PEELER = PEEL_NR;
}
public Patient() {}
public Patient(String name, String secondName, int PEELER) {
this.name = name;
this.secondName = secondName;
this.PEELER = PEELER;
}
}
I tried following the suggestions given in the comments, but it's still not working.
package Loop2_hospital;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Scanner;
public class Hospital {
public static void main(String[] args) {
List<Patient> listToDisplay = new ArrayList<>();
boolean exit = false;
Scanner in = new Scanner(System.in);
do {
System.out.println("0 - wyjście z programu, 1 - dopisanie pacjenta, 2 - wyświetlenie listy zapisanych pacjentów.");
int nr = in.nextInt();
if (!Objects.equals(nr, 0)){
isExit(listToDisplay, nr, exit);}
else exit = true;
} while (exit != true);
}
public static boolean isExit(List<Patient> listToDisplay, int nr, boolean exit) {
int actualPatientsNumber = 0;
int MaxPatientsAmount = 10;
Hospital ref3 = new Hospital();
Patient patient = new Patient();
switch (nr) {
case 0:
return true;
case 1:
Scanner in2 = new Scanner(System.in);
System.out.println("Podaj imię pacjenta ");
String name = in2.nextLine();
System.out.println("Podaj nazwisko pacjenta");
String secondName = in2.nextLine();
System.out.println("Podaj PESEL pacjenta");
int PEELER = in2.nextInt();
if (actualPatientsNumber < MaxPatientsAmount){
actualPatientsNumber++;
Patient tmp = new Patient(name, secondName, PEELER);
listToDisplay.add((tmp));}
break;
case 2:
display(listToDisplay);
break;
default:
System.out.println("Podaj właściwy nr przy wyborze operacji");
break;
}
return false;
}
public static void display(List<Patient> listToDisplay) {
if(listToDisplay != null){
StringBuilder words = new StringBuilder();
for (Patient one : listToDisplay){
words.append(one);
}
System.out.println(words);
}
// final String d = listToDisplay.toString();
// System.out.println(d);
// Stream.of(listToDisplay).peek(System.out::println);
// System.out.println("Zapisani pacjenci: ");
// for (int i = 0; i < actualPatientsNumber; i++) {
// System.out.println(listToDisplay.get(i).getName() + " " + listToDisplay.get(i).getSecondName() + " nr PESEL: " + listToDisplay.get(i).getPEEL_NR());
}
}

Can't seem to get it to write to an arrayList and then to a file

I have been working on this and can't seem to get it to run correctly. It should create an arraylist then add, remove, mark as loaned, mark as returned, and write to a file when you quit. I can't find what I messed up.
package cs1181proj1;
import static cs1181proj1.Media.media;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
/**
*
* #author Veteran
*/
public class CS1181Proj1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// Create ArrayList and mediaFile.
ArrayList<Media> Item = new ArrayList<>();
Scanner keyboard = new Scanner(System.in);
File mediaFile = new File("mediaFile.dat");
String Title;
String Format;
String loanedTo = null;
String dateLoaned = null;
int number = 0;
if (mediaFile.exists()) {
try {
try (ObjectInputStream dos = new ObjectInputStream(
new FileInputStream(mediaFile))) {
Item = (ArrayList<Media>) dos.readObject();
}
} catch (FileNotFoundException a) {
System.out.println("Thou hast erred! The file doth not exist!");
} catch (IOException b) {
System.out.println("GIGO My Lord or Lady!");
} catch (ClassNotFoundException c) {
System.out.println("Avast! I am in a quandry");
}
}
//Print out menu of choices
while (number != 6) {
System.out.println("");
System.out.println("1. Add new media item");
System.out.println("2. Mark an item out on loan");
System.out.println("3. Mark an item as Returned");
System.out.println("4. List items in collection");
System.out.println("5. Remove a media item");
System.out.println("6. Quit");
System.out.println("");
//accept users menu choice
try {
number = keyboard.nextInt();
} catch (InputMismatchException e) {
System.out.println("That's not a number between 1 and ` `6. IS IT!");
}
//Switch to tell program what method to use depending on user ` `//option
switch (number) {
case 1:
insert();
break;
case 2:
onLoan();
break;
case 3:
returned();
break;
case 4:
list();
break;
case 5:
removeItem();
break;
case 6:
System.out.println("Goodbye");
Quit(mediaFile);
break;
}
}
}
//Method for inserting items in arraylist
public static void insert() {
ArrayList<Media> media = new ArrayList<>();
System.out.println("New titles name");
Scanner newEntry = new Scanner(System.in);
String title = newEntry.nextLine();
System.out.println("");
//title of media
while (titleAlreadyExists(title, media)) {
System.out.println("Title already exists");
title = newEntry.nextLine();
System.out.println("");
}
//format of media
System.out.println("What format");
String format = newEntry.nextLine();
media.add(new Media(title, format));
System.out.println("Your entry has been created.");
}
//In case entry already exists
public static boolean titleAlreadyExists(
String title, ArrayList<Media> media) {
for (Media entry : media) {
if (entry.getTitle().equals(title)) {
return true;
}
}
return false;
}
//Method for putting item on loan
public static void onLoan() {
System.out.println("Enter name of Title on loan");
Scanner newLoan = new Scanner(System.in);
ArrayList<Media> media = new ArrayList<>();
String loanTitle = newLoan.nextLine();
System.out.println("Who did you loan this to");
Scanner To = new Scanner(System.in);
String loanedTo = To.nextLine();
System.out.println("");
System.out.println("When was it lent out?");
Scanner date = new Scanner(System.in);
String dateLoaned = date.nextLine();
System.out.println("");
for (Media title : media) {
if (title.getTitle().equals(loanTitle)) {
title.setDateLoaned(dateLoaned);
title.setloanedTo(loanedTo);
System.out.println(title + " loaned to " + loanedTo + ` `"on date" + dateLoaned + "is listed as loaned");
}
}
}
//Method for returning item in collection
public static void returned() {
System.out.println("Enter name of Title returned");
Scanner returned = new Scanner(System.in);
ArrayList<Media> media = new ArrayList<>();
String returnedTitle = returned.nextLine();
String loanedTo = null;
String dateLoaned = null;
System.out.println("");
for (Media title : media) {
if (title.getTitle().equals(returnedTitle)) {
title.setDateLoaned(dateLoaned);
title.setloanedTo(loanedTo);
System.out.println(title + "is listed as returned");
}
}
}
//Method for listing items in collection
public static void list() {
System.out.println("Your collection contains:");
for (int i = 0; i < media.size(); i++) {
System.out.print((media.get(i)).toString());
System.out.println("");
}
}
//method for removing an item from the collection
private static void removeItem() {
System.out.println("What item do you want to remove?");
Scanner remover = new Scanner(System.in);
ArrayList<Media> media = new ArrayList<>();
String removeTitle = remover.nextLine();
System.out.println("");
media.stream().filter((title) -> ` ` (title.getTitle().equals(removeTitle))).forEach((title) -> {
media.remove(removeTitle);
System.out.println(title + "has been removed");
});
}
//method for saving to file when the user quits the program.
//To ensure there is no data loss.
public static void Quit(File mediaFile) {
try {
ArrayList<Media> media = new ArrayList<>();
try (ObjectOutputStream oos = new ObjectOutputStream(new ` ` FileOutputStream(mediaFile))) {
oos.writeObject(media);
System.out.println("Your file has been saved.");
}
} catch (IOException e) {
System.out.println("Unable to write to file. Data not ` `saved");
}
}
}
Here is its companion media file:
package cs1181proj1;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Comparator;
/**
*
* #author Veteran
*/
public class Media implements Serializable {
static ArrayList<String> media = new ArrayList<>();
private String Title;
private String Format;
private String loanedTo = null;
private String dateLoaned = null;
Media() {
this.Title = ("Incorrect");
this.Format = ("Incorrect");
this.loanedTo = ("Available");
this.dateLoaned = ("Available");
}
Media(String Title, String Format) {
this.Title = Title;
this.Format = Format;
this.loanedTo = ("Available");
this.dateLoaned = ("Available");
}
//Get and Set Title
public String getTitle() {
return this.Title;
}
public void setTitle(String Title) {
this.Title = Title;
}
//Get and Set Format
public String getFormat() {
return this.Format;
}
public void setFormat(String Format) {
this.Format = Format;
}
//Get and Set loanedTo
public String getLoanedTo() {
return this.loanedTo;
}
public void setloanedTo (String loanedTo){
this.loanedTo = loanedTo;
}
//Get and set dateLoaned
public String getDateLoaned() {
return this.dateLoaned;
}
public void setDateLoaned(String dateLoaned){
this.dateLoaned = dateLoaned;
}
#Override
public String toString(){
return this.Title + ", " + this.Format +", " + this.loanedTo + ", "
+ this.dateLoaned;
}
public static Comparator <Media> TitleComparator = new Comparator <Media>(){
#Override
public int compare(Media t, Media t1) {
String title = t.getTitle().toUpperCase();
String title1 = t1.getTitle().toUpperCase();
return title.compareTo(title1);
}
};
}

Why is my quizzcount doubling its value

I'm having a problem with this code in that the quizzcount variable is not outputting the correct value, it doubles the value.
I found a work around by diving the quizzcount by 2 and it works but i would really like to figure out why its doubling the value.
So for example, without dividing quizzcount by 2, if the user gets 7 out of the 10 questions correct the messagedialog will display that the user got 14 out of 10 correct.
What is causing this?
Thanks guys, any help would be appreciated.
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InvalidClassException;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.*;
import java.util.*;
import java.awt.* ;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.Image;
import java.lang.*;
public class MathFiles extends JFrame implements ActionListener
{
private ObjectOutputStream toFile;
private String name;
private boolean open;
private static String response;
private static int menuOption = 0;
private static int numberOfMaths = 0;
private FileInputStream fis;
private ObjectInputStream fromFile;
Math aMath = null;
private int quizcount =0;
String checkbutton = "";
private static int tracker =1;
int count = 0;
int fimage =0;
JRadioButton questA, questB, questC, questD, questE;
ButtonGroup questGroup;
JPanel questPanel;
JLabel question;
JPanel questionPanel;
JTextField resultText;
JLabel resultLabl;
JPanel resultPanel;
JButton nextButton;
JPanel quizPanel;
ImageIcon image;
JLabel imageLabl;
JPanel imagePanel;
JTextArea questionText;
JScrollPane scrollPane;
Random rand;
/** #param fileName is the desired name for the binary file. */
public MathFiles()
{
setTitle( "Math Quiz Competition" );
rand = new Random();
toFile = null;
//tracker = rand.nextInt(5)+1;
tracker = 1;
name = "Quiz"+tracker+".txt";
open = false;
//openFile(); //Use only when creating file
//writeMathsToTextFile(name);
setLayout( new FlowLayout() );
inputFile();
beginquiz();
showquestions();
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
} // end MathFiles constructor
/** Writes all Maths from a text file and writes them to a binary file.
#param fileName the text file */
public void writeMathsToTextFile(String fileName)
{
Scanner inputFile = null;
Math nextMath = null;
String question_num;
String question;
String answera;
String answerb;
String answerc;
String answerd;
String answer_cor;
String file_name;
String SENTINEL ="DONE";
try
{
inputFile = new Scanner(new File(fileName));
}
catch(FileNotFoundException e)
{
System.out.println("Text file " + fileName + " not found.");
System.exit(0);
}
Scanner keyboard = new Scanner(System.in);
System.out.print("Question number: ");
question_num = keyboard.nextLine();
while (!question_num.equalsIgnoreCase(SENTINEL))
{
System.out.print("Question: ");
question = keyboard.nextLine();
System.out.print("Answer A: ");
answera = keyboard.nextLine();
System.out.print("Answer B: ");
answerb = keyboard.nextLine();
System.out.print("Answer C: ");
answerc = keyboard.nextLine();
System.out.print("Answer D: ");
answerd = keyboard.nextLine();
fimage = rand.nextInt(30)+1;
file_name = "image"+fimage+".gif";
System.out.print(file_name);
System.out.print("Correct Answer: ");
answer_cor = keyboard.nextLine();
nextMath = new Math(question_num, question, answera, answerb,
answerc, answerd, answer_cor, file_name);
writeAnObject(nextMath);
numberOfMaths++;
System.out.print("\nQuestion number: ");
question_num = keyboard.nextLine();
} // end while
System.out.println("successfully created = " + name);
} // end readMathsFromTextFile
/** Opens the binary file for output. */
public void openFile()
{
try
{
FileOutputStream fos = new FileOutputStream(name);
toFile = new ObjectOutputStream(fos);
open = true;
}
catch (FileNotFoundException e)
{
System.out.println("Cannot find, create, or open the file " + name);
System.out.println(e.getMessage());
open = false;
}
catch (IOException e)
{
System.out.println("Error opening the file " + name);
System.out.println(e.getMessage());
open = false;
}
//System.out.println("successfully opened = " + name);
} // end openFile
/** Writes the given object to the binary file. */
public void writeAnObject(Serializable anObject)
{
try
{
if (open)
toFile.writeObject(anObject);
}
catch (InvalidClassException e)
{
System.out.println("Serialization problem in writeAnObject.");
System.out.println(e.getMessage());
System.exit(0);
}
catch (IOException e)
{
System.out.println("Error writing the file " + name);
System.out.println(e.getMessage());
System.exit(0);
}
} // end writeAnObject
public void result()
{
System.out.println("Your score is");
}
public void inputFile()
{
try
{
fromFile = new ObjectInputStream(new FileInputStream(name));
}
catch(StreamCorruptedException e)
{
System.out.println("Error in input stream: " + name);
System.out.println(e.getMessage());
System.exit(0);
}
catch(IOException e)
{
System.out.println("Error reading input stream: " + name);
System.out.println(e.getMessage());
System.exit(0);
}
} // end displayFile
/** Closes the binary file. */
public void closeFile()
{
System.out.println("closed name = " + name);
try
{
toFile.close();
open = false;
}
catch (IOException e)
{
System.out.println("Error closing the file " + name);
System.out.println(e.getMessage());
System.exit(0);
}
} // end closeFile
/** #return the fileís name as a string */
public String getName()
{
return name;
} // end getName
/** #return true if the file is open */
public boolean isOpen()
{
return open;
} // end isOpen
public void beginquiz()
{
try
{
aMath = (Math)fromFile.readObject();
}
catch (ClassNotFoundException e)
{
System.out.println("The class Math is not found.");
System.out.println(e.getMessage());
System.exit(0);
}
catch(StreamCorruptedException e)
{
System.out.println("Error in input stream: " + name);
System.out.println(e.getMessage());
System.exit(0);
}
catch(IOException e)
{
System.out.println("Error reading input stream: " + name);
System.out.println(e.getMessage());
System.exit(0);
}
}
void showquestions()
{
//question group
/*question = new JLabel();
question.setText(aMath.getquestion());
question.setFont(new Font("Arial", Font.BOLD, 20));
question.setForeground(Color.BLUE);
questionPanel = new JPanel();
questionPanel.add( question );*/
questionText = new JTextArea(5,20);
questionText.setWrapStyleWord(true);
questionText.setLineWrap(true);
questionText.setText(aMath.getquestion());
questionText.setFont(new Font("Arial", Font.BOLD, 20));
questionText.setForeground(Color.BLUE);
questionPanel = new JPanel();
questionPanel.setLayout(new BoxLayout(questionPanel, BoxLayout.PAGE_AXIS));
questionPanel.add( questionText );
// quest group
questA = new JRadioButton(aMath.getanswera(), false );
questB = new JRadioButton(aMath.getanswerb(), false );
questC = new JRadioButton(aMath.getanswerc(), false );
questD = new JRadioButton(aMath.getanswerd(), false );
questGroup = new ButtonGroup();
questGroup.add( questA );
questGroup.add( questB );
questGroup.add( questC );
questGroup.add( questD );
questPanel = new JPanel();
questPanel.setLayout( new BoxLayout( questPanel, BoxLayout.Y_AXIS ) );
questPanel.add( new JLabel("Choose the Correct Answer") );
questPanel.add( questA );
questPanel.add( questB );
questPanel.add( questC );
questPanel.add( questD );
// result panel
//resultText = new JTextField(20);
//resultText.setEditable( false );
//resultLabl = new JLabel("Result");
//resultPanel = new JPanel();
//resultPanel.add( resultLabl );
//resultPanel.add( resultText );
//button
nextButton = new JButton("Next");
quizPanel = new JPanel();
quizPanel.add(nextButton);
//Image image1 = new ImageIcon("image/image1.gif").getImage();
image = new ImageIcon("image1.gif");
imageLabl=new JLabel(image);
imagePanel = new JPanel();
imagePanel.add(imageLabl);
// frame: use default layout manager
add( imagePanel);
add( questionPanel);
add( questPanel);
//add( resultPanel);
questA.setActionCommand(aMath.getanswera());
questB.setActionCommand(aMath.getanswerb());
questC.setActionCommand(aMath.getanswerc());
questD.setActionCommand(aMath.getanswerd());
questA.addActionListener(this);
questB.addActionListener(this);
questC.addActionListener(this);
questD.addActionListener(this);
nextButton.setActionCommand( "next" ); // set the command
// register the buttonDemo frame
// as the listener for both Buttons.
nextButton.addActionListener( this );
add(quizPanel);
}
public void actionPerformed( ActionEvent evt)
{
//evt.getActionCommand() = aMath.getanswer_cor();
if (questA.isSelected()&&
aMath.getanswera().equalsIgnoreCase(aMath.getanswer_cor().trim()))
quizcount++;
if (questB.isSelected()&&
aMath.getanswerb().equalsIgnoreCase(aMath.getanswer_cor().trim()))
quizcount++;
if (questC.isSelected()&&
aMath.getanswerc().equalsIgnoreCase(aMath.getanswer_cor().trim()))
quizcount++;
if (questD.isSelected()&&
aMath.getanswerd().equalsIgnoreCase(aMath.getanswer_cor().trim()))
quizcount++;
if(questA.isSelected() || questB.isSelected() || questC.isSelected() || questD.isSelected())
if ( evt.getActionCommand().equals( "next" ))
{
try
{
aMath = (Math)fromFile.readObject();
questionText.setText(aMath.getquestion());
questA.setText(aMath.getanswera());
questB.setText(aMath.getanswerb());
questC.setText(aMath.getanswerc());
questD.setText(aMath.getanswerd());
imageLabl.setIcon(new ImageIcon(aMath.getfile()));
questGroup.clearSelection();
repaint();
}
catch (ClassNotFoundException e)
{
System.out.println("The class Math is not found.");
System.out.println(e.getMessage());
System.exit(0);
}
catch(StreamCorruptedException e)
{
System.out.println("Error in input stream: " + name);
System.out.println(e.getMessage());
System.exit(0);
}
catch(IOException e)
{
if (count<=0)
count = 0;
else
count--;
JOptionPane.showMessageDialog(null,"Your score is "+quizcount/2 +" out of 10");
try{
Thread.sleep(2000);
System.exit(0);
}catch (InterruptedException em) { }
}
}
}
public static void main ( String[] args )
{
MathFiles mat = new MathFiles();
mat.setSize( 450, 550 );
mat.setLocationRelativeTo(null);
mat.setResizable( false );
mat.setVisible( true );
}
} // end MathFiles
class Math implements java.io.Serializable
{
private String question_num;
private String question;
private String answera;
private String answerb;
private String answerc;
private String answerd;
private String answer_cor;
private String file_name;
public Math(String quesno, String quest, String ansa, String ansb, String ansc,
String ansd, String ans_cor, String file)
{
question_num = quesno;
question = quest;
answera = ansa;
answerb = ansb;
answerc = ansc;
answerd = ansd;
answer_cor = ans_cor;
file_name = file;
}
public void setquestion(String lName)
{
question = lName;
} // end setquestion
public void setquestion_num(String fName)
{
question_num = fName;
} // end setquestion_num
public void setanswera(String add)
{
answera = add;
} // end setanswera
public void setanswerb(String cty)
{
answerb = cty;
} // end setanswerb
public void setanswerc(String st)
{
answerc = st;
} // end setanswerc
public void setanswerd(String z)
{
answerd = z;
} // end setanswerd
public void setanswer_cor(String phn)
{
answer_cor = phn;
} // end setanswer_corr
public String getquestion_num()
{
return question_num;
} // end getquestion_num
/** #return the question */
public String getquestion()
{
return question;
} // end getquestion
/** #return the answera*/
public String getanswera()
{
return answera;
} // end getanswera
/** #return the answerb */
public String getanswerb()
{
return answerb;
} // end getanswerb
public String getanswerc()
{
return answerc;
} // end getanswerc
public String getanswerd()
{
return answerd;
} // end getanswerd
public String getanswer_cor()
{
return answer_cor;
} // end getanswer_corr
public String getfile()
{
return file_name;
} // end getanswer_corr
/** #return the Math information */
public String toString()
{
String myMath = getquestion_num() + " " + getquestion() + "\n";
myMath += getanswera() + "\n";
myMath += getanswerb() + " " + getanswerc() + " " + getanswerd() + "\n";
myMath += getanswer_cor() + "\n";
myMath += getfile() + "\n";
return myMath;
} // end toString
} // end Math
It looks like your problem is that you've registered ActionListeners on the radio buttons. This means the event fires when you select an answer as well as clicking the 'next' button. With that in mind it should be obvious why your score is doubling itself.
As far as I can tell you don't need ActionListeners for the radio buttons. You should only be checking the answer when the user has indicated they are done with their selection. That the score is exactly doubling itself also suggests that you basically haven't tested the program besides naively selecting a radio button and clicking 'next'. Before commenting out the lines where you add the listeners to the radio buttons, try changing your answer. Open the program, select the correct answer, then select an incorrect answer, then select the correct answer again and click 'next'. See what happens.
This kind of error can also be easily found with a debugger. Just insert a breakpoint inside actionPerformed and it will be obvious it's being called by more than one action.

No suitable constructor found for FacultyListFrame1

I am working on a creating a simple GUI window to manage faculty list,
The error i have is :
--------------------Configuration: FacultyListFrame1 - JDK version 1.7.0_02 <Default> - <Default>--------------------
C:\Users\lm_b116\Documents\JCreator Pro\MyProjects\Myfaculty\FacultyListFrame1.java:175: error: no suitable constructor found for Faculty(String,Name,MyDate,boolean)
Facultylistframe[noOfFaculty++] = new Faculty(ssnS,new Name(firstName,lastName), new MyDate(month, day, year),selectedStatus);
^
constructor Faculty.Faculty(int,Name,MyDate,double,boolean) is not applicable
(actual and formal argument lists differ in length)
constructor Faculty.Faculty(int,Name,MyDate) is not applicable
(actual and formal argument lists differ in length)
Note: C:\Users\lm_b116\Documents\JCreator Pro\MyProjects\Myfaculty\FacultyListFrame1.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error
I would really appreciate any help,
The code for FacultyListFrame1 is :
import java.awt.FlowLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.Scanner;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import java.awt.*;
public class FacultyListFrame1 extends JFrame {
private JButton store;
private JTextArea outputTextArea;
private JTextField fname, lname, dmonth, dday, dyear, ssalary,nssn,fstatus;
Faculty Facultylistframe[];
JComboBox statusSelection;
int noOfFaculty;
String[] status={"Fulltime","Parttime"};
public FacultyListFrame1(int num) {
super("Faculty List");
setLayout(new FlowLayout());
Facultylistframe = new Faculty[num];
noOfFaculty = 0;
JLabel jl1 = new JLabel("First Name:");
add(jl1);
fname = new JTextField(22);
add(fname);
JLabel jl2 = new JLabel("Last Name");
add(jl2);
lname = new JTextField(22);
add(lname);
JLabel jl7 = new JLabel("SSN:");
add(jl7);
nssn = new JTextField(20);
add(nssn);
JLabel jl8 = new JLabel("Salary:");
add(jl8);
ssalary = new JTextField(20);
add(ssalary);
JLabel jl9 = new JLabel("Status:");
add(jl9);
statusSelection= new JComboBox(status);
statusSelection.setMaximumRowCount(2);
add(statusSelection);
JLabel jl4 = new JLabel("Birthdate: MM");
add(jl4);
dmonth = new JTextField(3);
add(dmonth);
JLabel jl5 = new JLabel("DD");
add(jl5);
dday = new JTextField(3);
add(dday);
JLabel jl6 = new JLabel("Year");
add(jl6);
dyear = new JTextField(5);
add(dyear);
store = new JButton("Store Data");
store.addActionListener(new buttonEvent());
add(store);
outputTextArea = new JTextArea();
add(outputTextArea);
}
public static void main(String[] args) {
final int SIZEOFARRAY = 10;
FacultyListFrame1 plFrame = new FacultyListFrame1(SIZEOFARRAY);
plFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
plFrame.setSize(380, 500);
plFrame.setLocation(500, 200);
plFrame.setVisible(true);
}
private class buttonEvent implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() != store) return;
{
String firstName = fname.getText();
if (firstName.length() == 0) {
JOptionPane.showMessageDialog(null, "No first name",
"Warning", JOptionPane.WARNING_MESSAGE);
return;
}
String lastName = lname.getText();
if (lastName.length() == 0) {
JOptionPane.showMessageDialog(null, "No last name",
"Warning", JOptionPane.WARNING_MESSAGE);
return;
}
String ssnS = nssn.getText();
int ssn;
if (ssnS.length() == 0) ssn = -1;
else
try {
ssn = Integer.parseInt(ssnS);
} catch (NumberFormatException ne) { ssn = -1; }
if (ssn < 0) {
JOptionPane.showMessageDialog(null, "Invalid SSN",
"Warning", JOptionPane.WARNING_MESSAGE);
return;
}
String salaryS = ssalary.getText();
int salary;
if (salaryS.length() == 0) ssn = -1;
else
try {
salary = Integer.parseInt(ssnS);
} catch (NumberFormatException ne) { ssn = -1; }
if (salary < 0) {
JOptionPane.showMessageDialog(null, "Invalid Salary",
"Warning", JOptionPane.WARNING_MESSAGE);
return;
}
String monthS = dmonth.getText();
int month, day, year;
try {
month = Integer.parseInt(monthS);
} catch (NumberFormatException ne) { month = 0; }
String dayS = dday.getText();
try {
day = Integer.parseInt(dayS);
} catch (NumberFormatException ne) { day = 0; }
String yearS = dyear.getText();
try {
year = Integer.parseInt(yearS);
} catch (NumberFormatException ne) { year = -1; }
int ret = MyDate.checkDate(month, day, year);
if (ret != 0) {
String t="";
switch (ret) {
case 1: t = "Month"; break;
case 2: t = "Day"; break;
case 3: t = "Year"; break;
}
JOptionPane.showMessageDialog(null, t + " is invalid",
"Warning", JOptionPane.WARNING_MESSAGE);
return;
}
fname.setText("");
lname.setText("");
nssn.setText("");
dmonth.setText("");
dday.setText("");
dyear.setText("");
ssalary.setText("");
int j=statusSelection.getSelectedIndex();
boolean selectedStatus=true;
if(j>0) selectedStatus=false;
if (noOfFaculty < Facultylistframe.length)
Facultylistframe[noOfFaculty++] = new Faculty(ssnS,new Name(firstName,lastName), new MyDate(month, day, year),selectedStatus);
else
JOptionPane.showMessageDialog(null, "Faculty List is full", "Warning", JOptionPane.WARNING_MESSAGE);
outputTextArea.setText("Last-Name\t First-Name\t SSN\t Salary\t Birth-Date\n");
for (int i=0; i<Facultylistframe.length; i++) {
if (Facultylistframe[i]!=null)
outputTextArea.append(Facultylistframe[i].toString() + "\n");
}
}
}
}
}
.......................................................................................
Sorry
here is the code for Faculty
public class Faculty extends Person{
private double salary;
private boolean fullTime;
public Faculty (int ssn, Name name, MyDate birth)
{
super(ssn, name, birth);
}
public Faculty (int ssn, Name name, MyDate birth, double salary, boolean f)
{
super(ssn, name, birth);
this.salary = salary;
fullTime = f;
}
public void setSalary (double salary)
{
this.salary = salary;
}
public double getSalary()
{
return salary;
}
public void setFullTime (boolean f)
{
fullTime = f;
}
public boolean getFullTime()
{
return fullTime;
}
public String toString()
{
String faculty = new String ("");
if (fullTime == false)
faculty = super.toString() + "\t" + salary + "\t part time ";
else
faculty = super.toString() + "\t" + salary + "\t full time ";
return faculty;
}
}
You are attempting to pass 4 arguments, but according to the error message, the constructors for Faculty expect either 3 or 5 arguments.
Either don't pass your selectedStatus variable to the constructor, to match Faculty(int,Name,MyDate), or include a double value before selectedStatus to match Faculty(int,Name,MyDate,double,boolean).
Another alternative: create the 4-argument constructor to match what you are attempting to call: Faculty(int,Name,MyDate,boolean).

Unable to print console output in same format onto text document

I have my java file set up to calculate a phone bill and print out to the console in this format.
Invoice
--------------------------
Account Amount Due
10011 $12.25
10033 $11.70
--------------------------
Total $23.95
but when I run the program I only get this on the text file
Account Amount_Due
10011 $12.25
10033 $11.7
Can someone help me edit my filecreating code in correct format?
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.Vector;
public class PhoneBill {
Vector data;
Vector processed = new Vector();
Vector markProcessed = new Vector();
public void readFile(String inFileStr)
{
String str = "";
data = new Vector<LineItem>();
FileReader fReader;
InputStream inFileStream;
try{
fReader = new FileReader(inFileStr);
BufferedReader br=new BufferedReader(fReader);
String line;
while ((line=br.readLine())!= null){
if (line.indexOf("_") != -1)
continue;
else
if (!line.isEmpty()){
data.add(new LineItem(line.trim()));
}
}
br.close();
}
catch (Exception e){
}
}
public void processCharges()
{
String out = "Account Amount_Due\n";
System.out.println ("Invoice");
System.out.println ("--------------------------");
System.out.println ("Account " + "Amount Due ");
double total = 0.0;
double lCharges =0;
boolean done = false;
DecimalFormat numFormatter = new DecimalFormat("$##.##");
for (int j = 0; j < data.size(); j++ ){
LineItem li = (LineItem)data.get(j);
String accNum = li.getAccountNum();
if (j > 0){
done = checkProcessed(accNum);}
else
processed.add(accNum);
if (!done){
lCharges = 0;
for (int i = 0; i < data.size(); i++){
String acc = ((LineItem)data.get(i)).getAccountNum();
if (acc.equals(accNum) && !done)
lCharges += processItemCharges(accNum);
done = checkProcessed(accNum);
}
lCharges+=10.0;
System.out.format ("%s" + " $%.2f%n",accNum, lCharges);
out += accNum+" ";
out += numFormatter.format(lCharges)+"\n";
processed.add(accNum);
total += lCharges;
}
}
System.out.println ("--------------------------");
System.out.format ("%s" + " $%.2f%n","Total", total);
writeToFile("invoice.txt", out);
}
private void writeToFile(String filename,String outStr)
{
try{
File file = new File(filename);
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(outStr);
bw.close();
} catch (IOException ioe){
System.out.println(ioe.getMessage());
}
}
private boolean checkProcessed(String accNum){
if (processed.contains(accNum))
return true;
else
return false;
}
private double processItemCharges(String accNum)
{
double charges = 0.0;
for (int i = 0; i < data.size(); i++)
{
if(((LineItem)data.get(i)).getAccountNum().equals(accNum))
charges += ((LineItem)data.get(i)).getCharges();
}
return charges;
}
public static void main(String[] args)
{
PhoneBill pB = new PhoneBill();
pB.readFile("input_data.txt");
pB.processCharges();
}
class LineItem{
String accNum ;
String timeOfCall;
double mins;
double amountDue;
boolean counted = false;
public LineItem(String accStr)
{
processAccount(accStr);
}
private void processAccount(String accStr){
StringTokenizer st = new StringTokenizer(accStr);
accNum = (String)st.nextElement();
timeOfCall = (String) st.nextElement();
mins = Double.parseDouble((String) st.nextElement());
if (timeOfCall.compareTo("08:00")>0 && timeOfCall.compareTo("22:00")<0)
amountDue = mins*0.10;
else
amountDue = mins*0.05;
}
public String getAccountNum()
{
return accNum;
}
public double getCharges()
{
return amountDue;
}
}
}
Study this. It uses a bit more advanced Java but understanding it will be well worth your while.
package test;
import java.io.*;
import java.util.*;
public class PhoneBill {
private static String BILL_FORMAT = "%-10s $%,6.2f\n";
private static boolean DEBUG=true;
Map<String, List<LineItem>> accounts = new HashMap<String,List<LineItem>>();
public void readFile(String inFileStr) {
FileReader fReader=null;
try {
fReader = new FileReader(inFileStr);
BufferedReader br = new BufferedReader(fReader);
String line;
while ((line = br.readLine()) != null) {
if (line.indexOf("_") != -1)
continue;
else if (!line.isEmpty()) {
LineItem li = new LineItem(line.trim());
List<LineItem> list = accounts.get(li.accNum);
if(list==null){
list = new ArrayList<LineItem>();
accounts.put(li.accNum, list);
}
list.add(li);
}
}
br.close();
} catch (Exception e) {
/* Don't just swallow Exceptions. */
e.printStackTrace();
} finally {
if(fReader!=null){
try{
fReader.close();
} catch(Exception e){
e.printStackTrace();
}
}
}
}
public void processCharges() {
StringBuffer out = new StringBuffer(100)
.append("Invoice\n")
.append("--------------------------\n")
.append("Account Amount Due \n");
double total = 0.0;
double lCharges = 0;
for (String accNum:accounts.keySet()) {
List<LineItem> account = accounts.get(accNum);
lCharges = 10;
for(LineItem li:account){
lCharges += li.getCharges();
}
total += lCharges;
out.append(String.format(BILL_FORMAT, accNum, lCharges));
}
out.append("--------------------------\n");
out.append(String.format(BILL_FORMAT, "Total", total));
writeToFile("invoice.txt", out.toString());
}
private void writeToFile(String filename, String outStr) {
if(DEBUG){
System.out.printf("========%swriteToFile:%s=========\n", '=', filename);
System.out.println(outStr);
System.out.printf("========%swriteToFile:%s=========\n", '/', filename);
}
try {
File file = new File(filename);
// If file doesn't exist, then create it.
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(outStr);
bw.close();
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
}
public static void main(String[] args) {
PhoneBill pB = new PhoneBill();
pB.readFile("input_data.txt");
pB.processCharges();
}
static class LineItem {
String accNum;
double timeOfCall;
double mins;
double amountDue;
boolean counted = false;
private static final double EIGHT_AM = convertTime("08:00");
private static final double TEN_PM = convertTime("22:00");
public LineItem(String accStr) {
processAccount(accStr);
}
private void processAccount(String accStr) {
StringTokenizer st = new StringTokenizer(accStr);
accNum = st.nextToken();
timeOfCall = convertTime(st.nextToken());
mins = Double.parseDouble(st.nextToken());
if (timeOfCall > EIGHT_AM && timeOfCall < TEN_PM)
amountDue = mins * 0.10;
else
amountDue = mins * 0.05;
}
public String getAccountNum() {
return accNum;
}
public double getCharges() {
return amountDue;
}
private static double convertTime(String in){
/* Will blow up if `in` isn't given in h:m. */
String[] h_m = in.split(":");
return Double.parseDouble(h_m[0])*60+Double.parseDouble(h_m[1]);
}
}
}
Printing to the console (i.e. System.out.println) is not the same as concatenating to your out variable (i.e. out+=).
So when you call
writeToFile("invoice.txt", out);
You are only writing what is in the string 'out' to the file. If you look back at your code, you'll see that all of your missing lines are only ever printed to the console, but not concatenated to the 'out' variable. Correct that and you shouldn't have a problem.

Categories