I want to validate email id which is entered by the user.
In my program the constraints are that there cannot be whitespaces,(-),(_) and more than one (#).
This is the code i have written but its not giving the right output.
the code is:
import java.io.*;
class test
{
void main() throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter your email-address");
String emailid=br.readLine().trim();
boolean ans=true;
int n=0;
while(ans)
{
for(int i=0;i<emailid.length();i++)
{
char temp=emailid.charAt(i);
if( Character.isLetterOrDigit(temp)==false && temp!='#' && temp!='.')
{
System.out.println("A email id can consist of only alphabets,numerics and '.'");
emailid=br.readLine().trim();
ans=true;
continue;
}
else
{
ans=false;
}
if(temp=='#')
{
n+=1;
}
if(n>1)
{
System.out.println("email id can have only one #..Please try again");
emailid=br.readLine().trim();
ans=true;
continue;
}
else
{
ans=false;
}
}
}
}
}
Related
I have to figure out a way to re-open a file that was initially an output file in order to make my program work.
My program needs to read from the input file first and then write to an output file.
Then I will prompt the user to enter code here`e option to input more or search any data from the output file.
My program starts with the option to 1-Insert more data, 2-Search Data, 3-Quit program.
I could close the I/O files after the user has input more data, but what if the user wants to search data first?
if(readFile==0)
{
FileReader inFile = new FileReader("DATA4STUDENTS.txt");
BufferedReader br = new BufferedReader(inFile);
FileWriter fw1 = new FileWriter("PASSED_STUDENTS.txt");
BufferedWriter bw1= new BufferedWriter(fw1);//Files i want to write and read again later on in the same program.
FileWriter fw2 = new FileWriter("FAILED_STUDENTS.txt");
BufferedWriter bw2 = new BufferedWriter(fw2);
PrintWriter pw1 = new PrintWriter(bw1);
PrintWriter pw2 = new PrintWriter(bw2);
pw1.print("STUDENT ID\t"+"SUBJECT CODE\t"+"CARRY MARK\t"+"STATUS\t"+"FINAL EXAM\t"+"STATUS\t"+"TOTAL MARK\t"+"STATUS\t"+"GRADE\t"+"GRADE SCORE");
pw1.println();
pw2.print("STUDENT ID\t"+"SUBJECT CODE\t"+"CARRY MARK\t"+"STATUS\t"+"FINAL EXAM\t"+"STATUS\t"+"TOTAL MARK\t"+"STATUS\t"+"GRADE\t"+"GRADE SCORE");
pw2.println();
int index=0;
Assessment [] a = new Assessment[100];
Assessment [] b = new Assessment[100];
double[] CM=new double[100]; //array for CarryMark
double[] FM= new double[100]; //array for FullMark
boolean[] PG=new boolean[100]; //array for Passing-Grade
while(((inData=br.readLine()) !=null))
{
StringTokenizer st = new StringTokenizer(inData,"#");
StudName=st.nextToken();
StudID=st.nextToken();
SubName=st.nextToken();
FullOn=Integer.parseInt(st.nextToken());
FullEX=Integer.parseInt(st.nextToken());
mark=Double.parseDouble(st.nextToken());
fullM=Integer.parseInt(st.nextToken());
EMark=Double.parseDouble(st.nextToken());
fullEM=Integer.parseInt(st.nextToken());
a[index]=new Ongoing_Assessment(StudName, StudID, SubName,FullOn, FullEX, mark, fullM);
b[index]=new Final_Exam_Assessment(StudName, StudID, SubName,FullOn,FullEX,EMark, fullEM);
if(a[index] instanceof Ongoing_Assessment)
{
Ongoing_Assessment OA=(Ongoing_Assessment) a[index];
CM[index]=OA.getFinalMark();
}
if(b[index] instanceof Final_Exam_Assessment)
{
Final_Exam_Assessment FEA=(Final_Exam_Assessment) b[index];
FM[index]=FEA.getFinalMark();
}
if((CM[index]+FM[index])>=a[index].PassingGrade())
{
PG[index]=true;
}
else
{
PG[index]=false;
}
index++;
}
for(int i=0;i<index;i++)
{
String mss=" ";
String mss1=" ";
String mss2=" ";
String grade=" ";
double grade2=0.00;
if(PG[i])
{
mss="PASS";
}
else
{
mss="FAIL";
}
if(a[i] instanceof Ongoing_Assessment)
{
Ongoing_Assessment OA=(Ongoing_Assessment) a[i];
mss1=OA.toString();
}
if(b[i] instanceof Final_Exam_Assessment)
{
Final_Exam_Assessment FEA=(Final_Exam_Assessment) b[i];
mss2=FEA.toString();
}
if(mss.equals("PASS"))
{
if((CM[i]+FM[i])>=91 &&(CM[i]+FM[i])<=100)
{
grade="A+";
grade2=4.00;
}
else if((CM[i]+FM[i])>=80 &&(CM[i]+FM[i])<=90)
{
grade="A";
grade2=4.00;
}
else if((CM[i]+FM[i])>=75 &&(CM[i]+FM[i])<=79)
{
grade="A-";
grade2=3.67;
}
else if((CM[i]+FM[i])>=70 &&(CM[i]+FM[i])<=74)
{
grade="B+";
grade2=3.33;
}
else if((CM[i]+FM[i])>=65 &&(CM[i]+FM[i])<=69)
{
grade="B";
grade2=3.00;
}
else if((CM[i]+FM[i])>=60 &&(CM[i]+FM[i])<=64)
{
grade="B-";
grade2=2.67;
}
else if((CM[i]+FM[i])>=55 &&(CM[i]+FM[i])<=59)
{
grade="C+";
grade2=2.33;
}
else if((CM[i]+FM[i])>=50 &&(CM[i]+FM[i])<=54)
{
grade="C";
grade2=2.00;
}
}
else if(mss.equals("FAIL"))
{
if((CM[i]+FM[i])>=47 &&(CM[i]+FM[i])<=49)
{
grade="C-";
grade2=1.67;
}
else if((CM[i]+FM[i])>=44 &&(CM[i]+FM[i])<=46)
{
grade="D+";
grade2=1.33;
}
else if((CM[i]+FM[i])>=40 &&(CM[i]+FM[i])<=43)
{
grade="D";
grade2=1.00;
}
else if((CM[i]+FM[i])>=30 &&(CM[i]+FM[i])<=39)
{
grade="E";
grade2=0.67;
}
else if((CM[i]+FM[i])>=0 &&(CM[i]+FM[i])<=29)
{
grade="F";
grade2=0.00;
}
}
if(mss.equals("PASS"))
{
**strong text**pw1.print(mss1+mss2+"\t"+df.format((CM[i]+FM[i]))+"%\t\t"+mss+"\t"+grade+"\t"+df.format(grade2));
pw1.println();
}
else
{
pw2.print(mss1+mss2+"\t"+df.format((CM[i]+FM[i]))+"%"+mss+"\t"+grade+"\t"+df.format(grade2));
pw2.println();
}
}
br.close();
pw1.close();
pw2.close();
}
Files cannot be reopened after they are closed. There is no way do that without recreating a object.
See https://stackoverflow.com/a/12347891/10818862 for more information.
I was trying to search for the specific data from the text file by using the ID.
But I was just able to search and display for the id T1001.
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String filepath = "Technician.txt";
System.out.print("Enter ID : ");
String searchTerm= sc.nextLine();
readRecord(searchTerm,filepath);
}
public static void readRecord(String searchTerm,String filepath){
boolean found = false;
String techID="";
String service="";
String firstName="";
String lastName="";
String salary="";
String position="";
String password="";
try
{
Scanner x = new Scanner(new File(filepath));
x.useDelimiter("[\\|]");
while(x.hasNext()&& !found)
{
techID = x.next();
service=x.next();
firstName=x.next();
lastName=x.next();
salary=x.next();
position=x.next();
password=x.next();
if(techID.equals(searchTerm)){
found = true;
}
}
if(found)
{
System.out.print("ID: "+techID+"\n"+"Service : "+service+"\n"+"First Name: "+firstName+"\n"+"Last Name : "+lastName+"\n" + "Salary : "+salary
+"\n" + "Position : "+position);
}
else
{
System.out.print("ID not found");
}
}
catch(Exception e)
{
}
}
And below is my text file :
T1001|Repair|Raymond|Lee|3000.00|staff|abc123|
T1002|Repaint|Joey|Tan|3000.00|staff|123456|
By Default Scanner class takes the first line as input from your file. But you have to read all lines, so its better to use #nextLine method and then #split method to extract your individual values from the line. Follow the bellow code :
import java.util.Scanner;
import java.io.*;
public class example {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String filepath = "Technician.txt";
System.out.print("Enter ID : ");
String searchTerm= sc.nextLine();
readRecord(searchTerm,filepath);
}
public static void readRecord(String searchTerm,String filepath){
try
{
Scanner x = new Scanner(new File(filepath));
while(x.hasNext())
{
String values[] = x.nextLine().toString().split("\\|");
if(values[0].equals(searchTerm)){
System.out.print("ID: "+values[0]+"\n"+"Service : "+values[1]+"\n"+"First Name: "+values[2]+"\n"+"Last Name : "+values[3]+"\n" + "Salary : "+values[4]
+"\n" + "Position : "+values[5] + "\n");
return;
}
}
System.out.print("ID not found");
}
catch(Exception e)
{
}
}
}
Reason of your error is that next line also contains string for next line "\n" and that's how techID is read. In my case it looks like "\n\nT1002" . That's why you need to use function contains and if not equals cut your ID. Your code:
public static void readRecord(String searchTerm,String filepath){
boolean found = false;
boolean toUpdate = false;
String techID="";
String service="";
String firstName="";
String lastName="";
String salary="";
String position="";
String password="";
try
{
Scanner x = new Scanner(new File(filepath));
x.useDelimiter("[\\|]");
while(x.hasNext()&& !found)
{
techID = x.next();
service=x.next();
firstName=x.next();
lastName=x.next();
salary=x.next();
position=x.next();
password=x.next();
if(techID.contains(searchTerm)){
found = true;
if(!techID.equals(searchTerm)) {
toUpdate = true;
}
}
}
if(found)
{
if(toUpdate) {
techID = techID.substring(4, techID.length());
}
System.out.print("ID: "+techID+"\n"+"Service : "+service+"\n"+"First Name: "+firstName+"\n"+"Last Name : "+lastName+"\n" + "Salary : "+salary
+"\n" + "Position : "+position);
}
else
{
System.out.print("ID not found");
}
x.close();
}
catch(Exception e)
{
e.printStackTrace();
}
finally {
}
}
}
Another way can be using delimiter two times. Firstly to make rows in result "x" and then make x.split("|") for example.
I can't get this part of my project to work. (fileOut() and fileIn() methods). I would appreciate any help!
I am trying to construct a method to open a text file and to write the details of an ArrayList of type to it.
I am also trying to construct a second method to open the text file containing details of all the bank’s accounts and uses the incoming data to create BankAccount objects using a BankAccount Constructor and storing each account in an ArrayList.
Please note that other methods in the class need to use the information stored in the arraylist(s).
Here is the main bit of code to focus on(reading and writing):
public void fileOut()
{
File fileName = new File("BankAccountFiles.txt");
try{
FileWriter fw = new FileWriter(fileName);
Writer output = new BufferedWriter(fw);
int numEntries = bankAccArrayList.size();
for (int i = 0; i < numEntries; i++) {
output.write(bankAccArrayList.get(i).toString() + "\n");
}
output.close();
}
catch(Exception e) {
JOptionPane.showMessageDialog(null,"File cannot be created");
}
}
public void fileIn()
{
ArrayList<BankAccount> aList = new ArrayList<BankAccount>();
String line;
try {
BufferedReader input = new BufferedReader(new FileReader("BankAccountFiles.txt"));
if(!input.ready()) {
throw new IOException();
}
while ((line = input.readLine()) != null) {
aList.add(line);
}
input.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null,e);
}
}
Here is the code for the whole class:
import javax.swing.JOptionPane;
import java.util.ArrayList;
import java.io.*;
import java.lang.*;
import java.util.*;
import javax.swing.*;
public class MyBankController
{
private ArrayList<BankAccount> bankAccArrayList;
public MyBankController()
{
bankAccArrayList = new ArrayList<BankAccount>();
}
public void createAccount (String accNum, String custName)
{
bankAccArrayList.add(new BankAccount( accNum,custName));
printAccountDetails(bankAccArrayList.get(bankAccArrayList.size()-1));
}
private void printAccountDetails(BankAccount incomingAcc)
{
JOptionPane.showMessageDialog(null,incomingAcc.toString(),"Account Details",JOptionPane.PLAIN_MESSAGE);
}
public void listAllAccounts()
{
String outputStr = "List of all accounts :\n\n";
for(BankAccount account : bankAccArrayList){
outputStr += account + "\n\n";
}
JOptionPane.showMessageDialog(null,outputStr,"List of all Accounts",JOptionPane.PLAIN_MESSAGE);
}
public void listAllActiveAccounts()
{
String outputStr = "List of all active accounts :\n\n";
for(BankAccount account : bankAccArrayList){
if(account.getActive()) {
outputStr += account + "\n\n";
}
}
JOptionPane.showMessageDialog(null,outputStr,"List of all Active Accounts",JOptionPane.PLAIN_MESSAGE);
}
private int getIndex(String bankAccNum)
{
for (int i = 0; i < bankAccArrayList.size(); i++) {
if (bankAccNum.equals(bankAccArrayList.get(i).getAccNumber()))
{
return i;
}
}
JOptionPane.showMessageDialog(null,"Bank Account Number: " + bankAccNum + " is invalid","Error wrong account number",JOptionPane.ERROR_MESSAGE);
return -1;
}
public void makeWithdrawal(String accNumber, double amount)
{
if(getIndex(accNumber) != -1){
bankAccArrayList.get(getIndex(accNumber)).makeWithdraw(amount);
}
}
public void makeLodgement(String accNumber, double amount)
{
if(getIndex(accNumber) != -1){
bankAccArrayList.get(getIndex(accNumber)).makeLodgement(amount);
}
}
public void displayAccount(String accNumber)
{
if(getIndex(accNumber) != -1){
JOptionPane.showMessageDialog(null,(bankAccArrayList.get(getIndex(accNumber)).toString()),"Accounts Details",JOptionPane.PLAIN_MESSAGE);
}
}
public void closeAccount(String accNumber)
{
if(getIndex(accNumber) != -1){
bankAccArrayList.get(getIndex(accNumber)).closeAccount();
}
}
public void removeAccount(String accNumber)
{
int index = getIndex(accNumber);
if(index != -1){
BankAccount myAcc = bankAccArrayList.get(index);
if ((myAcc.getActive() == false) && (myAcc.getAccBalance() == 0)){
bankAccArrayList.remove(index);
}else if((myAcc.getActive() == false) && (myAcc.getAccBalance() > 0)){
int dialogResult = JOptionPane.showConfirmDialog(null," This account has a balance,do you wish to withdraw this balance " +
"so as to remove the account ?"," Balance in inactive account",JOptionPane.PLAIN_MESSAGE);
if(dialogResult == JOptionPane.YES_OPTION){
myAcc.setActive();
myAcc.makeWithdraw(myAcc.getAccBalance());
myAcc.setActive();
bankAccArrayList.remove(index);
JOptionPane.showMessageDialog(null,"Account Removed","Confirmation",JOptionPane.PLAIN_MESSAGE);
}
} else if((myAcc.getActive() == true) && (myAcc.getAccBalance() == 0)){
int dialogResult = JOptionPane.showConfirmDialog(null," This account still has an active status, do you wish to change its status so as to remove account ?"
,"Account Active",JOptionPane.PLAIN_MESSAGE);
if(dialogResult == JOptionPane.YES_OPTION){
myAcc.setActive();
bankAccArrayList.remove(index);
JOptionPane.showMessageDialog(null,"Account Removed","Confirmation",JOptionPane.PLAIN_MESSAGE);
}
} else{
int dialogResult = JOptionPane.showConfirmDialog(null," This account still has an active status and a balance, do you wish to close the account so as remove it"
,"Account Active with Balance",JOptionPane.PLAIN_MESSAGE);
if(dialogResult == JOptionPane.YES_OPTION){
myAcc.closeAccount();
bankAccArrayList.remove(index);
JOptionPane.showMessageDialog(null,"Account Removed","Confirmation",JOptionPane.PLAIN_MESSAGE);
}
}
}
}
public void customerInterface()
{
String accNumber = JOptionPane.showInputDialog(null,"Please enter your account number","Account Login",JOptionPane.PLAIN_MESSAGE);
if(getIndex(accNumber) != -1)
{
String numOption = JOptionPane.showInputDialog(null,"Please select an option below:\n\n" +
" [1] Make a lodgment:\n\n [2] Make a withdrawal:\n\n [3] Display account details:\n\n" +
" [4] Close account:\n\n [5] Exit","MyBank ATM",JOptionPane.PLAIN_MESSAGE);
if (numOption == null) //User presses cancel or 'x'.
{
JOptionPane.showMessageDialog(null,"Goodbye.","MyBank System",JOptionPane.INFORMATION_MESSAGE);
}
else if(Integer.parseInt(numOption) == 1) //Converts numOption from String to Integer.
{
//Brings up lodgement interface
String amount = JOptionPane.showInputDialog("Please enter the amount you would like to lodge.");
makeLodgement(accNumber, Double.parseDouble(amount)); // Lodges amount into account.
customerInterface();
}
else if(Integer.parseInt(numOption) == 2)
{
String amount = JOptionPane.showInputDialog("Please enter the amount you wish to withdraw.");
makeWithdrawal(accNumber, Double.parseDouble(amount)); //Call on makeWithdrawl method.
customerInterface();
}
else if(Integer.parseInt(numOption) == 3)
{
displayAccount(accNumber); //Calls on displayAccount method.
customerInterface();
}
else if(Integer.parseInt(numOption) == 4)
{
closeAccount(accNumber); //Call on close account method.
customerInterface();
}
else if(Integer.parseInt(numOption) == 5)
{
return; //Exits system.
}
else if(Integer.parseInt(numOption) > 5 || Integer.parseInt(numOption) < 1) //If number enter is outside of 1-5.
{
JOptionPane.showMessageDialog(null,"Please enter a number between 1-5 and try again.","Error",JOptionPane.ERROR_MESSAGE);
customerInterface();
}
}
}
public void bankInterface()
{
String numOption = JOptionPane.showInputDialog(null,"Please select an option below:\n\n" +
" [1] Display All Accounts:\n\n [2] Display All Active Accounts:\n\n [3] Open a New Account:\n\n" +
" [4] Close an Existing Account:\n\n [5] Run Start of Day:\n\n [6] Run End of Day:\n\n [7] Exit:","MyBank System",JOptionPane.PLAIN_MESSAGE);
if (numOption == null)
{
JOptionPane.showMessageDialog(null,"Goodbye.","MyBank System",JOptionPane.INFORMATION_MESSAGE); //User presses cancel or 'x'.
}
else if(Integer.parseInt(numOption) == 1) //Converts numOption from String to Integer.
{
//Displays all accounts.
listAllAccounts();
bankInterface();
}
else if(Integer.parseInt(numOption) == 2)
{
//Display all active accounts.
listAllActiveAccounts();
bankInterface();
}
else if(Integer.parseInt(numOption) == 3)
{
//Open a new account
String accNum = JOptionPane.showInputDialog("Please allocate an account number:");
String custName = JOptionPane.showInputDialog("Please enter the customers name:");
createAccount (accNum, custName);
bankInterface();
}
else if(Integer.parseInt(numOption) == 4)
{
//Close an existing account.
String accNumber = JOptionPane.showInputDialog("Please enter the account number you would like to close:");
closeAccount(accNumber);
bankInterface();
}
else if(Integer.parseInt(numOption) == 5)
{
//Run start of day file.
fileIn();
bankInterface();
}
else if(Integer.parseInt(numOption) == 6)
{
//Run end of day file.
fileOut();
bankInterface();
}
else if(Integer.parseInt(numOption) == 7)
{
//Exits system.
return;
}
else if(Integer.parseInt(numOption) > 7 ||Integer.parseInt(numOption) < 1) //If user enters number outside of 1-7.
{
JOptionPane.showMessageDialog(null,"Please enter a number between 1-7 and try again.","Error",JOptionPane.ERROR_MESSAGE);
bankInterface();
}
}
public void fileOut()
{
File fileName = new File("BankAccountFiles.txt");
try{
FileWriter fw = new FileWriter(fileName);
Writer output = new BufferedWriter(fw);
int numEntries = bankAccArrayList.size();
for (int i = 0; i < numEntries; i++) {
output.write(bankAccArrayList.get(i).toString() + "\n");
}
output.close();
}
catch(Exception e) {
JOptionPane.showMessageDialog(null,"File cannot be created");
}
}
public void fileIn()
{
ArrayList<BankAccount> aList = new ArrayList<BankAccount>();
String line;
try {
BufferedReader input = new BufferedReader(new FileReader("BankAccountFiles.txt"));
if(!input.ready()) {
throw new IOException();
}
while ((line = input.readLine()) != null) {
aList.add(line);
}
input.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null,e);
}
}
}
In your fileIn method, you're trying to add a String to an ArrayList of type BankAccount. Instead of aList.add(line), you should use aList.add(new BankAccount(line)).
Assuming your BankAccount constructor takes only a single String parameter, this should work.
Full method:
public void fileIn()
{
List<BankAccount> aList = new ArrayList<BankAccount>();
String line;
try {
BufferedReader input = new BufferedReader(new FileReader("BankAccountFiles.txt"));
if(!input.ready()) {
throw new IOException();
}
while ((line = input.readLine()) != null) {
aList.add(new BankAccount(line));
}
input.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null,e);
}
aList.forEach(System.out::println); // Java8
}
I've also changed your aList to use the List interface, and added a lambda to print each value in aList at the end.
I am currently working on a project for school that is due tonight and have exhausted my resources. I am required to build an authentication program for a zoo that allows an employee to login with limited attempts. After a successful login it is suppose to display their text file according to their role in the fourth column.
griffin.keyes 108de81c31bf9c622f76876b74e9285f "alphabet soup" zookeeper
rosario.dawson 3e34baa4ee2ff767af8c120a496742b5 "animal doctor" admin
bernie.gorilla a584efafa8f9ea7fe5cf18442f32b07b "secret password" veterinarian
donald.monkey 17b1b7d8a706696ed220bc414f729ad3 "M0nk3y business" zookeeper
jerome.grizzlybear 3adea92111e6307f8f2aae4721e77900 "grizzly1234" veterinarian
bruce.grizzlybear 0d107d09f5bbe40cade3de5c71e9e9b7 "letmein" admin
I have successful login, limited to 3 attempts, and the option to logout and exit, but I can't seem to figure out why it isn't loading their role files accordingly.. Any help on this would be much appreciated!
import java.io.File;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.util.List;
import java.util.Scanner;
public class AuthenticationSystem {
public static void main(String args[]) {
try {
Scanner scan;
scan = new Scanner(new File("C:\\Users\\Zane Hewgley\\Desktop\\AuthSys\\.idea\\credentials.txt"));
String credentials[][] = new String[100][4];
int count = 0;
while (scan.hasNextLine()) {
//read file
credentials[count][0] = scan.next();
credentials[count][1] = scan.next();
//obtain credentials from file
String l[] = scan.nextLine().split("\"[ ]+");
l[0] = l[0].trim();
l[0] = l[0].replace("\"", "");
credentials[count][2] = l[0];
credentials[count][3] = l[0].trim();
count++;
}
//request user input
Scanner input = new Scanner(System.in);
boolean RUN = true;
int tries = 0;
while (RUN) {
System.out.println("-Welcome-");
System.out.println("1-Login");
System.out.println("2-Exit");
int ch = Integer.parseInt(input.nextLine().trim());
if (ch == 1) {
//increment number of attempts
tries++;
//request username and password
System.out.print("Username: ");
String username = input.nextLine();
System.out.print("Password: ");
String password = input.nextLine();
//generate hash
MessageDigest md;
md = MessageDigest.getInstance("MD5");
md.update(password.getBytes());
byte[] digest = md.digest();
StringBuilder sb = new StringBuilder();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
String hPassword = sb.toString();
boolean badUser = true;
for (int i = 0; i < count; i++) {
if (username.contentEquals(credentials[i][0])) {
if (hPassword.contentEquals(credentials[i][1])) {
//if verified, logged in
List<String> data = null;
//check type of user and print
switch (credentials[i][3]) {
case "zookeeper":
data = Files.readAllLines(Paths.get("zookeeper.txt"), Charset.defaultCharset());
break;
case "admin":
data = Files.readAllLines(Paths.get("admin.txt"), Charset.defaultCharset());
break;
case "veterinarian":
data = Files.readAllLines(Paths.get("veterinarian.txt"), Charset.defaultCharset());
break;
default:
break;
}
if (data != null) {
for (String s : data) {
System.out.println(s);
}
}
//reset
tries = 0;
System.out.println("\n1) Logout.");
System.out.println("2) Exit.");
ch = Integer.parseInt(input.nextLine().trim());
if (ch == 2) {
RUN = false;
}
badUser = false;
break;
}
}
}
if (badUser) {
System.out.println("Invalid Username or password.");
}
} else {
break;
}
//limit attempts
if (tries == 3) {
RUN = false;
System.out.println("Immoderate attempts!");
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
When you split the array information:
String l[] = scan.nextLine().split("\"[ ]+");
l[0] = l[0].trim();
l[0] = l[0].replace("\"", "");
you go on to write the result - which is the password - in credentials[count][3]; so this will later contain the password when you check if it is a zookeper, etc.
Above you have fixed lengths; if you use that, you could split up the line like this:
while (scan.hasNextLine()) {
String line = scan.nextLine();
credentials[count][0] = line.substring(0, 20).trim();
credentials[count][1] = line.substring(20, 55).trim();
credentials[count][2] = line.substring(55, 74).trim();
credentials[count][3] = line.substring(74).trim();
count++;
}
As the topic states im trying to get a specific string that is usually auto generated into the same string and it seems to work because the temp file is created and the string is replaced with "" but its seems that there is an IOException when it comes to renaming to original when deleting , help please?
import java.io.*;
import java.util.Scanner;
/**
* Main class to test the Road and Settlement classes
*
* #author Chris Loftus (add your name and change version number/date)
* #version 1.0 (24th February 2016)
*
*/
public class Application {
private Scanner scan;
private Map map;
private static int setting;
public Application() {
scan = new Scanner(System.in);
map = new Map();
}
private void runMenu() {
setting = scan.nextInt();
scan.nextLine();
}
// STEP 1: ADD PRIVATE UTILITY MENTHODS HERE. askForRoadClassifier, save and
// load provided
private Classification askForRoadClassifier() {
Classification result = null;
boolean valid;
do {
valid = false;
System.out.print("Enter a road classification: ");
for (Classification cls : Classification.values()) {
System.out.print(cls + " ");
}
String choice = scan.nextLine().toUpperCase();
try {
result = Classification.valueOf(choice);
valid = true;
} catch (IllegalArgumentException iae) {
System.out.println(choice + " is not one of the options. Try again.");
}
} while (!valid);
return result;
}
private void deleteSettlement() {
String name;
int p;
SettlementType newSetK = SettlementType.CITY;
int set;
System.out.println("Please type in the name of the settlement");
name = scan.nextLine();
System.out.println("Please type in the population of the settlment");
p = scan.nextInt();
scan.nextLine();
System.out.println("Please type in the number of the type of settlement .");
System.out.println("1: Hamlet");
System.out.println("2: Village");
System.out.println("3: Town");
System.out.println("4: City");
set = scan.nextInt();
scan.nextLine();
if (set == 1) {
newSetK = SettlementType.HAMLET;
}
if (set == 2) {
newSetK = SettlementType.VILLAGE;
}
if (set == 3) {
newSetK = SettlementType.TOWN;
}
if (set == 4) {
newSetK = SettlementType.CITY;
}
String generatedResult = "Name: " + name + " Population: " + p + " SettlementType " + newSetK;
String status = searchAndDestroy(generatedResult);
}
private String searchAndDestroy(String delete) {
File file = new File("C:\\Users\\Pikachu\\workspace\\MiniAssignment2\\settlements.txt");
try {
File temp = File.createTempFile("settlement", ".txt", file.getParentFile());
String charset = "UTF-8";
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));
for (String line; (line = reader.readLine()) != null;) {
line = line.replace(delete, "");
writer.println(line);
}
System.out.println("Deletion complete");
reader.close();
writer.close();
file.delete();
temp.renameTo(file);
}
catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
System.out.println("Sorry! Can't do that! 1");
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("Sorry! Can't do that! 2");
}
}
catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Sorry! Can't do that! , IO Exception error incurred 3");
}
return null;
}
private void save() {
map.save();
}
private void load() {
map.load();
}
public void addSettlement() {
String name;
int p;
SettlementType newSetK = SettlementType.CITY;
int set;
System.out.println("Please type in the name of the settlement");
name = scan.nextLine();
System.out.println("Please type in the population of the settlment");
p = scan.nextInt();
scan.nextLine();
System.out.println("Please type in the number of the type of settlement .");
System.out.println("1: Hamlet");
System.out.println("2: Village");
System.out.println("3: Town");
System.out.println("4: City");
set = scan.nextInt();
scan.nextLine();
if (set == 1) {
newSetK = SettlementType.HAMLET;
}
if (set == 2) {
newSetK = SettlementType.VILLAGE;
}
if (set == 3) {
newSetK = SettlementType.TOWN;
}
if (set == 4) {
newSetK = SettlementType.CITY;
}
new Settlement(name, newSetK, p);
}
private void printMenu() {
System.out.println("Please type in the number of the action that you would like to perform");
System.out.println("1: Create Settlement");
System.out.println("2: Delete Settlement");
System.out.println("3: Create Road");
System.out.println("4: Delete Road");
System.out.println("5:Display Map");
System.out.println("6:Save Map");
}
public static void main(String args[]) {
Application app = new Application();
app.printMenu();
app.runMenu();
System.out.println(setting);
if (setting == 1) {
app.addSettlement();
}
if (setting == 2) {
app.deleteSettlement();
}
app.load();
app.runMenu();
app.save();
}
}
I checked if it was deletable (file.delete throws a boolean exception) so I tried deleting it directly via windows and apparently it was being used by java so I assumed eclipsed glitch and upon closing and booting up eclipse again it worked..... well... that was rather anti-climactic .... Thank you so much for the discussion , I would definitely never had figured it out if not for the discussion :D <3 You are all in my heart