Using JOptionPane to print reports - java

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);

Related

Find all matching elements in Array - Java

At the moment my code is only giving me the first matching result. The user inputs their desired room price and at the moment it will only display the first match. In the case the user inputs '60' to the console it should display 3 results. I imagine i'll need another forloop and if statement after it prints to the console but not sure how to execute
public static void secondMain() {
BufferedReader reader;
var lines = new ArrayList<String>();
var rooms = new ArrayList<Room>();
Room selectedRoom = null;
try {
reader = new BufferedReader(new FileReader("rooms.txt"));
String line = reader.readLine();
lines.add(line);
while (line != null) {
line = reader.readLine();
lines.add(line);
}
reader.close();
for (int i = 0; i < lines.size() - 1; i++) {
String[] words = lines.get(i).split(" ");
var room = new Room();
room.roomNum = Integer.parseInt(words[0]);
room.roomType = (words[1]);
room.roomPrice = Double.parseDouble(words[2]);
room.hasBalcony = Boolean.parseBoolean(words[3]);
room.hasLounge = Boolean.parseBoolean(words[4]);
room.eMail = (words[5]);
rooms.add(room);
}
var searchRoomPrice = input.nextDouble();
for (int i = 0; i < rooms.size(); i++) {
if (rooms.get(i).roomPrice == searchRoomPrice) {
selectedRoom = rooms.get(i);
break;
}
}
System.out.println("Room Number: " + selectedRoom.roomNum);
System.out.println("Room Type: " + selectedRoom.roomType);
System.out.println("Room Price: " + selectedRoom.roomPrice);
System.out.println("Balcony: " + selectedRoom.hasBalcony);
System.out.println("Lounge: " + selectedRoom.hasLounge);
System.out.println("Email: " + selectedRoom.eMail);
System.out.println("-------------------");
} catch (Exception e) {
e.printStackTrace();
}
}
Any other information needed feel free to ask
If you only want to print the information move the print commands inside the loop and remove the break i.e.
for(int i = 0; i < rooms.size(); i++){
if(rooms.get(i).roomPrice == searchRoomPrice){
selectedRoom = rooms.get(i);
System.out.println("Room Number: " + selectedRoom.roomNum);
System.out.println("Room Type: " + selectedRoom.roomType);
System.out.println("Room Price: " + selectedRoom.roomPrice);
System.out.println("Balcony: " + selectedRoom.hasBalcony);
System.out.println("Lounge: " + selectedRoom.hasLounge);
System.out.println("Email: " + selectedRoom.eMail);
System.out.println("-------------------");
}
}
You could also save all the objects in a list with the first loop and then in a second loop iterate over the list and print the information i.e.
List<Room> roomList = new ArrayList<Room>();
for(int i = 0; i < rooms.size(); i++){
if(rooms.get(i).roomPrice == searchRoomPrice){
roomList.add(rooms.get(i));
}
}
for(Room room : roomList){
System.out.println("Room Number: " + room.roomNum);
System.out.println("Room Type: " + room.roomType);
System.out.println("Room Price: " + room.roomPrice);
System.out.println("Balcony: " + room.hasBalcony);
System.out.println("Lounge: " + room.hasLounge);
System.out.println("Email: " + room.eMail);
System.out.println("-------------------");
}
I notice 2 things:
You are using a break; here:
if(rooms.get(i).roomPrice == searchRoomPrice){
selectedRoom = rooms.get(i);
break;
}
So you are stopping the loop after the first match.
Here:
for (int i = 0; i < lines.size() - 1; i++)
Is there a reason to use that minus 1?

