Java Passing strings and string[] into another class - java

I am sure this question is answered, I get all kinds of results when I search on it, but I just cant grasp this concept. This is a homework assignment and I prefer to understand which is why I am posting. The assignment is to read user credentials from a file, hash the password, and then if they match display contents of another file that associates with their role.
I wrote this in a single class and then discovered that the assignment calls for at least two classes. So it made sense to me to read the files in 1 class and do everything else in another. It worked very well as one class, but this is my first programming adventure and im only 6 classes in. I do not understand the basics as I should, so in your response if you can teach me why the code needs modified as it does I would be grateful. My code is as follows;
package it145_final;
import java.util.Scanner;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class IT145_Final {
public static void main(String[] args) throws IOException, NoSuchAlgorithmException {
Scanner scnr = new Scanner(System.in);
Scanner fileIn = null;
int failedAttempts = 0;
int i = 0;
String q = "q";
// objects that I think I need???? Maybe??? but dont know how to get them from the FinalFiles class
FinalFiles fileAdmin = new FinalFiles();
FinalFiles fileVet = new FinalFiles();
FinalFiles fileZoo = new FinalFiles();
FinalFiles userA = new FinalFiles();
fileAdmin.file();
userA.file();
while (failedAttempts < 3)
{
System.out.println("Enter user name, or q to exit"); //get username
String userName = scnr.next();
if (userName.equalsIgnoreCase(q)) //option to terminiate
{
System.out.println("Logging Out");
break;
}
System.out.println("Enter password"); // get password
scnr.nextLine();
String userPassword = scnr.nextLine();
//The following takes the entered password and hashes it
String hashedPass = userPassword;
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(hashedPass.getBytes());
byte[] digest = md.digest();
StringBuffer sb = new StringBuffer();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
if (userName.equals(userA[i]) && sb.toString().equals(userA[i + 1]))
{
if (userA[i + 3].equals("admin"))
{
System.out.println(admin);
break;
}
else if (userA[i + 3].equals("veterinarian"))
{
System.out.println(veterinarian);
break;
}
else if (userA[i + 3].equals("zookeeper"))
{
System.out.println(zookeeper);
break;
}
else
{
System.out.println("Failed attempt");
failedAttempts ++;
}
}
if (userName.equals(userB[i]) && sb.toString().equals(userB[i + 1]))
{
if (userB[i + 3].equals("admin"))
{
System.out.println(admin);
break;
}
else if (userB[i + 3].equals("veterinarian"))
{
System.out.println(veterinarian);
break;
}
else if (userB[i + 3].equals("zookeeper"))
{
System.out.println(zookeeper);
break;
}
else
{
System.out.println("Failed attempt");
failedAttempts ++;
}
}
if (userName.equals(userC[i]) && sb.toString().equals(userC[i + 1]))
{
if (userC[i + 3].equals("admin"))
{
System.out.println(admin);
break;
}
else if (userC[i + 3].equals("veterinarian"))
{
System.out.println(veterinarian);
break;
}
else if (userC[i + 3].equals("zookeeper"))
{
System.out.println(zookeeper);
break;
}
else
{
System.out.println("Failed attempt");
failedAttempts ++;
}
}
if (userName.equals(userD[i]) && sb.toString().equals(userD[i + 1]))
{
if (userD[i + 3].equals("admin"))
{
System.out.println(admin);
break;
}
else if (userD[i + 3].equals("veterinarian"))
{
System.out.println(veterinarian);
break;
}
else if (userD[i + 3].equals("zookeeper"))
{
System.out.println(zookeeper);
break;
}
else
{
System.out.println("Failed attempt");
failedAttempts ++;
}
}
if (userName.equals(userE[i]) && sb.toString().equals(userE[i + 1]))
{
if (userE[i + 3].equals("admin"))
{
System.out.println(admin);
break;
}
else if (userE[i + 3].equals("veterinarian"))
{
System.out.println(veterinarian);
break;
}
else if (userE[i + 3].equals("zookeeper"))
{
System.out.println(zookeeper);
break;
}
else
{
System.out.println("Failed attempt");
failedAttempts ++;
}
}
if (userName.equals(userF[i]) && sb.toString().equals(userF[i + 1]))
{
if (userF[i + 3].equals("admin"))
{
System.out.println(admin);
break;
}
else if (userF[i + 3].equals("veterinarian"))
{
System.out.println(veterinarian);
break;
}
else if (userF[i + 3].equals("zookeeper"))
{
System.out.println(zookeeper);
break;
}
else
{
System.out.println("Failed attempt");
failedAttempts ++;
}
}
System.out.println("Login Failed");
failedAttempts++;
}
}
}
You can see I started to create some objects but I just cannot figure out how, or if thats even a good way, to get info from my other class.
And the class I created to read the files is;
package it145_final;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class FinalFiles {
public static void file() throws IOException{
String admin = "";
String veterinarian = "";
String zookeeper = "";
String[] userA = new String[4];
String[] userB = new String[4];
String[] userC = new String[4];
String[] userD = new String[4];
String[] userE = new String[4];
String[] userF = new String[4];
File file0 = new File("C:usercredentials.txt"); // Opens files
Scanner contents0 = new Scanner(file0);
File file1 = new File("C:admin.txt");
Scanner contents1 = new Scanner(file1);
File file2 = new File("C:veterinarian.txt");
Scanner contents2 = new Scanner(file2);
File file3 = new File("C:zookeeper.txt");
Scanner contents3 = new Scanner(file3);
// Following reads the files and assignes to variables as needed
while (contents1.hasNext())
{
admin += contents1.nextLine();
}
// System.out.println(admin); used to verify that admin was correct
while (contents2.hasNext())
{
veterinarian += contents2.nextLine();
}
while (contents3.hasNext())
{
zookeeper += contents3.nextLine();
}
while(contents0.hasNext())
{
String user1 = contents0.nextLine();//grabs the line from the file for each individual user
String user2 = contents0.nextLine();
String user3 = contents0.nextLine();
String user4 = contents0.nextLine();
String user5 = contents0.nextLine();
String user6 = contents0.nextLine();
userA = user1.split("\t");//takes information on user and breaks it into an array
userB = user2.split("\t");
userC = user3.split("\t");
userD = user4.split("\t");
userE = user5.split("\t");
userF = user6.split("\t");
System.out.println(userB[0]); //using for testing to make sure I am getting the correct info
System.out.println(userB[1]);
}
}
}
I know its not neat and tidy and I am sure there are better ways for me write something like this, I just did what I though of and what I know. I think if somebody could just show me how to pass those strings(admin, veterinarian, and zookeeper) along with the String[], userA userB etc. into my main it would work again and be sufficient for somebody with my skill level.
Cheers
Andy

