I need some help finishing up my program. I have it set up so that it lists 6 options. Options 2 and 3 are supposed to open their own lists of 4 options. Right now when I select 2 or 3 it opens the correct options they should, but if I try and select one of their subsequent reports it just kicks me back to the main menu. My questions is that is their a way to alter my code to make this work the way I want it too, or should I use command-line and either way I could use some help with it as I'm thoroughly stumped. Any help is much appreciated.
Error Message: doctorMain (String[]) in Patient_Reports cannot be
applied to ()
Error Message is located in my main method
Compiler Error Message: Error:(30, 24) java: method doctorMain in
class Test.Patient_Reports cannot be applied to given types;
required: java.lang.String[] found: no arguments reason:
actual and formal argument lists differ in length
Data File (patient.txt):
11111,Smith,Norris,Thyroid,1000.00
11112,Obama,Norris,Lasek,500.00
11113,Hoover,Norris,Dental,100.00
11114,Cena,Norris,Lasek,500.00
11115,Leto,Norris,Thyroid,1000.00
22221,Clark,Bond,Thyroid,1000.00
22222,Chang,Bond,Lasek,500.00
22223,Dent,Bond,Dental,100.00
22224,Nixon,Bond,Lasek,500.00
22225,Washington,Bond,Dental,100.00
33331,Jones,Lee,Dental,100.00
33332,Ross,Lee,Lasek,500.00
33333,Gates,Lee,Thyroid,1000.00
33334,Johnson,Lee,Thyroid,1000.00
33335,Carter,Lee,Dental,100.00
Condensed version of the Program
Program: (class is Patient_Reports)
package Test;
/**
* Created by Brandon on 9/6/2015.
*/
import javax.swing.*;
import java.io.*;
import java.util.*;
public class Patient_Reports {
private final int[] id = new int[100];
private final String[] patient = new String[100];
private final String[] doctor = new String[100];
private final String[] surgery = new String[100];
private final double[] cost = new double[100];
private int count = -1;
private int i;
//Main Method
public static void main(String[] args) {
int selection;
String report_number;
Patient_Reports patient = new Patient_Reports();
patient.start_system();
report_number = patient.menu();
selection = Integer.parseInt(report_number);
while (selection != 2) {
if (selection == 1) {
patient.surgeryDoctorMenu();
patient.doctorMain(); <<<<<<<<<< error message is here
}
report_number = patient.menu();
selection = Integer.parseInt(report_number);
}//While Loop
patient.writeReports();
System.exit(0);
}//End Main
//Read Data File into Array
private void start_system() {
String newLine;
try {
//Read text file into an array.
BufferedReader Patient_Reports = new BufferedReader(new FileReader("patient.txt"));
while ((newLine = Patient_Reports.readLine()) != null) {
//Comma Delimited
StringTokenizer delimiter = new StringTokenizer(newLine, ",");
count = count + 1;
id[count] = Integer.parseInt(delimiter.nextToken());
patient[count] = delimiter.nextToken();
doctor[count] = delimiter.nextToken();
surgery[count] = delimiter.nextToken();
cost[count] = Double.parseDouble(delimiter.nextToken());
}//While Loop
Patient_Reports.close();
}//End Try
catch (IOException error) {
//Error in File Writing
System.out.println("Error on file read " + error);
}//End Catch
}//End start_system
//Report Menu
private String menu() {
String report;
String Output = "Reports:" + "\n" + "1. Surgeries Doctor Report" + "\n" +
"2. Exit" + "\n" +
" " + "\n" +
"Select a Report >";
report = JOptionPane.showInputDialog(null,
Output, "", JOptionPane.QUESTION_MESSAGE);
return report;
}//End Menu
//Store Data File in Array
private void writeReports() {
try {
BufferedWriter Patient_Reports = new BufferedWriter(new FileWriter("patient_out.txt"));
for (i = 0; i <= count; ++i) {
//Comma Delimit
Patient_Reports.write(id[i] + "," + patient[i] + "," + doctor[i] + "," +
surgery[i] + "," + cost[i] + ",");
//Write a new line in patient_out.txt
Patient_Reports.newLine();
}//End For Loop
Patient_Reports.close();
}//End Try
catch (IOException error) {
//Error on Write to File
System.out.println("Error on file write " + error);
}//End Error
}//End writeReports
//Main for Doctor Reports
public static void doctorMain (String[] args) {
int doctor_selection;
String doctor_name;
Patient_Reports doctor = new Patient_Reports();
doctor.start_system();
doctor_name = doctor.surgeryDoctorMenu();
doctor_selection = Integer.parseInt(doctor_name);
while (doctor_selection !=2) {
if (doctor_selection == 1) {
doctor.norrisSurgeries();
}
doctor_name = doctor.surgeryDoctorMenu();
doctor_selection = Integer.parseInt(doctor_name);
}//While Loop
}//End doctorMain
//Report on all surgeries of a specific doctor (prompt for the doctor)
//Report Menu
private String surgeryDoctorMenu() {
System.out.println("Surgeries Doctor Report:");
String doctor_report;
String Output = "Surgery Doctor Reports:" + "\n" + "1. Norris Surgeries Report" + "\n" +
"2. Bond Surgeries Report" + "\n" +
"3. Lee Surgeries Report" + "\n" +
"4. Exit" + "\n" +
" " + "\n" +
"Select a Report >";
doctor_report = JOptionPane.showInputDialog(null,
Output, "", JOptionPane.QUESTION_MESSAGE);
return doctor_report;
}//end menu\
//Report on all surgeries by Dr. Norris
private void norrisSurgeries() {
System.out.println("Norris Surgeries Report:");
System.out.println("5" + " ");
}//End norrisSurgeries
}
Related
I am being tasked with adding 2 more classes to a prewritten program, one that does all calculations and one that prints the total bill. I understand how to add other classes but im a bit confused since the program already looks like it does the calculations inside of the main class.
Ive tried just adding in the classes but it throws errors because its missing information obviously.
public static void main(String[] args)
{
String squantity, snumber, output, line_output = "";
String [] item = new String [5];
double [] cost = new double [5];
double [] quantity = new double [5];
double [] amount = new double [5];
int number, i;
double grandtotal = 0;
String costout, amountout, grandtotalout;
DecimalFormat df2 = new DecimalFormat("$##,###.00");
for(i=0;i<=4;++i)
{
output = " Acme Grocery Store" + "\n" +
"1-Green Beans $0.35 per pound" + "\n" +
"2-Yellow Beans $0.40 per pound" + "\n" +
"3-Head Lettuce $0.79 per pound" + "\n" +
"4-Leaf Lettuce $1.98 per pound" + "\n" +
"5-Hot House Tomatoes $0.99 per pound" + "\n" +
"6-Hydro Tomatoes $3.98 per pound" + "\n" + "\n" +
"Please make your selection ";
snumber = JOptionPane.showInputDialog(null,
output, "Input Data", JOptionPane.QUESTION_MESSAGE);
number = Integer.parseInt(snumber);
squantity = JOptionPane.showInputDialog(null,
"Enter Quantity", "Input Data", JOptionPane.QUESTION_MESSAGE);
quantity[i] = Double.parseDouble(squantity);
//code for the calculation
if(number == 1)
{
cost[i] = 0.35;
item[i]="Green Beans";
}
else if(number == 2)
{
cost[i] = 0.4;
item[i]="Yellow Beans";
}
else if(number == 3)
{
cost[i] = 0.79;
item[i]="Head Lettuce";
}
else if(number ==4)
{
cost[i] = 1.98;
item[i]="Leaf Lettuce";
}
else if (number==5)
{
cost[i] = 0.99;
item[i]="Hot House Tomatoes";
}
else
{
cost[i] = 3.98;
item[i]="Hydro Tomatoes";
}
amount[i]=cost[i]*quantity[i];
costout=df2.format(cost[i]);
amountout=df2.format(amount[i]);
line_output=line_output+item[i]+" "+costout+" "+amountout+"\n";
grandtotal=grandtotal + amount[i];
}//for loop
grandtotalout=df2.format(grandtotal);
output=line_output+"\n"+ "The total grocery bill = "+grandtotalout;
JOptionPane.showMessageDialog(null, output, " ", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}//main
We are expected to add the classes
class grocery {
}
class printbill{
}
I tried messing with the extends function but I dont think that is correct either
As a starter, your grocery class would look something like this:
final class Grocery
{
Grocery(String InputItem, double InputCost, double InputQuantity)
{
Item = InputItem;
Cost = InputCost;
Quantity = InputQuantity;
}
public final String GetItem()
{
return Item;
}
public final double GetCost()
{
return (double)InputQuantity * Cost;
}
private final String Item;
private final double Cost;
private final int Quantity;
}
The PrintBill class may go like this:
final class PrintBill
{
PrintBill(Grocery [] InputGroceries)
{
Groceries = InputGroceries;
}
public final void Print()
{
double Cost, TotalCost = 0.0;
String Line = "";
String Item;
for (int i = 0; i < Groceries.length; i++)
{
Cost = Groceries[i].GetCost();
Item = Groceries[i].GetItem();
TotalCost += Cost;
// I'll leave it up to you to print this info out.
Line = Item + " " + Cost +" "+ TotalCost +"\n";
}
JOptionPane.showMessageDialog(null, output, " ",
JOptionPane.INFORMATION_MESSAGE);
}
private final Grocery [] Groceries;
}
Your main() would then be:
public static void main(String[] args)
{
String squantity, snumber, output, line_output = "";
Grocery [] Groceries = new Grocery [4];
PrintBill TheBill;
int number;
for (int i = 0; i < Groceries.length; i++)
{
output = " Acme Grocery Store" + "\n" +
"1-Green Beans $0.35 per pound" + "\n" +
"2-Yellow Beans $0.40 per pound" + "\n" +
"3-Head Lettuce $0.79 per pound" + "\n" +
"4-Leaf Lettuce $1.98 per pound" + "\n" +
"5-Hot House Tomatoes $0.99 per pound" + "\n" +
"6-Hydro Tomatoes $3.98 per pound" + "\n" + "\n" +
"Please make your selection ";
snumber = JOptionPane.showInputDialog(null,
output, "Input Data", JOptionPane.QUESTION_MESSAGE);
number = Integer.parseInt(snumber);
squantity = JOptionPane.showInputDialog(null,
"Enter Quantity", "Input Data", JOptionPane.QUESTION_MESSAGE);
quantity = Double.parseDouble(squantity);
if(number == 1)
{
Groceries[i] = new Grocery("Green Beans", 0.35, quantity);
}
else if(number == 2)
{
Groceries[i] = new Grocery("Yellow Beans", 0.4, quantity);
}
// etc...
}
TheBill = new PrintBill(Groceries);
TheBill.Print();
}
More work is required to actually complete this but it should give you a starting point anyway.
Happy Days :-)
I'm new to coding. I'm currently trying to get an input value and grab information from a csv file and format it into a song method (predefined) via four outputs. However, I'm not able to get to this point because every time I try to run it through it saids it is unable to load it. Either that or it automatally cuts to the default in the switch statement, which I don't understand. I'm completely lost right now.
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
/**
* #author chasestauts
*
*/
public class JukeboxHero {
public static void main(String args[]) {
final String MENU = "*****************************" + "\n" + "* Program Menu *" + "\n" + "*****************************"
+ "\n" + "(L)oad catalog" + "\n" + "(S)earch catalog" + "\n" + "(A)nalyse catalog" + "\n" + "(P)rint catalog" + "\n" + "(Q)uit"
+ "\n" + "\n";
final String cR = ("Please enter a command (press 'm' for Menu):");
System.out.print(MENU + cR);
Scanner input = new Scanner(System.in);
String decision = input.nextLine();
while(decision.equalsIgnoreCase("q") == false)
{
System.out.println(cR);
decision = input.nextLine();
switch (decision){
case ("L"):
{
ArrayList<Song> songList = new ArrayList<Song>();
System.out.println("Load Catalog..");
System.out.print("Please enter filename: ");
String filepath = input.nextLine();
File songFile = new File(filepath);
try
{
Scanner songScan = new Scanner(songFile);
while (songScan.hasNext())
{
String line = songScan.nextLine();
Scanner lineScan = new Scanner(line);
lineScan.useDelimiter(",");
while (lineScan.hasNext())
{
String artist = lineScan.next();
String album = lineScan.next();
String title = lineScan.next();
int duration = lineScan.nextInt();
Song song = new Song(title, artist, album, duration);
songList.add(song);
}
lineScan.close();
}
songScan.close();
int size = songList.size() + 1;
System.out.println("Successfully loaded " + size + " songs!");
}
catch (FileNotFoundException error)
{
System.out.println("Sorry, unable to open file: " + filepath);
}
}
break;
case ("S"):
{
System.out.println();
break;
}
case ("A"):
{
System.out.println();
break;
}
case ("P"):
{
System.out.println();
break;
}
case ("Q"):
{
System.out.println("Goodbye!");
break;
}
case ("M"):
{
System.out.println(MENU);
break;
}
default:
{
System.out.println("Invalid selection");
}
}
}
input.close();
}
}
I have a GUI based e-store project. I read in a file and parse through it and saved it into an array.
The file format is like so: 11111, "title", 9.90
11111 is the book id, "title" is title, and 9.90 is the price.
I currently have 3 classes in my project. 1 class for Input/Output, 1 class for the Book store GUI code, and another for pop-up boxes when specific buttons are clicked.
In the GUI code, I check read the file into String[] fileArray and then loop through it until there is a match (with TextField input String bookIds = bookIdinput.getText())
I'm able to successfully get a match and go on with the rest of the code, but when there isn't a match, I get an error: Exception in thread "JavaFX Application Thread" java.lang.NullPointerException at windowDisplay.lambda$start$3(windowDisplay.java:###)
which is this line of code for(int i=0; i<fileArray.length; i++)
If there isn't a match, then it should show a pop-up box saying that bookID isn't found.
Below is some of the GUI code
public class windowDisplay extends Application
{
// Variable declarations
private String[] fileArray = null;
private String holdStr = "";
private Stage mainWindow;
private boolean matchFound = false;
private int count = 1;
private int lineItems = 1;
private double totalAmount = 0.0;
private double subTotal = 0.0;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception
{
// OMITTED CODE
// These TextFields show the output depending on the input TextField's.
itemInfoOutput.setDisable(true);
orderSubtotalOutput.setDisable(true);
// Process item button.
processItem.setText("Process Item #" + count);
processItem.setMinWidth(106);
processItem.setOnAction(e ->
{
int numItems = Integer.parseInt(numItemInput.getText());
lineItems = numItems;
String bookIDs = bookIdInput.getText();
int qtyItems = Integer.parseInt(qtyItemInput.getText());
// Read file and check for Book ID
fileArray = bookStoreIO.readFile(bookIDs);
// Loop through array to find match or no matches
for(int i=0; i<fileArray.length; i++)
{
// If there is a match in book ID
if (fileArray[i].equals(bookIDs))
{
double price = Double.parseDouble(fileArray[i + 2]); // Price is in the i+2 position
double discount = calculateDiscount(qtyItems);
totalAmount = calculatePrice(qtyItems, price);
itemInfoOutput.setText(fileArray[i] + " " + fileArray[i + 1] + " " + "$" + price + " " +
qtyItems + " " + discount + "%" + " " + "$" + df.format(totalAmount));
// Disable processItem Button if there is a match and enable confirmItem Button
processItem.setDisable(true);
confirmItem.setDisable(false);
matchFound = true;
}
}
if(matchFound == false)
System.out.println("No match found!");
});
}
// OMITTED CODE
// This method calculates the discount depending on the quantity of items
public static double calculateDiscount(int inputQty){return null;}
// This methdod calculates the price with the discount
public static double calculatePrice(int inputQty, double price){return null;}
}
This class reads the file and returns an array with the contents of that file (once split by the ", " delimitter).
public class bookStoreIO
{
// This method reads the input file "inventory.txt" and saves it into an array.
public static String[] readFile(String stringIn)
{
try
{
String nextLine;
String[] fIn;
// Read file
BufferedReader br = new BufferedReader(new FileReader("inventory.txt"));
while((nextLine = br.readLine()) != null)
{
fIn = nextLine.split(", "); // Split when ", " is seen
if(stringIn.equalsIgnoreCase(fIn[0]))
{
br.close(); // Close file
return fIn; // Return array
}
}
}
// Just in case file isn't found
catch(IOException e)
{
System.out.println("File not found.");
}
return null;
}
I apologize if this seems messy, I'm still new to JavaFX and Java programming.
If you think more code is needed, please let me know!
EDIT: I improved some variable naming and removed the for loop. I'm still having trouble checking when there isn't a match.
public class windowDisplay extends Application
{
// Variable declarations
private String[] fileArray = null;
private Stage mainWindow;
private boolean matchFound = false;
private int count = 1;
private int lineItems = 1;
private double totalAmount = 0.0;
private double subTotal = 0.0;
private int itemQty = 0;
private int idBook = 0;
private String bookTitle = "";
private double bookPrice = 0.0;
private double discountAmount = 0.0;
private String resultOrder = "";
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception
{
// OMITTED CODE
// These TextFields show the output depending on the input TextField's.
itemInfoOutput.setDisable(true);
orderSubtotalOutput.setDisable(true);
// Process item button.
processItem.setText("Process Item #" + count);
processItem.setMinWidth(106);
processItem.setOnAction(e ->
{
int numItems = Integer.parseInt(numItemInput.getText());
lineItems = numItems;
String bookIDs = bookIdInput.getText();
itemQty = Integer.parseInt(qtyItemInput.getText());
// Read file and check for Book ID
fileArray = bookStoreIO.readFile(bookIDs);
idBook = Integer.parseInt(fileArray[0]);
bookTitle = fileArray[1];
bookPrice = Double.parseDouble(fileArray[2]);
discountAmount = calculateDiscount(itemQty);
totalAmount = calculatePrice(itemQty, bookPrice);
itemInfoOutput.setText(idBook + " " + bookTitle + " $" + bookPrice + " " + itemQty + " " + discountAmount
+ "% $" + df.format(totalAmount));
itemInfo.setText("Item #" + count + " info:");
processItem.setDisable(true);
confirmItem.setDisable(false);
matchFound = true;
if(matchFound == false)
System.out.println("not found");
});
// OMITTED CODE
// This method calculates the discount depending on the quantity of items
public static double calculateDiscount(int inputQty){return null;}
// This method calculates the price with the discount
public static double calculatePrice(int inputQty, double price){return null;}
}
I'm also having trouble saving
itemInfoOutput.setText(idBook + " " + bookTitle + " $" + bookPrice + " " + itemQty + " " + discountAmount
+ "% $" + df.format(totalAmount));
into an String or String array to print out a list of all the corresponding matches (along with their book ID, book Title, book Price, quantity, discount , and total price).
An example is shown below:
enter image description here
EDIT 2: The right box is the main GUI. The bottom left box is what shows up when a wrong book is entered (on the 2nd order). The top left is the length of the array.
// Process item button.
processItem.setText("Process Item #" + count);
processItem.setMinWidth(106);
processItem.setOnAction(e ->
{
int numItems = Integer.parseInt(numItemInput.getText());
lineItems = numItems;
String bookIDs = bookIdInput.getText();
itemQty = Integer.parseInt(qtyItemInput.getText());
// Read file and check for Book ID
fileArray = bookStoreIO.readFile(bookIDs);
for(int i=0; i<fileArray.length; i++)
System.out.println(fileArray[i]);
if(fileArray.length >= 3)
{
idBook = Integer.parseInt(fileArray[0]);
bookTitle = fileArray[1];
bookPrice = Double.parseDouble(fileArray[2]);
discountAmount = calculateDiscount(itemQty);
totalAmount = calculatePrice(itemQty, bookPrice);
resultOrder = itemInfoOutput.getText();
itemInfoOutput.setText(idBook + " " + bookTitle + " $" + bookPrice + " " + itemQty + " " + discountAmount
+ "% $" + df.format(totalAmount));
resultOrder = idBook + " " + bookTitle + " $" + bookPrice + " " + itemQty + " " + discountAmount
+ "% $" + df.format(totalAmount);
itemInfo.setText("Item #" + count + " info:");
processItem.setDisable(true);
confirmItem.setDisable(false);
}
else
alertBox.confirmDisplay("Book ID " + idBook + " not in file");
});
Okay so now I got my code to compile and run, but the output is incorrect now. I need to be able to select an option and then for 2, and 3 have 3 additional options after selecting that option. How should I adapt my coding to do this?
Task:
List of all information
List of all surgeries for a specific doctor (prompt for the doctor)
List of all surgeries of a specific type (prompt for the surgery type)
Total amount of surgery fees paid to each Doctor
Average Fees
Data File (patient.txt):
11111,Smith,Norris,Thyroid,1000.00
11112,Obama,Norris,Lasek,500.00
11113,Hoover,Norris,Dental,100.00
11114,Cena,Norris,Lasek,500.00
11115,Leto,Norris,Thyroid,1000.00
22221,Clark,Bond,Thyroid,1000.00
22222,Chang,Bond,Lasek,500.00
22223,Dent,Bond,Dental,100.00
22224,Nixon,Bond,Lasek,500.00
22225,Washington,Bond,Dental,100.00
33331,Jones,Lee,Dental,100.00
33332,Ross,Lee,Lasek,500.00
33333,Gates,Lee,Thyroid,1000.00
33334,Johnson,Lee,Thyroid,1000.00
33335,Carter,Lee,Dental,100.00
Code so far for reference:
package Patient_Reports_Package;
/**
* Created by bzink on 8/28/2015.
*/
import javax.swing.*;
import java.io.*;
import java.util.StringTokenizer;
/**
* The Patient_Reports_File class reads the data file into an array, and then has a menu for 5 reports.
*/
class Patient_Reports {
private final int[] id = new int[100];
private final String[] patient = new String[100];
private final String[] doctor = new String[100];
private final String[] surgery = new String[100];
private final double[] cost = new double[100];
private int count = -1;
private int i;
public static void main (String[] args) {
int selection;
String report_number;
Patient_Reports patient = new Patient_Reports();
patient.start_system();
report_number = patient.menu();
selection = Integer.parseInt(report_number);
while (selection !=6) {
if (selection == 1) {
patient.allInformationReport();
} else if (selection == 2) {
patient.surgeryDoctorReport();
} else if (selection == 3) {
patient.surgeryTypeReport();
} else if (selection == 4) {
patient.doctorFeesReport();
} else if (selection == 5) {
patient.averageFeesReport();
}
report_number = patient.menu();
selection = Integer.parseInt(report_number);
}//while loop
patient.writeReports();
System.exit(0);
}//main
//Read Data File into Array
private void start_system() {
String newLine;
try {
//define a file variable for Buffered read
BufferedReader Patient_Reports = new BufferedReader(new java.io.FileReader("C:\\Users\\Brandon\\" +
"Downloads\\Patient_Reports_File\\patient.txt"));
//read lines in file until there are no more lines in the file to read
while ((newLine = Patient_Reports.readLine()) != null) {
//there is a "," between each data item in each line
StringTokenizer delimiter = new StringTokenizer(newLine, ",");
count = count + 1;
id[count] = Integer.parseInt(delimiter.nextToken());
patient[count] = delimiter.nextToken();
doctor[count] = delimiter.nextToken();
surgery[count] = delimiter.nextToken();
cost[count] = Double.parseDouble(delimiter.nextToken());
}//while loop
Patient_Reports.close();
}//end try
catch (IOException error) {
//there was an error on the file writing
System.out.println("Error on file read " + error);
}//end catch
}//end start_system
//Report Menu
private String menu () {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Id ").append(" \n");
stringBuilder.append("Patient ").append(" \n");
stringBuilder.append("Doctor ").append(" \n");
stringBuilder.append("Surgery ").append(" \n");
stringBuilder.append("Cost ").append(" \n");
for (int i = 0; i < 6; i++) {
stringBuilder.append(i).append(" Name"+i).append('\n');
}
String startTag ="<font size='2' color='red'>";
String endTag = "</font>";
stringBuilder.append(startTag).append("Some content").append(endTag);
JOptionPane.showMessageDialog(null, stringBuilder.toString());
return stringBuilder.toString();
}//end menu\
/*
//Report Menu
private String menu() {
String report;
String Output = "Reports" + "\n" + "1. All_Information_Report" + "\n" +
"2. Surgeries_Doctor_Report" + "\n" +
"3. Surgeries_Type_Report" + "\n" +
"4. Doctor_Fees_Report" + "\n" +
"5. Average_Fees_Report" + "\n" +
"6. Exit" + "\n" +
" " + "\n" +
"Select a Report >";
report = JOptionPane.showInputDialog(null,
Output, "", JOptionPane.QUESTION_MESSAGE);
return report;
}//end menu\
*/
//Report containing all of the information
private void allInformationReport() {
System.out.println("All Information Report");
for (i = 0; i <= count; ++i) {
System.out.println(id[i] + " " + patient[i] + " " + doctor[i] + " " + surgery[i] + " " + cost[i] + " ");
}//for loop
}//end report
/* void selectDoctor()
{
//select doctor
String doctorOutput;
//int intNum=0,intNum1=0,i,x=-1;
count=count+1;
doctorOutput = "Enter the Doctor's Name";
doctor[count] =JOptionPane.showInputDialog(null,doctorOutput,
"",JOptionPane.QUESTION_MESSAGE);
}//end select doctor
//Start Doctor Menu
public static void doctorMenu (String[] args) {
int selection;
String doctorName;
Patient_Reports doctor = new Patient_Reports();
doctor.start_system();
doctorName = doctorMenu();
selection = Integer.parseInt(doctorName);
while (selection !=4) {
if (selection == 1) {
doctor.norrisSurgeries();
} else if (selection == 2) {
doctor.bondSurgeries();
} else if (selection == 3) {
doctor.leeSurgeries();
}
doctorName = doctorMenu();
selection = Integer.parseInt(doctorName);
}//while loop
doctor.writeReports();
System.exit(0);
}//End Doctor Menu
//Report on all surgeries by Dr. Norris
private void norrisSurgeries() {
System.out.println("Norris Surgeries Report");
for (i = 0; i <= count; ++i) {
System.out.println(doctor[i] + " " + surgery[i] + " ");
}//for loop
}//end report
//Report on all surgeries by Dr. Bond
private void bondSurgeries() {
System.out.println("Bond Surgeries Report");
for (i = 0; i <= count; ++i) {
System.out.println(doctor[i] + " " + surgery[i] + " ");
}//for loop
}//end report
//Report on all surgeries by Dr. Lee
private void leeSurgeries() {
System.out.println("Lee Surgeries Report");
for (i = 0; i <= count; ++i) {
System.out.println(doctor[i] + " " + surgery[i] + " ");
}//for loop
}//end report
*/
//Report on all surgeries of a specific doctor (prompt for the doctor)
private void surgeryDoctorReport() {
System.out.println("Surgeries Doctor Report");
for (i = 0; i <= count; ++i) {
System.out.println(id[i] + " " + patient[i] + " " + doctor[i] + " " + surgery[i] + " " + cost[i] + " ");
}//for loop
}//end report
/*
void selectSurgery()
{
//select surgery
String surgeryOutput;
//int intNum=0,intNum1=0,i,x=-1;
count=count+1;
surgeryOutput = "Enter the Surgery Type";
doctor[count] =JOptionPane.showInputDialog(null,surgeryOutput,
"",JOptionPane.QUESTION_MESSAGE);
}//end select surgery
*/
//Report on all surgeries of a specific type(Prompt for the surgery type)
private void surgeryTypeReport() {
System.out.println("Surgeries Type Report");
for (i = 0; i <= count; ++i) {
System.out.println(id[i] + " " + patient[i] + " " + doctor[i] + " " + surgery[i] + " " + cost[i] + " ");
}//for loop
}//end report
//Report on the total amount of fees paid to each doctor
private void doctorFeesReport() {
System.out.println("Doctor Fees Report");
for (i = 0; i <= count; ++i) {
System.out.println(id[i] + " " + patient[i] + " " + doctor[i] + " " + surgery[i] + " " + cost[i] + " ");
}//for loop
}//end report
//Report on the Average Fee
private void averageFeesReport() {
System.out.println("Average Fees Report");
for (i = 0; i <= count; ++i) {
System.out.println(id[i] + " " + patient[i] + " " + doctor[i] + " " + surgery[i] + " " + cost[i] + " ");
}//for loop
}//end report
//Store Data File in Array
private void writeReports()
{
try {
BufferedWriter Patient_Reports = new BufferedWriter(new java.io.FileWriter("patient_out.txt"));
for (i = 0; i <= count; ++i) {
//put "," between each data item in the file
Patient_Reports.write(id[i] + "," + patient[i] + "," + doctor[i] + "," +
surgery[i] + "," + cost[i] + ",");
//write a new line in the file
Patient_Reports.newLine();
}//for loop
Patient_Reports.close();
}//end try
catch (IOException error) {
//there was an error on the write to file
System.out.println("Error on file write " + error);
}//end error
}//end write_reports
}
'
Use String or StringBuilder or StringBuffer to do this. But instead of String use either StringBuilder or StringBuffer. Since for String, you need some extra objects for String manipulation.
Ex:
StringBuilder sb = new StringBuilder();
sb.append("Id ").append(" Name\n");
for (int i = 0; i < 10; i++) {
sb.append(i).append(" Name"+i).append('\n');
}
JOptionPane.showMessageDialog(null, sb.toString());
Use HTML tags to produce better formatted results like <font>, <table>, etc.
Ex:
String startTag ="<font size='2' color='red'>";
String endTag = "</font>";
sb.append(startTag+"Some content"+endTag);
I need some assistance with my program. Using an example program that was similar I was able to get the basic layout of everything I needed to do. Right now my main questions is if my code is correct for the first part. I want it to read the data from my data file into a parallel array. I included my entire program for reference of the layout, but for now I'm just trying to read the data file into an array. Any help is greatly appreciated. Let me know if more information is needed or if my formatting is wrong.
Data File (patient.txt):
11111,Smith,Norris,Thyroid,1000.00
11112,Obama,Norris,Lasek,500.00
11113,Hoover,Norris,Dental,100.00
11114,Cena,Norris,Lasek,500.00
11115,Leto,Norris,Thyroid,1000.00
22221,Clark,Bond,Thyroid,1000.00
22222,Chang,Bond,Lasek,500.00
22223,Dent,Bond,Dental,100.00
22224,Nixon,Bond,Lasek,500.00
22225,Washington,Bond,Dental,100.00
33331,Jones,Lee,Dental,100.00
33332,Ross,Lee,Lasek,500.00
33333,Gates,Lee,Thyroid,1000.00
33334,Johnson,Lee,Thyroid,1000.00
33335,Carter,Lee,Dental,100.00
Program (class is Patient_Reports)
`
import javax.swing.JOptionPane;
import java.io.*;
import java.util.*;
public class Patient_Reports {
public static void main(String[] args)
{
int selection;
String pnumber;
Patient_Reports patient = new Patient_Reports();
patient.start_system();
pnumber = patient.menu();
selection = Integer.parseInt(pnumber);
while(selection !=3)
{
if(selection==1)
patient.All_Information_Report();
else
if(selection==2)
patient.Surgeries_Doctor_Report();
else
if(selection==3)
patient.Surgeries_Type_Report();
else
if(selection==4)
patient.Doctor_Fees_Report();
else
if(selection==5)
patient.Average_Fees_Report();
pnumber = patient.menu();
selection = Integer.parseInt(pnumber);
}//while loop
patient.Exit();
System.exit(0);
}//main method
//Read Data File
int count=-1,i;
int [] id = new int [10];
String [] patient = new String [10];
String [] doctor = new String [10];
String [] surgery = new String [10];
double [] cost = new double [10];
void start_system()
{
String newLine;
try
{
//define a file valiable for Buffered read
BufferedReader Patient_Reports = new BufferedReader(new FileReader("patient.txt"));
//read lines in file until there are no more lines in the file to read
while ((newLine = Patient_Reports.readLine()) != null)
{
//there is a "," between each data item in each line
StringTokenizer delimiter = new StringTokenizer(newLine,",");
count=count+1;
id[count] = Integer.parseInt(delimiter.nextToken());
patient[count] =delimiter.nextToken();
doctor[count] =delimiter.nextToken();
surgery[count] =delimiter.nextToken();
cost[count] = Double.parseDouble(delimiter.nextToken());
}//while loop
Patient_Reports.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
}//end start_system
//Method for Menu of Reports
String menu()
{
String pnum;
String Output = "Reports" + "\n" +"1. All_Information_Report" + "\n" +
"2. Surgeries_Doctor_Report" + "\n" +
"3. Surgeries_Type_Report" + "\n" +
"4. Doctor_Fees_Report" + "\n" +
"5. Average_Fees_Report" + "\n" +
"6. Exit" + "\n" +
" " + "\n" +
"Select a Report >";
pnum = JOptionPane.showInputDialog(null,
Output, "",JOptionPane.QUESTION_MESSAGE);
return pnum;
}//end menu
/* Placeholder for the Reports
//All_Information_Report Report containing all of the information
void All_Information_Report()
{
System.out.println("All_Information_Report");
for (i=0; i<=count; ++i)
{
System.out.println(id[i] + " " + patient[i] + " " + doctor[i] + " " + surgery[i] + " " + cost[i] + " ");
}//for loop
}//end report
//Surgeries_Doctor_Report Report on all surgeries of a specific doctor (prompt for the doctor)
void Surgeries_Doctor_Report()
{
System.out.println("Surgeries_Doctor_Report");
for (i=0; i<=count; ++i)
{
System.out.println(id[i] + " " + patient[i] + " " + doctor[i] + " " + surgery[i] + " " + cost[i] + " ");
}//for loop
}//end report
//Surgeries_Type_Report Report on all surgeries of a specific type(Prompt for the surgery type)
void Surgeries_Type_Report()
{
System.out.println("Surgeries_Type_Report");
for (i=0; i<=count; ++i)
{
System.out.println(id[i] + " " + patient[i] + " " + doctor[i] + " " + surgery[i] + " " + cost[i] + " ");
}//for loop
}//end report
//Doctor_Fees_Report Report on the total amount of fees paid to each doctor
void Doctor_Fees_Report()
{
System.out.println("Doctor_Fees_Report");
for (i=0; i<=count; ++i)
{
System.out.println(id[i] + " " + patient[i] + " " + doctor[i] + " " + surgery[i] + " " + cost[i] + " ");
}//for loop
}//end report
//Average_Fees_Report Report on the Average Fee
void Average_Fees_Report()
{
System.out.println("Average_Fees_Report");
for (i=0; i<=count; ++i)
{
System.out.println(id[i] + " " + patient[i] + " " + doctor[i] + " " + surgery[i] + " " + cost[i] + " ");
}//for loop
}//end report
*/
//Store Data File in Array
void Exit()
{
try
{
BufferedWriter Patient_Reports = new BufferedWriter(new FileWriter("patient.txt"));
for (i=0; i<=count; ++i)
{
//put "," between each data item in the file
Patient_Reports.write(id[i] + "," + patient[i] + "," + doctor[i]+ "," + surgery[i] + ","+ cost[i]+ ",");
//write a new line in the file
Patient_Reports.newLine();
}//for loop
Patient_Reports.close();
}//end try
catch (IOException error)
{
//there was an error on the write to file
System.out.println("Error on file write " + error);
}//end error
}//end class
}//end exit_system`
To begin, your code is VERY confusing and violates several OOP programming conventions.
The first (and most egregious) problem is that your static class Patient_Reports contains the main method but does not utilize this static entry point to declare an object or advance. So, it would behoove you to reformat your code like this:
public class Patient_Reports {
Patient_Reports fields...
public Patient_Report() {
//start work here in Constructor
}
Patient_Reports methods...
public static void main(String[] args) {
new Patient_Reports();
}
}
To address your main question, you would want to have some sort of generalized method you could call within your class like this:
public static void writePatientReports(int[] id, String[] patient,
String[] doctor, String[] surgery, double[] cost) {
BufferedWriter Student_file = new BufferedWriter(new FileWriter("patient.txt"));
for (i=0; i<=count; ++i)
{
//put "," between each data item in the file
Student_file.write(id[i] + "," + patient[i] + "," + doctor[i]+ "," + surgery[i] + ","+ cost[i]+ ",");
//write a new line in the file
Student_file.write("\n");
}//for loop
Student_file.close();
}
The reason you were getting errors is because you had no methods attached to Patient_Reports like write() or newLine(). And even if you had, you would have needlessly declared Student_file as a BufferedWriter object.
Further, you would do greatly in furthering your knowledge of Java and general OOP by reading Java Code Conventions