Java: Highscore function [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have created a counting game and I have tried to create a highscore method.
The problem is the program returns "null" when the "Highscore" menu is chosen. What could be causing this?
import javax.swing.*;
import java.text.DecimalFormat;
import java.util.*;
import java.io.*;
public class Räknesätt {
public static void main(String[]args) throws IOException {
DecimalFormat df = new DecimalFormat("0.00");
int input = Integer.parseInt(JOptionPane.showInputDialog(null, "-------------------------" + "\n\n" +
"1. Spela" + "\n" +
"2. Highscores" + "\n" +
"3. Avsluta" + "\n\n" +
"-------------------------"));
if(input == 2) {
String highscores = "";
int rader = countline("Highscores");
BufferedReader inström1 = new BufferedReader
(new FileReader("Highscores"));
for(int i = 0; i <= rader; i++) {
highscores = inström1.readLine() + "\n";
}
JOptionPane.showMessageDialog(null, highscores);
}
else if(input == 3) {
System.exit(0);
}
else if(input == 1) {
String namn = JOptionPane.showInputDialog(null, "Skriv in ditt namn");
int counter = 0;
int rätt = 0;
int fel = 0;
while(counter < 10) {
int slump1 = 1 + (int)(Math.random()*100);
int slump2 = 1 + (int)(Math.random()*100);
List<String> räknesätt = new LinkedList<String>(Arrays.asList("+",
"-",
"*",
"/"));
int räknesättRand = (int)(Math.random()*4);
String räknesättStr = räknesätt.get(räknesättRand);
counter++;
switch(räknesättStr) {
case "+":
String svarStr1 = JOptionPane.showInputDialog(null,namn + " räkna ut: " + "\n" + slump1 + " + " + slump2 + " = ");
int svar1 = Integer.parseInt(svarStr1);
if(svar1 == slump1 + slump2) {
JOptionPane.showMessageDialog(null, namn + " du räknade rätt!");
rätt++;
}
else {
JOptionPane.showMessageDialog(null, namn + " du räknade fel!");
fel++;
}
break;
case "-":
String svarStr2 = JOptionPane.showInputDialog(null,namn + " räkna ut: " + "\n" + slump1 + " - " + slump2 + " = ");
int svar2 = Integer.parseInt(svarStr2);
if(svar2 == slump1 - slump2) {
JOptionPane.showMessageDialog(null, namn + " du räknade rätt!");
rätt++;
}
else {
JOptionPane.showMessageDialog(null, namn + " du räknade fel!");
fel++;
}
break;
case "*":
String svarStr3 = JOptionPane.showInputDialog(null,namn + " räkna ut: " + "\n" + slump1 + " * " + slump2 + " = ");
int svar3 = Integer.parseInt(svarStr3);
if(svar3 == slump1 * slump2) {
JOptionPane.showMessageDialog(null, namn + " du räknade rätt!");
rätt++;
}
else {
JOptionPane.showMessageDialog(null, namn + " du räknade fel!");
fel++;
}
break;
case "/":
String svarStr = JOptionPane.showInputDialog(null,namn + " räkna ut: " + "\n" + slump1 + " / " + slump2 + " = ");
int svar = Integer.parseInt(svarStr);
if(svar == (double)slump1 / slump2) {
JOptionPane.showMessageDialog(null, namn + " du räknade rätt!");
rätt++;
}
else {
JOptionPane.showMessageDialog(null, namn + " du räknade fel!");
fel++;
}
break;
}
}
JOptionPane.showMessageDialog(null, "Resultat för: " + namn + "\n\n" +
"=========================" + "\n" +
"Antal räknade tal: " + counter + "\n" +
"Antal rätt: " + rätt + "\n" +
"Antal fel: " + fel + "\n" +
"Rättprocent: " + (double)100*rätt/(rätt+fel) + "%");
PrintWriter utström1 = new PrintWriter
(new BufferedWriter
(new FileWriter("Highscores")));
utström1.println(namn + ", " + (double)100*rätt/(rätt+fel) + "% rätt");
utström1.close();
}
}
public static int countline (String filnamn)throws IOException {
BufferedReader inström1 = new BufferedReader
(new FileReader(filnamn));
int lines = 0;
while(inström1.readLine() != null) {
++lines;
}
inström1.close();
return lines;
}
}
Code is trying to open a handle to a non-existent file by the name 'Highscores'.
Problem is being caused by the following line of code :
BufferedReader inström1 = new BufferedReader
(new FileReader("Highscores"));
The solution would be to create this file upfront, at the beginning of the program and write default contents into it.
Here is how you can go about doing it.
private static void createHighScoreFile() throws IOException {
PrintWriter printWriter = new PrintWriter
(new BufferedWriter
(new FileWriter("Highscores")));
printWriter.write("0\n");
printWriter.close();
}
public static void main(String[] args) throws IOException {
createHighScoreFile();
DecimalFormat df = new DecimalFormat("0.00");
There is also one more issue related to reading the contents of the file.
The condition in the for loop attempts to read an extra line from the file, which turns out to be null always. It needs to be fixed this way.
for (int i = 0; i <= rader; i++) {
to
for (int i = 0; i < rader; i++) {

Using Strings with submenu's to print reports

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
}

Reading a .txt file into a parallel array

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

Array values being set for everything (Java)

In my code below, I am having an issue where I add the customer name to one room, but instead it adds the customer to every room. I can't figure out what in my code the issue is. I have tried removing the procedure but that still produced the same problem.
package test;
import java.util.*;
public class test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String choice, custName = "";
int roomNum = 1;
String[] hotel = new String[12];
String[] customer = new String[12];
hotelInitialise(hotel);
custInitialise(customer);
while ( roomNum < hotel.length-1 ) {
for (int i = 0; i < hotel.length-1; i++) {
System.out.println("This is the Hotel Menu. Please choose from the following options:\n");
System.out.println("A: " + "This will add a new entry\n");
System.out.println("V: " + "View all rooms\n");
choice = input.next().toUpperCase();
if (choice.equals("A")) {
System.out.println("Enter room number(1-10)");
roomNum =input.nextInt();
System.out.println("Enter name for room " + roomNum + " : " ) ;
custName = input.next();
addNewBooking(hotel, custName);
System.out.println(" ");
}
if (choice.equals("V")) {
seeAllRooms(hotel, custName);
}
}
}
}
// When the program loads it will assign all the values of the array as being empty
private static void hotelInitialise( String hotelRef[] ) {
for (int x = 0; x < 11; x++){
hotelRef[x] = "Room " + x + " is empty.";
}
System.out.println( "Welcome to the Summer Tropic Hotel.\n");
}
private static void custInitialise (String custRef[]) {
for (int i = 0; i < 11; i++) {
custRef[i] = ", no customer has occupied this room";
}
}
private static void addNewBooking(String hotel[], String customer) {
for (int x =1; x <11; x++) {
if (hotel[x].equals("Room " + hotel[x] + " is empty."))
System.out.println("Room " + x + " is empty.");
else {
System.out.println("Room " + x + " is occupied by "+ customer);
}
}
}
private static void seeAllRooms(String hotel[], String customer) {
for (int i = 0; i < hotel.length-1; i++) {
int j=0;
String custName = customer;
hotel[j]= custName;
if (hotel[i].equals("Room " + i + " is empty."))
System.out.println("Room " + i + " is empty.");
else {
System.out.println("Room " + i + " is occupied by "+ hotel[j] + ".");
}
}
}
}
In addNewBooking method you have this line:
if (hotel[x].equals("Room " + hotel[x] + " is empty."))
However hotel[x] has a value of "Room x is empty" e.g. hotel[1] is "Room 1 is empty" So the final check is becoming "hotel[x].equals(Room Room x is empty is empty.)" which is never equals to your hotel[x]
You have to change your code to
if (hotel[x].equals("Room " + x + " is empty."))
//do something there like add the booking

Categories