As you are at entry level coding i would try to help you understand the logic a little which is essential to making a good application.
To make it easier for yourself you should think that each task needs a class. In your case you should have one class for obtaining the files and another for checking password. keep in mind that there is always one dominant class that launches the application and contains the main method.
In these individual classes you should create methods to break down the processes making the code more clear. In the password checking class you would want a method for each of these jobs (reading the files, encrypting password, decrypting password, checking the credentials against eachother).
Then return the value back to the first class. So it would look something like this.
class Main { //first class
public static void main(String[] args){
File = new File("file1"); //obtain file 1
File = new File("file2"); //obtain file 2
PasswordCheck checker = new PasswordCheck(); // call instance of second class
boolean credentialOk= passwordCheck.process(file1,file2)//calls method in second class and returns if the credentials match
}
}
class PasswordCheck { //second class
public passwordCheck(){
}//inistialise class
public boolean process(File file1, File file2){
}// method to process the files and returns if match succesfully or not
}

Related

How to overwrite integer at specific part of text file?

I have a textfile called "BookDetails.txt"
It is formatted in Book Title, Author, Publisher, Branch Call Number, and # of Copies like so:
1984 : George Orwell : Penguin : FIC Orw : 23
In my program, I am trying to overwrite the number of copies from 23 to 22 (decrementing by one essentially) when a patron checks out the specific book
public class CheckOutDialog extends javax.swing.JDialog {
private static final DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
ArrayList<CheckOut> checkOuts = new ArrayList<CheckOut>();
String bookTitle;
int numberOfCopies;
/**
* Creates new form CheckOutDialog
*/
public CheckOutDialog(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
Date currentDate = new Date();
jTextFieldDate.setText(df.format(currentDate));
}
private void jButtonCheckOutActionPerformed(java.awt.event.ActionEvent evt) {
String firstName = jTextFieldFirstName.getText();
String lastName = jTextFieldLastName.getText();
bookTitle = jTextFieldBookTitle.getText();
String checkOutDate = jTextFieldDate.getText();
CheckOut checkOutInfo = new CheckOut(firstName, lastName, bookTitle, checkOutDate);
checkOuts.add(checkOutInfo);
CheckOutCopy();
}
public void CheckOutCopy() //This method checks for book and num of copies
{
try {
File f = new File("BookDetails.txt");
Scanner fileRead = new Scanner(f);
boolean foundTitle = false;
fileRead.nextLine();
while(fileRead.hasNextLine())
{
String textLine = fileRead.nextLine();
String[] bookInfo = textLine.split(" : ");
String tempBookTitle = bookInfo[0];
numberOfCopies = Integer.parseInt(bookInfo[4]);
if(tempBookTitle.trim().equals(bookTitle))
{
foundTitle = true;
break;
}
}
if(foundTitle && numberOfCopies > 0)
{
OverwriteCopies();
WriteCheckOut();
this.setVisible(false);
}
else if(numberOfCopies == 0)
{
if(JOptionPane.showConfirmDialog(null, "Would you like to add the patron to the queue?", "No copies available", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
{
AddPatronQueue();
}
else
{
JOptionPane.getRootFrame().dispose();
}
}
else
{
JOptionPanes.messageBox("Book was not found in Library Catalog", "Check Out Error");
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}
private void OverwriteCopies()
{
numberOfCopies--;
//Unsure how to proceed from here
}
private void WriteCheckOut()
{
WriteFile wf = new WriteFile("CheckOutDetails.txt");
for(int i = 0; i < checkOuts.size(); i++)
{
CheckOut c = checkOuts.get(i);
String checkOutDetails = c.getFirstName() + " : " + c.getLastName() + " : " + c.getBookTitle() + " : " + c.getCheckOutDate();
wf.write(checkOutDetails);
}
wf.close();
}
My program is successful in finding a specific book and its number of copies (and it produces the JOptionPane if it has 0 copies left). However, I am unsure of how I can overwrite and update that specific element within the text file. I have done some research and it seems that RandomAccessFile may be one possible option. Is the RAF the viable solution to my problem or is there another option that I can take?

Arduino - Xbee- Java Communication

I am new to this and I am trying to make a simple program that will send a command to the arduino and then send a response back to java via xbee. I am able to send command to arduino but I am unable to read a response from it. I am using XBee S2C with API-2 configuration. How can I read the response from the arduino in my java?
Here is my code for java:
public class Transmitdataxbee {
private static final String PORT = "COM8";
private static final int BAUD_RATE = 9600;
private static RemoteXBeeDevice myremote;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
XBeeDevice myDevice = new XBeeDevice(PORT, BAUD_RATE);
Scanner input_rpi = new Scanner(System.in);
String data;
try {
myDevice.open();
XBeeNetwork myXBeeNetwork = myDevice.getNetwork();
myXBeeNetwork.setDiscoveryTimeout(10000);
myXBeeNetwork.startDiscoveryProcess();
while (myXBeeNetwork.isDiscoveryRunning()) {
System.out.println("Discovering devices...");
}
myremote = myXBeeNetwork.getDevice(new XBee64BitAddress("0013A20041768E48"));
String nodeIdentifier = myremote.getNodeID();
System.out.print("Node ID: ");
System.out.println(nodeIdentifier);
System.out.println("Enter Command");
data = input_rpi.next();
myDevice.sendData(myremote, data.getBytes());
System.out.println("Current timeout: " + myDevice.getReceiveTimeout() + "milliseconds");
//read from arduino
XBeeMessage edMessage = myDevice.readDataFrom(myremote);
String data_ed = edMessage.getDataString();
System.out.println(data_ed);
} catch (XBeeException e) {
e.printStackTrace(System.out);
myDevice.close();
System.exit(1);
}
}
}
and this is my code for arudino
#include <XBee.h>
XBee xbee = XBee();
ZBRxResponse rx = ZBRxResponse();
XBeeAddress64 test = XBeeAddress64(0x0013A200, 0x41768E6E);
ModemStatusResponse msr = ModemStatusResponse();
uint8_t data;
char cmd1[9];
String cmd;
char d_ata;
int j = 0;
int icount = 0;
int count = 32;
void setup() {
Serial.begin(9600);
Serial2.begin(9600);
xbee.setSerial(Serial2);
xbee.setAPImode(2);
Serial.println("Connecting....");
}
void loop() {
xbee.readPacket(50);
if (xbee.getResponse().isAvailable()){
Serial.println("Connected");
Serial.println("Getting Message...");
if (xbee.getResponse().getApiId() == ZB_RX_RESPONSE) {
xbee.getResponse().getZBRxResponse(rx);
Serial.println("Packet received!");
if(rx.getOption() == ZB_PACKET_ACKNOWLEDGED){
Serial.println("Packet acknowledged");
}
cmd = "";
Serial.println("Received Data: ");
for (int i = 0; i < rx.getDataLength(); i++) {
//print8Bits(rx.getData()[i]);
cmd1[i] = (char) rx.getData()[i];
cmd += cmd1[i];
Serial.println(cmd);
Serial.println();
}
if (cmd == "a") {
data = "l";
ZBTxRequest zbtx = ZBTxRequest(test,data, sizeof(data));
xbee.send(zbtx);
}
else if (cmd == "w"){
data = "u";
ZBTxRequest zbtx = ZBTxRequest(test,data, sizeof(data));
xbee.send(zbtx);
}
else if (cmd == "s"){
data = "d";
ZBTxRequest zbtx = ZBTxRequest(test,data, sizeof(data));
xbee.send(zbtx);
}
else if (cmd == "d"){
data = "r";
ZBTxRequest zbtx = ZBTxRequest(test,data, sizeof(data));
xbee.send(zbtx);
}
else{
data="e";
ZBTxRequest zbtx = ZBTxRequest(test,data, sizeof(data));
xbee.send(zbtx);
}
}
} else if (xbee.getResponse().isError()) {
// some kind of error happened, I put the stars in so
// it could easily be found
Serial.print("************************************* error code:");
Serial.println(xbee.getResponse().getErrorCode(),DEC);
}
}
After a few reasearches I found a piece of documentation from Digi that might help you.
As I thought in my first comment, the problem appears to come from the part where you try to read datas from the device.
According to this documentation : https://www.digi.com/resources/documentation/digidocs/90001438/reference/r_xb_java_lib_data_reception_callback.htm
You have to create a datalistener an register it to your XBeeDevice.
They even give you a few hints about XBeeMessage information.
I don't know your Java level but all the code is provided in the link above.
If you want to read more about listeners, check this : What is the purpose of a listener in Java?

Adding a condition to accept specific entries in HashMap

My program is a Simple Student Management Database which collects the name, subject and phone numbers of students and adds to a database. I've been able to achieve the main logical operations like adding, deleting and searching students in the database. I'm unable to restrict students to enter only approved subjects like for example "English", "Maths" and "Computing" when adding into a HashMap collection. Any help would be appreciated. Here's the main code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Scanner;
public class Menu {
private HashMap<String, Student> students;
public Menu() {
students = new HashMap<String, Student>();
}
private void eventLoop() {
Scanner scanner = new Scanner(System.in);
int choice = 0;
boolean exit = false;
this.readFromFile();
while (!exit) {
System.out.println("Welcome to Student Management System");
System.out.println("==============================");
System.out.println("(1) Add new student");
System.out.println("(2) Delete a student");
System.out.println("(3) Find Student By Name");
System.out.println("(4) List Students By Subject");
System.out.println("(5) List All Students");
System.out.println("(6) Exit System");
System.out.println("Choose an option: ");
try {
choice = Integer.parseInt(scanner.nextLine());
System.out.print('\u000C');
if (choice < 1 || choice > 6) {
System.err.println("Error : Choose an option between 1 and 6");
choice = 0;
}
} catch (NumberFormatException e) {
System.err.println("Error : Choose an option between 1 and 6");
choice = 0;
}
switch (choice) {
case 1:
this.addStudent(scanner);
break;
case 2:
this.deleteStudent(scanner);
break;
case 3:
this.findStudentByName(scanner);
break;
case 4:
this.findStudentsBySubject(scanner);
break;
case 5:
this.listStudents();
break;
case 6:
this.writeToFile();
exit = true;
}
}
scanner.close();
}
private void findStudentsBySubject(Scanner scanner) {
System.out.println("Enter the exact name of the subject:");
String subjectStr = scanner.nextLine();
boolean atleastOne = false;
for (String name : students.keySet()) {
if (students.get(name).getSubject().getName().toLowerCase().equals(subjectStr.toLowerCase())) {
System.out.println(students.get(name));
atleastOne = true;
}
}
if (!atleastOne) {
System.err.println("No students have enrolled for this subject.");
}
}
private void findStudentByName(Scanner scanner) {
System.out.println("Enter the exact name of the Student to search:");
String name = scanner.nextLine();
if (students.get(name.toLowerCase()) != null) {
System.out.println("Student details:");
System.out.println(students.get(name.toLowerCase()));
} else {
System.err.println(name + " not found in the database.");
}
}
private void deleteStudent(Scanner scanner) {
System.out.println("Enter the exact name of the Student to delete:");
String name = scanner.nextLine();
if (students.get(name.toLowerCase()) != null) {
students.remove(name.toLowerCase());
System.err.println("Student " + name + " deleted from the database.");
} else {
System.err.println(name + " not found in the database.");
}
}
private void addStudent(Scanner scanner) {
System.out.println("The information should be comma separated and in a single line.");
System.out.println("If the name is not unique, the system will throw an error.");
System.out.println("Enter the name, phone and subject of the new student.");
String line = scanner.nextLine();
System.out.print('\u000C');
String[] info = line.split(",");
if (info.length != 3) {
System.err.println("Please enter the information in the proper format.");
return;
}
String name = info[0];
String phone = info[1];
String subjectStr = info[2];
if (students.get(name.toLowerCase()) != null) {
System.err.println("This student already exists in the database.");
return;
}
if (phone.length() != 9) {
System.err.println("The phone number must contain exactly 9 digits.");
return;
}
if (phone.charAt(0) != '9') {
System.err.println("The phone number must start with '9'.");
return;
}
if (!phone.matches("^[0-9]*$")) {
System.err.println("The phone number must contain only numbers.");
return;
}
students.put(name.toLowerCase(), new Student(name, new Subject(subjectStr), phone));
System.err.println("Student added successfully");
}
private void listStudents() {
for (String name : this.students.keySet()) {
System.out.println(this.students.get(name));
}
}
private void readFromFile() {
try {
BufferedReader br = new BufferedReader(new FileReader(new File("./students.txt")));
String line;
while ((line = br.readLine()) != null) {
String[] info = line.split(",");
String name = info[0];
String phone = info[1];
String subjectName = info[2];
if (students.get(name.toLowerCase()) == null) {
Subject subject = new Subject(subjectName);
students.put(name.toLowerCase(), new Student(name, subject, phone));
} else {
System.err.println("There seems to be a duplicate student in the file.");
}
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private void writeToFile() {
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("./students.txt")));
for (String name : students.keySet()) {
bw.write(students.get(name).toString());
bw.newLine();
}
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Menu menu = new Menu();
menu.eventLoop();
}
}
Subject Class:
public class Subject {
private String name;
public Subject(String subjectName) {
this.setName(subjectName);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return this.getName();
}
}
When you have a restricted list of possible values you can use an Enum e.g.
enum Subject {
English, Maths, Computing
}
A collection of these is just an EnumSet and you can check it's value by calling
EnumSet<Subject> subjects = EnumSet.of(Subject.class);
Subject s = Subject.valueOf(subjectName);
subjects.add(s);
Using stream and filter you can easily achieve this
students.entrySet()
.stream()
.filter(.. some predicate...)
.map(Map.Entry::getValue)
.collect(Collectors.toList())
If you are sure you are going to get at most a single element that passed the filter (which is guaranteed by your filter), you can use findFirst :
Optional<List> o = students.entrySet()
.stream()
.filter( e -> e.getKey() == 1)
.map(Map.Entry::getValue)
.findFirst();
In the general case, if the filter may match multiple Lists, you can collect them to a List of Lists :
List<List> list = students.entrySet()
.stream()
.filter(.. some predicate...)
.map(Map.Entry::getValue)
.collect(Collectors.toList());

Java - Reading files into array

I want to save a library for a small scale java application which stores technical manuals. Right now I am able to save the library to an external file but I am unable to load it back into the library itself, currently "-1" just gets printed to the console.
How can I solve this?
Here is my code:
//Choice 7: Load Library:
if(Menu.menuChoice == 7){
boolean loadYesNo = Console.readYesNo("\n\nThe manualKeeper app is able to load and display any 'Library.txt' files \nfound in your home folder directory.\n\nWould you like to load and display library? (Y/N):\n");
String fileName = "Library.bin";
if(loadYesNo==true){
try {
FileInputStream fileIs = new FileInputStream(fileName);
ObjectInputStream is = new ObjectInputStream(fileIs);
int x = is.read();
System.out.println(x);
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Menu.displayMenu();
}
else if(loadYesNo==false){
System.out.println("\n\n--------------------------------------------------------------------------");
System.out.println("\n Library not loaded!\n");
System.out.println("--------------------------------------------------------------------------\n");
Menu.displayMenu();
}
}
//Choice 0: Exit the program:
if(Menu.menuChoice == 0){
if(Menu.menuChoice == 0){
if(Library.ManualList.size() > 0){
boolean saveYesNo = Console.readYesNo("\nThe manualKeeper app is able to save your current library to a '.txt' \nfile in your home folder directory (C:\\Users\\ 'YOUR NAME').\n\nWould you like to save the current library? (Y/N):\n");
String fileName = "Library.bin";
if(saveYesNo==true){
try {
FileOutputStream fileOs = new FileOutputStream(fileName);
ObjectOutputStream os = new ObjectOutputStream(fileOs);
for (int i = 0; i < Library.ManualList.size(); i++){
os.writeObject(Library.ManualList.get(i).displayManual());
os.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("DONE WRITING!");
} else if(saveYesNo==false){
System.out.println("\n\n--------------------------------------------------------------------------");
System.out.println("\n Library not saved!\n");
System.out.println("--------------------------------------------------------------------------\n");
break exit;
}
Menu.displayMenu();
}else if(Library.ManualList.isEmpty()){
Menu.displayMenu();
}
}
}
}
System.out.println("\n ~ You have exited the manualKeeper app! ~ ");
System.out.println("\n Developed by Oscar Moore - 2014 - UWL\n");
System.out.println("\n <3\n");
}
}
Here is also my library class:
package library;
import java.util.ArrayList;
public class Library {
public static int ManualChoice;
static String returnManualTitle;
static String status1 = "Available";
static String status2 = "Borrowed";
public static ArrayList<Manual> ManualList = new ArrayList<Manual>();
static ArrayList<Manual> borrowedManuals = new ArrayList<Manual>();
static void addManual(){
Manual newManual = new Manual();
newManual.createManual();
ManualList.add(newManual);
System.out.println("\n\n--------------------------------------------------------------------------");
System.out.println("\n Manual added to library!\n");
System.out.println("--------------------------------------------------------------------------\n");
}
static void displayManualList(){
if (ManualList.isEmpty()){
System.out.println("-------------------------------------------------------------");
System.out.println(Messages.empltyLibraryMessage + Messages.tryAgainMessage);
System.out.println("-------------------------------------------------------------");
Menu.menuChoice = 8;
} else {
System.out.printf("\n\nHere are the Manual/s currently stored in the library:\n\n\n");
for (int i = 0; i < ManualList.size(); i++){
System.out.printf("-------------------- Index Number: %s --------------------\n",i);
System.out.println(ManualList.get(i).displayManual());
System.out.println("---------------------------------------------------------\n");
}
}
}
static void displayBorrowedManuals(){
if (ManualList.isEmpty()){
System.out.println("-------------------------------------------------------------");
System.out.println(Messages.empltyLibraryMessage + Messages.tryAgainMessage);
System.out.println("-------------------------------------------------------------");
Menu.menuChoice = 8;
} else {
for (int i = 0; i < borrowedManuals.size(); i++){
System.out.printf("-------------------- Index Number: %s --------------------\n",i);
System.out.println(borrowedManuals.get(i).displayManual());
System.out.println("---------------------------------------------------------");
}
}
}
public static void borrowManual(){
displayManualList();
ManualChoice = (Console.readInteger(Messages.enterManualIndexMessage, Messages.ManualIndexNotInListMessage, 0, Library.ManualList.size() - 1));
borrowLoop:
while(Menu.menuChoice == 3){
if ((ManualList.get(ManualChoice).status.equalsIgnoreCase(status1)) && (ManualList.size() >= ManualChoice)){
ManualList.get(ManualChoice).status = "Borrowed";
ManualList.get(ManualChoice).borrower = User.userName;
ManualList.get(ManualChoice).borrowDate = "Today.";
ManualList.get(ManualChoice).returnDate = "In two weeks.";
borrowedManuals.add(ManualList.get(ManualChoice));
System.out.println("\n--------------------------------------------------------------------------");
System.out.println("\n Manual borrowed!\n");
System.out.println("--------------------------------------------------------------------------\n");
break borrowLoop;
}else if(ManualList.get(ManualChoice).status.equalsIgnoreCase(status2) && ManualList.size() >= ManualChoice){
System.out.println("\n--------------------------------------------------------------------------");
System.out.println("\n "
+ " The Manual you wish to borrow is already on loan.");
System.out.println("\n--------------------------------------------------------------------------\n");
break borrowLoop;
}else if(ManualChoice > ManualList.size()-1){
System.out.println(Messages.noSuchManualMessage);
break borrowLoop;
}
if(ManualList.size() > 1){
displayManualList();
}
else if(ManualList.size() == 1){
ManualList.get(ManualChoice).status = "Borrowed";
ManualList.get(ManualChoice).borrower = User.userName;
ManualList.get(ManualChoice).borrowDate = "Today.";
ManualList.get(ManualChoice).returnDate = "In two weeks.";
borrowedManuals.add(ManualList.get(ManualChoice));
System.out.printf("\n\n %s\n\n", ManualList.get(ManualChoice).displayManual());
System.out.println("Please return the Manual within two weeks!\n");
displayManualList();
}
}
Menu.displayMenu();
}
static void returnManual(){
System.out.printf("\n\nHere are the Manual/s currently out on loan:\n\n");
if(borrowedManuals.size() > 0){
for (int i = 0; i < borrowedManuals.size(); i++)
System.out.println(borrowedManuals.get(i).displayManual());
returnManualTitle = Console.readString(Messages.enterManualSerial, Messages.tooShortMessage, 3);
}
int x = 0;
boolean serialExistance = false;
while (x < ManualList.size()){
if (ManualList.get(x).serial.equalsIgnoreCase(returnManualTitle)){
ManualList.get(x).status = "Available";
ManualList.get(x).borrower = "N/A";
ManualList.get(x).borrowDate = "N/A";
ManualList.get(x).returnDate = "N/A";
int p = 0;
while (p < borrowedManuals.size()) {
Manual borrowed = borrowedManuals.get(p);
if (borrowed.serial.equalsIgnoreCase(returnManualTitle)) {
borrowedManuals.remove(p);
break;
}
p++;
}
System.out.println(Messages.successReturnMessage);
serialExistance = true;
break;
}
x = x+1;
}
if(serialExistance == false){
boolean repeatReturnManual = Console.readYesNo("\n--------------------------------------------------------------------------" + "\n\nThe Manual with the serial "+"\""+returnManualTitle +"\""+ " wasn't found!"
+"\n\nDo you want to try again? (Y/N):\n");
System.out.println("\n--------------------------------------------------------------------------");
if(repeatReturnManual){
returnManual();
}
}else if(serialExistance){
Menu.menuChoice = 8;
}
}
public static void removeManual(){
if(ManualList.size() >0){
displayManualList();
ManualChoice = Console.readInteger(Messages.enterRemoveManualIndex ,Messages.ManualIndexNotInListMessage, 0, ManualList.size());
int p = 0;
while (p < borrowedManuals.size()){
if (borrowedManuals.get(p).title.equalsIgnoreCase(returnManualTitle)){
borrowedManuals.remove(p);
}
}
ManualList.remove(ManualChoice);
System.out.print(Messages.successRemovedManualMessages);
Menu.menuChoice = 8;
}
}
static void emptyLibrary(){
System.out.println("\n WARNING!");
System.out.println("\n You have chosen to delete all Manuals in the library.\n");
System.out.println("--------------------------------------------------------------------------");
boolean emptyLibraryChoice = Console.readYesNo("\nAre you sure you wish to destroy the library? (Y/N): \n");
System.out.println("\n--------------------------------------------------------------------------\n");
if(emptyLibraryChoice){
Library.ManualList.clear();
System.out.println(Messages.successEmptyLibraryMesssage);
System.out.println("--------------------------------------------------------------------------\n");
Menu.menuChoice = 8;
}
}
}
You are using ObjectInputStream not in the intended manner. The correct way would be like:
ObjectInputStream is = new ObjectInputStream(fileIs);
Library x = (Library) is.readObject(); // change Library to the type of object you are reading
System.out.println(x);
You probably need to change Library, but I could not find out, what type of object you are reading.

read from a text file and records are separated by empty lines (java)

I am stuck with this problem, please help:
I want to read a txt file and put the content into an ArrayList, and the format is like this:
name Yoshida Shuhei
birthday 8-04-1961
phone 0123456789
email abc#123.com
medicalHistory None
address 12 X Street, Suburb,
NSW, Australia
address 13 Y Street, Suburb, VIC, Australia
name Kazuo Hirai
medicalHistory None
email xyz#123.com
phone 0987654321
birthday 26-11-1972
the file contains several patient records, and the record within each patient’s records block may occur in any order(e.g. the first patient's name comes first, but the second patient's address comes first), and all records are separated by blank lines.
My idea is, if the current line is not a blank line, begin to read the patient records and add them into a patient object, here's my code:
public static ArrayList<Patient> getData(String fileName) {
try {
File file = new File(fileName);
Scanner reader = new Scanner(file);
ArrayList<Patient> recordList = new ArrayList<Patient>();
ArrayList<MedicalHistory> mhList = new ArrayList<MedicalHistory>();
int index = -1;
int mh_index = -1;
String s;
Patient p = null;
MedicalHistory mh = null;
boolean addressActive = false;
boolean mhActive = false;
while (reader.hasNext()) {
s = reader.nextLine();
Scanner line = new Scanner(s);
String cmd;
if (!s.trim().isEmpty()) {
cmd = line.next();
if (cmd.equalsIgnoreCase("name")) {
index++;
p = new Patient();
p.setName(line.nextLine());
recordList.add(index, p);
addressActive = false;
mhActive = false;
} else if (cmd.equalsIgnoreCase("address")) {
if (line.hasNext()) {
p.setAddress(line.nextLine().trim());
recordList.set(index, p);
}
addressActive = true;
mhActive = false;
} else if (cmd.equalsIgnoreCase("birthday")) {
p.setBirthday(line.nextLine());
recordList.set(index, p);
addressActive = false;
mhActive = false;
} else if (cmd.equalsIgnoreCase("email")) {
if (line.hasNext()) {
p.setEmail(line.nextLine());
recordList.set(index, p);
}
addressActive = false;
mhActive = false;
} else if (cmd.equalsIgnoreCase("phone")) {
if (line.hasNextInt()) {
p.setPhone(line.nextInt());
recordList.set(index, p);
}
addressActive = false;
mhActive = false;
} else if (cmd.equalsIgnoreCase("medicalHistory")) {
mh = new MedicalHistory();
//...parse the medicalHistory
addressActive = false;
mhActive = true;
} else if (addressActive) {
String address = p.getAddress() + " " + s.trim();
p.setAddress(address);
recordList.set(index, p);
} else if (mhActive) {
//to deal with multiple medical histories
} else
System.out.println("Error: no command:" + s);
}
}
reader.close();
return recordList;
} catch (Exception e) {
System.out.println("Error:- " + e.getMessage());
return null;
}
}
The problem is, my code can only handle when the name comes first; if the first non-empty line begins with other command(e.g. begins with address), there will be no new Patient() initialized for it, and the program will get an error...
So where exactly should I put the p = new Patient() in, the program to read the patient records no matter what the order of commands is, and then store the data in a Patient object?
Can anybody be able to improve my code and satisfy this condition? Thanks a lot!
I'd suggest that you read each block into a HashMap<String,String> that maps each attribute to its value from the file. When the block is finished (that is, when you see a blank line or the end of the file) you can process the block in whatever particular order of attributes you need so as to properly create a Patient object.
Alternatively, with your current logic, you only need to change it a bit to do what you want:
. . .
while (reader.hasNext()) {
s = reader.nextLine();
Scanner line = new Scanner(s);
String cmd;
if (!s.trim().isEmpty()) {
if (p == null) {
// starting a new block -- create a new patient record
p = new Patient();
recordList.add(p);
}
if (cmd.equalsIgnoreCase("name")) {
index++;
p.setName(line.nextLine());
addressActive = false;
mhActive = false;
} else if (cmd.equalsIgnoreCase("address")) {
if (line.hasNext()) {
p.setAddress(line.nextLine().trim());
}
addressActive = true;
mhActive = false;
} else if (cmd.equalsIgnoreCase("birthday")) {
p.setBirthday(line.nextLine());
addressActive = mhActive = false;
} else if (cmd.equalsIgnoreCase("email")) {
if (line.hasNext()) {
p.setEmail(line.nextLine());
}
addressActive = mhActive = false;
} else if (cmd.equalsIgnoreCase("phone")) {
if (line.hasNextInt()) {
p.setPhone(line.nextInt());
}
addressActive = mhActive = false;
} else if (cmd.equalsIgnoreCase("medicalHistory")) {
mh = new MedicalHistory();
//...parse the medicalHistory
addressActive = false;
mhActive = true;
} else if (addressActive) {
String address = p.getAddress() + " " + s.trim();
p.setAddress(address);
} else if (mhActive) {
//to deal with multiple medical histories
} else
System.out.println("Error: no command:" + s);
}
} else {
// blank line indicates end of block
p = null;
}
}
. . .
Note that when you modify the current patient record (referenced by p), you don't need to set the element of recordList again; it will be automatically updated, since it refers to the object already in the array list. With this, you don't need the index at all; you just add the new patient record to the end of recordList and keep modifying it as long as the input is still in the same block.
my idea would be to maintain the hashtable to store the complete data..
Hashtable<Integer,Hashtable<String,String>> ht = new Hashtable<Integer,Hashtable<String,String>>();
Integer to store the patient#, Hashtable to store the name,value pair.
("address","<addr>"), ("name","<name>")
HashMap is not thread safe.. It may give problem when you run it in multithreaded environment..

Categories

Resources