Adding a condition to accept specific entries in HashMap - java

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

Related

How to delete a word from the csv file

How to delete a word from the csv file when it is used so as not to have the same question twice with the same word and stop when all the words have been used?
import extensions.CSVFile;
CSVFile wordPrice = loadCSV("wordPrice");
class Word {
String word;
int price;
}
void play (Word info) {
int RightPrice = info.price;
int Price;
println("What is the price of a" + info.word);
do{
counter = counter + 1;
Price = readInt();
if (Price<RightPrice){
println("It's +");
}
else if (Price>RightPrice) {
println("It's -");
}
}
Word randWord(){
Word mp = new Word();
int line = (int)(random() * rowCount(wordPrice));
mp.word = getCell(wordPrice, line, 0);
String price = getCell(wordPrice, line, 1);
mp.price = stringToInt(price);
return mp;
}
boolean replay(boolean exit) {
println("Do you wan to play again (Y : Yes, N : No) ?");
char answer = readChar();
if(answer == 'N') {
exit = true;
}
if(answer == 'Y') {
exit = false;
}
return exit;
}
void algorithm(){;
println("Find the price of items to win !");
boolean exxite = false;
while(exxite == false) {
Word randWord = randWord();
play(randWord);
exxite = replay(exxite);
}
}
csv name: wordPrice.
There are two columns, one with the words and the other with the prices.
You can try for that HashMap with key as a word and value as a price. Then just use this data structure in your algorithm.
So it could be something like that:
// CSV to map
Map<String, String> wordAndPrice = new HashMap<>();
try (BufferedReader br = new BufferedReader(new FileReader("wordPrice.csv"))) {
String currentLine;
while ((currentLine = br.readLine()) != null) {
String[] values = currentLine.split(",");
wordAndPrice.put(values[0], values[1]);
}
};
// remove unused words from map (use Iterator because you can get ConcurrentModification exception)
Iterator<Entry<String, String>> iterator = wordAndPrice.entrySet().iterator();
while (iterator.hasNext()) {
if (iterator.next().getKey().equals("Your word"))
iterator.remove();
}
As you pointed tag OpenCSV, you can use it to load csv file instead of BufferedReader:
CSVReader csvReader = new CSVReader(new FileReader("wordPrice.csv"));

infinite loop stuck and having problem with code in java

the task at hand is to make a Blood Transfusion Manager application that efficiently chooses donors for blood transfusion.
When the application is launched it should try to open two files: “donors.txt” and “recipients.txt”. If one of the files is missing the program should announce the problem and exit. Both files should be formatted in the following way: each row should contain a person’s full name and their blood type separated by semicolon. The program should first read donors.txt, split each line into name and blood type and store the resulting array as a new element in a donors arraylist. It should also print the list on the screen and check that each person’s blood type is valid. If an invalid blood type is found that entry should not be added to the arraylist and the user should be notified which entry had a problem. Recipients should then be read, processed and stored (in recipients arraylist) in a similar manner this is part one of the task
this is my previous code and after updating it more to get closer to the end of my task i found that the code stopped work i debugged it and found that it is stuck in an infinite loop not sure how to fix it to or if there any other way to rewrite it to work maybe not using a while loop
package java_assigment_4;
import java.io.*;
import java.util.*;
public class java_assigment_4 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner file_donors;
Scanner file_recp;
ArrayList list_donors = new ArrayList();
ArrayList list_recp = new ArrayList();
String blood_type = "o- o+ a- a+ b- b+ ab- ab+";
try
{
file_donors = new Scanner(new FileReader("donors.text"));
while (file_donors.hasNextLine())
{
list_donors.add(file_donors.nextLine()); // store donors names & blood type in array list
}//end while
file_donors.close();
}//end try
catch (FileNotFoundException e)
{
System.out.println("Error: " + e.getMessage());
}//end catch
try
{
file_recp = new Scanner(new FileReader("recipients.text"));
while (file_recp.hasNextLine())
{
list_recp.add(file_recp.nextLine()); // store recipents names & blood type in array list
}//end while
file_recp.close();
}//end try
catch (FileNotFoundException e)
{
System.out.println("Error: " + e.getMessage());
}//end catch
System.out.println("donors " + list_donors);
System.out.println("\n");
System.out.println("recipents " + list_recp);
// for (int i=0;i<list_donors.size();i++) {
// list_donors.contains(";"); // need a substring to store type after ;
}
}
}
this code below is the lastest code and is the one that is not working
public class java_assigment_4 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner file_donors;
Scanner file_recp;
ArrayList<String> list_donors = new ArrayList<String>();
ArrayList<String> list_recp = new ArrayList<String>();
String [] blood_type = {"o-","o+","a-","a+","b-","b+","ab-","ab+"};
try
{
file_donors = new Scanner(new FileReader("donors.txt"));
while (file_donors.hasNextLine())
{
for (int i=0;i<list_donors.size();i++) {
String donor=list_donors.get(i);
String type =donor.substring((donor.indexOf(";") + 1)); // look for ; and stores info after witch is the blood type into a substring so i can use for checking if vaild
type=type.trim();
for (int z=0;z<blood_type.length;z++) {
if (type.equals(blood_type [z])) { compares the two lists
list_donors.add(file_donors.nextLine()); // store donors names & blood if vaild type in array list
}
else {
System.out.println( "this person with blood;" + type + " is not valid ");
}
}
}
}
file_donors.close();
}
catch (FileNotFoundException e)
{
System.out.println("Error: " + e.getMessage());
}
System.out.println("donors " + list_donors);
try
{
file_recp = new Scanner(new FileReader("recipients.txt"));
while (file_recp.hasNextLine())
{
for (int i=0;i<list_recp.size();i++) {
String recp=list_recp.get(i);
String type =recp.substring((recp.indexOf(";") + 1));
type=type.trim();
for (int z=0;z<blood_type.length;z++) {
if (type.equals(blood_type [z])) { // compares the two lists
list_recp.add(file_recp.nextLine()); // store recp names & blood type if vaild in array list
}
else {
System.out.println( "this person with blood ;" + type + " is not valid ");
}
}
}
}
file_recp.close();
}
catch (FileNotFoundException e)
{
System.out.println("Error: " + e.getMessage());
}
// System.out.println("donors " + list_donors);
// System.out.println("\n");
// System.out.println("recipents " + list_recp);
}
}
The list_donors.size() will always return 0,
cause the list_donors is empty when it begins
so the code never call file_donors.nextLine()
and file_donors.hasNextLine() will be always true
public class java_assigment_4 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner file_donors;
Scanner file_recp;
ArrayList<String> list_donors = new ArrayList<String>();
ArrayList<String> list_recp = new ArrayList<String>();
String [] blood_type = {"o-","o+","a-","a+","b-","b+","ab-","ab+"};
try
{
file_donors = new Scanner(new FileReader("donors.txt"));
// file_donors.hasNextLine() always true in your code
while (file_donors.hasNextLine())
{
// list_donors.size() will return 0, cause the list_donors is empty when it begins
// so the code never enter this for and never call file_donors.nextLine()
for (int i=0;i<list_donors.size();i++) {
...
}
}
you can avoid this kind of situation doing something like
while (file_donors.hasNextLine())
{
string current_line = file_donors.hasNextLine();
updating with some code to help
import java.io.*;
import java.util.*;
public class Blood
{
public static void main(String[] args)
{
ArrayList<String> list_donors = new ArrayList<String>();
ArrayList<String> list_recp = new ArrayList<String>();
System.out.println("Starting!");
copyFromFile("/home/mitz/stackoverflow/java/Donors.txt", list_donors);
System.out.println("imported "+ list_donors.size() + " registers");
copyFromFile("/home/mitz/stackoverflow/java/Receptors.txt", list_recp);
System.out.println("imported "+ list_recp.size() + " registers");
System.out.println("Finished!");
}
public static void copyFromFile(String filename, ArrayList<String> listDestiny)
{
Scanner fileScanner;
FileReader fileReader;
try
{
fileReader = new FileReader(filename);
fileScanner = new Scanner(fileReader);
while (fileScanner.hasNextLine())
{
String currentLine = fileScanner.nextLine();
String type = currentLine.substring((currentLine.indexOf(";") + 1));
if(isValidBloodType(type))
{
listDestiny.add(currentLine);
System.out.println("Imported: " + currentLine);
}else{
System.out.println("Invalid blood type!! Alien detected with blood type: " + type);
}
}
fileScanner.close();
}
catch (FileNotFoundException e)
{
System.out.println("Arquivo não encontrado");
}
}
public static Boolean isValidBloodType(String type)
{
String[] blood_type = {"o-", "o+", "a-", "a+", "b-", "b+", "ab-", "ab+"};
return Arrays.asList(blood_type).contains(type);
}
}

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?

Java Passing strings and string[] into another class

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
}

My input is coming different in my program

The problem is that my input is 2, but according to my program it is 50. There is something wrong which I cannot understand. Here my aim is to make a contacts application where a user can keep on adding his/her contacts and all is saved and organized in the hash map.
For testers in the field of IO, I have been working with only the method contactList(). So at the moment other methods have not a lot of functionality.
package examples.hash.hashmap.IOintegration;
import java.util.HashMap;
import java.io.*;
public class Contacts{
/*Aim:
*Takes input from the user to add, remove or read a contact's number
*It also can show you all the contacts the user has added
*What's more it is finally integrated with IO!!
*/
//Initializing some very crucial variables
HashMap contacts = new HashMap();
InputStreamReader keyboardMethod = new InputStreamReader(System.in);
BufferedReader readerMethod = new BufferedReader(keyboardMethod);
public void contactList(){
System.out.println(contacts.entrySet());
}
public void addContact(){
System.out.println("Give contacts name");
}
public void removeContact(){}
public int getNumber(){
return 1;
}
public static void main(String[] args)throws IOException{
InputStreamReader keyboardOption = new InputStreamReader(System.in);
BufferedReader readerOption = new BufferedReader(keyboardOption);
Contacts obj = new Contacts();
System.out.print("Type in your option: ");
int option = readerOption.read();
System.out.println(option);
if(option == 1){
obj.addContact();
}
if(option == 2){
System.out.println("HI");
obj.contactList();
}
if(option == 3){
obj.getNumber();
}
if(option == 4){
obj.removeContact();
}
}
}
FYI: read() returns a character value, technically a char, but it has to be an int in order to allow the extra -1 value for EOF.
Comment by azurefrog is right, the char value '2' is the numeric ASCII/Unicode value 50.
If you want to read a number entered by the user, do this:
int option = Integer.parseInt(readerOption.readLine());
Beware bad user input.
Andreas is right!
I also know ur intention for ur application!
a while{} loop can solve ur problem!
My English is not skilled ,so I improved ur code!
Change the package's name
package com.fan.component;
import java.util.HashMap;
import java.io.*;
public class Contacts{
/*Aim:
*Takes input from the user to add, remove or read a contact's number
*It also can show you all the contacts the user has added
*What's more it is finally integrated with IO!!
*/
//Initializing some very crucial variables
HashMap contacts = new HashMap();
InputStreamReader keyboardMethod = new InputStreamReader(System.in);
BufferedReader readerMethod = new BufferedReader(keyboardMethod);
public void contactList(){
System.out.println(contacts.entrySet());
}
public void addContact() throws IOException{
System.out.println("Give contacts name");
//details
String contactName = readerMethod.readLine();
String contactNumber= readerMethod.readLine();
contacts.put(contactName, contactNumber);
}
public void removeContact() throws IOException{
//details
System.out.println("Give contacts name to remove");
String contactName = readerMethod.readLine();
String contactNumber = (String) contacts.get(contactName);
if(contactName != null)
contacts.remove(contactNumber);
else
System.out.println("No this contact");
}
public void getNumber() throws IOException{
//return 1;
System.out.println("input contact name");
String contactName = readerMethod.readLine();
String contactNum = (String) contacts.get(contactName);
if(contacts == null)
System.out.println("No this contact named " + contactName);
else
System.out.println(contactName + " : " + contactNum );
}
public static void main(String[] args)throws IOException{
InputStreamReader keyboardOption = new InputStreamReader(System.in);
BufferedReader readerOption = new BufferedReader(keyboardOption);
Contacts obj = new Contacts();
/*
* added code
*/
while(true)
{
System.out.print("Type in your option: ");
int option = Integer.parseInt(readerOption.readLine());
System.out.println(option);
//add new contact
if(option == 1){
obj.addContact();
}
//check contact list
if(option == 2){
System.out.println("HI");
obj.contactList();
}
//get number
if(option == 3){
obj.getNumber();
}
//remove contact
if(option == 4){
obj.removeContact();
}
}
}
}

Categories

Resources