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();
}
}
}
}
Related
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"));
Hi. I'm having the issue in an error of exception. I don't know what is wrong. But please help me fix this. I'm trying to store data from the file to ArrayList and display the data in the ArrayList. Here, I attached my code and data Code and data source.
the NoSuchElementException appears because you are calling input.nextToken(); while input doesn't have any token.It's due to the last empty line of your file listbook.txt. By deleting this line, the exception shouldn't appear.
A proper manner could be to ensure that you have sufficient tokens to retrieve all your fields for a given line.
public class TextFile
{
public static void main(String[] args)
{
try
{
FileReader read = new FileReader("C:\\Users\\ogawi\\Downloads\\listbook.txt");
BufferedReader bf = new BufferedReader(read);
Book B = new Book();
ArrayList<Book> bookList = new ArrayList<Book>();
String data = null;
StringTokenizer input = null;
while((data = bf.readLine()) != null)
{
input = new StringTokenizer(data,";");
//we ensure that we have enough tokens to retrieve all fields
if(input.countTokens() == 6)
{
String title = input.nextToken();
String author = input.nextToken();
String publisher = input.nextToken();
String genre = input.nextToken();
int year = Integer.parseInt(input.nextToken());
int page = Integer.parseInt(input.nextToken());
B = new Book(title, author, publisher, genre, year, page);
bookList.add(B);
}
}
//This part of code has been moved outside the while loop
//to avoid to print the total content of the array each time
//an element is added
int count=0;
for(int i=0;i<bookList.size();i++)
{
B = (Book)bookList.get(i);
System.out.println(B.toString());
System.out.println("=============================");
count++;
}
System.out.println("Number of Books: " + count);
bf.close();
}
catch(FileNotFoundException fnf)
{ System.out.println(fnf.getMessage());}
catch(EOFException eof)
{ System.out.println(eof.getMessage());}
catch(IOException io)
{ System.out.println(io.getMessage());}
finally
{ System.out.println("System end here..TQ!!");}
}
}
This issue is due to the extra line without book information:
You can see the line 31 and 32 in above figure.
To solve this issue you can add one if condition data.contains(";") . Text file has ; delimiter if we check the condition if given line has ; delimiter then it won't cause an issue.
while ((data = bf.readLine()) != null) {
if (data.contains(";")) {
input = new StringTokenizer(data, ";");
String title = input.nextToken();
String author = input.nextToken();
String publisher = input.nextToken();
String genre = input.nextToken();
int year = Integer.parseInt(input.nextToken());
int page = Integer.parseInt(input.nextToken());
B = new Book(title, author, publisher, genre, year, page);
bookList.add(B);
int count = 0;
for (int i = 0; i < bookList.size(); i++) {
B = (Book) bookList.get(i);
System.out.println(B.toString());
System.out.println("=============================");
count++;
}
System.out.println("Number of Books: " + count);
}
}
Here is the screenshot for successful execution of the code.
I have a csv file which is hashmapped, whenever the user enter the city name(key) it will display all the details of that city. I have to optimize the search result time, everytime the it is reading the file(instead of only once) and displaying the values.
The CSV files contains data like this :
city,city_ascii,lat,lng,country,iso2,iso3,admin_name,capital,population,id
Malishevë,Malisheve,42.4822,20.7458,Kosovo,XK,XKS,Malishevë,admin,,1901597212
Prizren,Prizren,42.2139,20.7397,Kosovo,XK,XKS,Prizren,admin,,1901360309
Zubin Potok,Zubin Potok,42.9144,20.6897,Kosovo,XK,XKS,Zubin
Potok,admin,,1901608808
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.io.IOException;
public class CSVFileReaders{
public static void main(String[] args) {
String filePath = "C:\\worldcities1.csv";
Scanner in = new Scanner(System.in);
System.out.println(" \n Enter the City name to be Searched : \n _> ");
long start = System.currentTimeMillis();
String searchTerm = in.nextLine();
readAndFindRecordFromCSV(filePath, searchTerm);
long end = System.currentTimeMillis();
System.out.println(" \n It took " + (end - start) + " Milli Seconds to search the result \n");
in.close();
}
public static void readAndFindRecordFromCSV( String filePath, String searchTerm) {
try{
HashMap<String,ArrayList<String>> cityMap = new HashMap<String,ArrayList<String>>();
Scanner x = new Scanner (new File(filePath),"UTF-8");
String city= "";
while(x.hasNextLine()) {
ArrayList<String> values = new ArrayList<String>();
String name = x.nextLine();
//break each line of the csv file to its elements
String[] line = name.split(",");
city = line[1];
for(int i=0;i<line.length;i++){
values.add(line[i]);
}
cityMap.put(city,values);
}
x.close();
//Search the city
if(cityMap.containsKey(searchTerm)) {
System.out.println("City name is : "+searchTerm+"\nCity details are accordingly in the order :"
+ "\n[city , city_ascii , lat , lng , country , iso2 , iso3 , admin_name , capital , population , id] \n"
+cityMap.get(searchTerm)+"");
}
else {
System.out.println("Enter the correct City name");
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}`
the time should be optimized and every time i search it is reading the entire file(which should happen)
Currently you mix the map initialization inside the search function.
You don't want that.
First, init the map, then use it in the search function.
To do that, extract a method for statements that instantiate and value the map and then refactor the readAndFindRecordFromCSV() method so that it accepts a Map as additional parameter :
public static void readAndFindRecordFromCSV( String filePath, String searchTerm, HashMap<String,ArrayList<String>> dataByCity) {...}
With refactoring IDE features, it should be simple enough : "extracting method" then "change signature".
Here is a code (not tested at runtime but tested at compile time) that splits the logical in separated tasks and also rely on instance methods :
public class CSVFileReaders {
private final String csvFile;
private HashMap<String, ArrayList<String>> cityMap;
private final Scanner in = new Scanner(System.in);
public static void main(String[] args) {
String filePath = "C:\\worldcities1.csv";
CSVFileReaders csvFileReaders = new CSVFileReaders(filePath);
csvFileReaders.createCitiesMap();
csvFileReaders.processUserFindRequest(); // First search
csvFileReaders.processUserFindRequest(); // Second search
}
public CSVFileReaders(String csvFile) {
this.csvFile = csvFile;
}
public void createCitiesMap() {
cityMap = new HashMap<>();
try (Scanner x = new Scanner(new File(csvFile), "UTF-8")) {
String city = "";
while (x.hasNextLine()) {
ArrayList<String> values = new ArrayList<String>();
String name = x.nextLine();
//break each line of the csv file to its elements
String[] line = name.split(",");
city = line[1];
for (int i = 0; i < line.length; i++) {
values.add(line[i]);
}
cityMap.put(city, values);
}
x.close();
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
public void processUserFindRequest() {
System.out.println(" \n Enter the City name to be Searched : \n _> ");
long start = System.currentTimeMillis();
String searchTerm = in.nextLine();
long end = System.currentTimeMillis();
System.out.println(" \n It took " + (end - start) + " Milli Seconds to search the result \n");
//Search the city
if (cityMap.containsKey(searchTerm)) {
System.out.println("City name is : " + searchTerm + "\nCity details are accordingly in the order :"
+ "\n[city , city_ascii , lat , lng , country , iso2 , iso3 , admin_name , capital , population , id] \n"
+ cityMap.get(searchTerm) + "");
} else {
System.out.println("Enter the correct City name");
}
}
}
The interesting part is here :
String filePath = "C:\\worldcities1.csv";
CSVFileReaders csvFileReaders = new CSVFileReaders(filePath);
csvFileReaders.createCitiesMap();
csvFileReaders.processUserFindRequest(); // First search
csvFileReaders.processUserFindRequest(); // Second search
The logical is clearer now.
Why do you create / load the CSV into a HashMap with every search ?
Just create the HashMap only once in the beginning, and then on every search just check whether it exists in the HashMap, eg move the read part into a separate method :
HashMap<String,ArrayList<String>> cityMap = new HashMap<String,ArrayList<String>>();
public static void readCSVIntoHashMap( String filePath) {
try{
Scanner x = new Scanner (new File(filePath),"UTF-8");
String city= "";
while(x.hasNextLine()) {
ArrayList<String> values = new ArrayList<String>();
String name = x.nextLine();
//break each line of the csv file to its elements
String[] line = name.split(",");
city = line[1];
for(int i=0;i<line.length;i++){
values.add(line[i]);
}
cityMap.put(city,values);
}
x.close();
...
}
Then have a separate method for searching :
public static void search(String searchTerm) {
if(cityMap.containsKey(searchTerm)) {
...
}
}
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());
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
}