Java for loop with if statement only iterating once - java

I have a version of a login for an employee system i would like to make, I have a for loop which should go through the entire list of Accounts, then see if the name of an employee matches one in the list then the if statement continues, further questions asked etc... it seems to only iterate once and then stop as it will only find the first user and tell me the other accounts do not exisit, even though they do!! What am i doing wrong? Also my list contains Employees and Managers which inherit from Account, the if statement uses the getName in Account to compare if it equals to the user input. Sorry if this is ridiculously stupid/bad! thanks.
List <Account> Accounts = new LinkedList<Account>();
Here is where i populate my Account, the main method calls this and the list() is called whihc contains the problematic loop
public void add() {
Employee Geoff = new Employee("Geoff", "password1");
Manager Bob = new Manager("Bob", "password2");
Employee John = new Employee("John", "password3");
Accounts.add(Geoff);
Accounts.add(Bob);
Accounts.add(John);
list();
}
problem:
System.out.println("Hello welcome: ");
System.out.println("Please enter your name: ");
String empName = Scan.nextLine();
for (Account a : Accounts) {
System.out.println(a);
if (a.getname().equals(empName)) {
System.out.println("\nPlease enter your passcode: ");
String code = Scan.nextLine();
if (a.check(code) == true) {
System.out.println("logged in");
}
}
System.out.println("Employee does not exist!");
login();
}
I am doing the print statement in the for loop to see what it is findng, and unfortunalty it is only the first account
EDIT: I have included more code here, my after my initial if statement i want to check if the code the user enters is also correct.

see if the name of an employee matches one in the list then the if
statement continues, further questions asked etc... it seems to only
iterate once and then stop as it will only find the first user and
tell me the other accounts do not exisit, even though they do!!
If it works for one employee and tells that others don't exist then your for loop does not iterate once.
The output you get is exactly what the code looks like. You get username once then try to match the same name with every employee in the list. If the names are equal you ask for password, otherwise you print out that employee doesn't exist. Everything right as it is in the code. You should add to your question the expected behaviour so I, or someone else can fix your code without guessing the purpose of your methods.
Here's one of those guesses:
System.out.println("Please enter your name: ");
String empName = Scan.nextLine();
boolean userFound = false;
for (Account a : Accounts) {
System.out.println(a);
if (a.getname().equals(empName)) {
System.out.println("\nPlease enter your passcode: ");
String code = Scan.nextLine();
if (a.check(code) == true) {
System.out.println("logged in");
userFound = true;
break;
}
}
}
if(userFound) {
login();
} else {
System.out.println("User not found.");
}

This is a possible solution that doesn't use your Account class (since I do not know what it looks like) and instead uses a Map:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Hello welcome: ");
System.out.println("Please enter your name: ");
String empName = input.nextLine();
boolean found = false;
Map<String, String> accounts = new HashMap<String, String>();
accounts.put("Geoff", "password1");
accounts.put("Bob", "password2");
accounts.put("John", "password3");
Set<String> names = accounts.keySet();
for (String a : names)
{
if (!a.equals(empName))
{
continue;
}
found = true;
// three tries to login
boolean success = false;
for(int i = 0; i < 3; i++)
{
System.out.println("Please enter your passcode: ");
String code = input.nextLine();
if (accounts.get(a).equals(code))
{
System.out.println("logged in");
success = true;
}
else
{
System.out.println("Wrong password... try again");
}
}
if(!success)
{
System.out.println("User failed to authenticate after 3 attempts. User has been locked out!");
}
}
if(!found)
{
System.out.println("Employee does not exist!");
}
}
Since I do not know what the login() method does, I just simply added that into the code. This solution iterates three times in an attempt to get the correct password. If that fails, a message is displayed.

Related

ArrayList in Class A and user trigger the output from Class B. How do I correctly get an output from an ArrayList?

I doing a bigger school project (first part of basic objective programming in java - so not touched extended, polyphorism etc yet, thats next part), but run in to a small problem and tried for couple of days to find solution (thru books and internet). I constructed different ArrayLists in one class and different classes (at least two) should get access to them.
public class Customer
{
public void subMenuCustomer()
{
............code............
int subMenuCust;
ServiceLogic addCustomer = new ServiceLogic();
ServiceLogic listAllCustomers = new ServiceLogic();
while(true)
{
System.out.println("Please Choose your preference: ");
System.out.println("Create account, press \"1\": ");
System.out.println("Get list of clustomers, press \"2\": ");
System.out.println("Log out, press \"0\": ";
subMenuCust = input.nextInt();
switch(subMenuCust)
{
case 1 ://Call method createCustomer in class ServiceTech to add new customers
addCustomer.createCustomer(name, lastname, ssNo);
break;
case 3
listAllCustomers.getCustomer();
............more code..............
}
}
When user has added details (social secuity number, name and lastname) it is stored in seperate ArrayList. These three ArrayList are added(merge/concat) together to a fourth ArayList, listCustomer , so that all elements from the three ArrayList end up in same index [101 -54 Clark Kent, 242-42 Linus Thorvalds, ...].
import java.util.ArrayList;
import java.util.Scanner;
public class ServiceLogic
{
//Create new ArrayLists of Strings
private ArrayList<String> listSSNoCustomers = new ArrayList<>();
private ArrayList<String> listNameCustomers = new ArrayList<>();
private ArrayList<String> listLastnameCustomers = new ArrayList<>();
private ArrayList<String> listCustomers;
Scanner input = new Scanner(System.in);
public boolean createCustomer(String name, String lastname, String ssNo) //
{
System.out.println("Write social security number; ");
ssNo = input.next();
//loop to check that it is a uniq social security number
for(String ssNumber : listSSNoCustomers)
{
if (ssNumber.equals(ssNo))
{
System.out.println("This customer already exist. Must be uniq social security number.");
return true;
}
}
//If social security number is not on list, add it
//and continue add first name and surname
listSSNoCustomers.add(ssNo);
System.out.println(ssNo);
System.out.println("Write firstname; ");
name = input.next();
listNameCustomers.add(name);
System.out.println(name);
System.out.println("Write lastnamame; ");
surname = input.next();
listSurnameCustomers.add(lastname);
System.out.println(lastname);
return false;
}
public void setListCustomer(ArrayList<String> listCustomers)
{
this.listCustomers = listCustomers;
}
public ArrayList<String> getCustomer()
{
//ArrayList<String> listCustomers = new ArrayList<>();
for(int i = 0; i <listSSNoCustomers.size(); i++)
{
listCustomers.add(listSSNoCustomers.get(i) + " " + listNameCustomers.get(i) + " " + listFirstnameCustomers.get(i));
}
System.out.println("customer" + listCustomers);
return listCustomers;
}
}
According to the specification we got, when user want to see list of all customer the outputs should be in format [666-66 Bruce Wayne, 242-42 Linus Thorvalds, ...].
When user (staff) choose to enter details in class Customer ( Case 1 ) it works and elements get stored in the Arraylists for social security numbers, name and lastname (have checked that) .
The problem: when I run I can add customers, but when I try to get a list of customer the output: [] . I tried different solution, but same output only empty between the brackets.
So the question, how do I get ouput to work when user choose case 2 to get a list of all cutomers?

Adding/set variable to Array from another method

Ok, so I'm more of a dunce than a beginner so bear with me.
What I'm trying to accomplished is to try to set/add variable within an array.
The question I am doing is to create a package and call another method called addAccommodation(); and use that method to add the required info and adding it to TravelPackage travelpackage.
I'm posting section of the issue here. The arraylist is called travelPackages and the one I want to add variables into is TravelPackage travelpackage.
(addAccommodation(); is the method soppose to lead another section, and travelpackage.setAccID is the issue I'm trying to solve)
public void addPackages() {
Scanner input = new Scanner(System.in);
System.out.println("Input Customer ID: ");
int customerID = input.nextInt();
input.nextLine();
System.out.print("Input Duration in Days: ");
int duration = input.nextInt();
input.nextLine();
System.out.print("Date in format yyyy-mm-dd? ");
String date = input.nextLine();
LocalDate startDate = null;
try{
startDate = LocalDate.parse(date);
}
catch(Exception e){}
TravelPackage travelpackage = new TravelPackage(customerID, duration, startDate);
travelPackages.add(travelpackage);
addAccommodation();
}
public void addAccommodation(){
Scanner input = new Scanner(System.in);
boolean match = false;
while(true) {
System.out.print("Input Accommodation Type(Hotel, Lodge, Ski Club, Apartment, Village): ");
String type = input.nextLine();
for (Accommodation a: accommodations) {
if (a.getType().equalsIgnoreCase(type) && a.getAvailability()) {
// Update accommodation status in ArrayList
a.setAvailability(false);
travelpackage.setAccID(a.getAccID());
// Set match flag to break loop
match = true;
// Stop searching for matching bike
break;
}
}
if(match){
System.out.println("Did not find a match.");
break;
}
}
}
It keep saying cannot find symbol. Is there something I'm missing here? (Sorry if I can't provide proper info, I am quite dumb)

Java - Storing Names in ArrayList and Using it to Login

I have a task to do which involves asking the user to input their last name and giving the user an account number to login to the program. I have listed the steps below which might make more sense.
1) User creates an account
2) User enters their last name (Stores into the arraylist)
3) User is given an account number (Stores into the arraylist)
4) User can then login using their last name and account number (checks arraylist for lastname and accountnumber, if it matches then login message, if it doesnt then error message)
A user enters their last name and they are given an account number which they then use to login to deposit, withdraw and check balance.
How do i create a programe to do this without the use of database?
Account Class
private static int number = 500;
Account(){
accountNumber = number++;
}
Create Account
public void createAccount(){
String firstName;
System.out.print("Please Enter Last Name: ");
lastName = scanner.nextLine();
System.out.println("This is your Account Number to log into: " + _______ );
}
public void logIn(){
System.out.println("Please enter your last name: ");
System.out.println("Please enter your account number: ");
}
I would like to suggest another method using xml to store credentials follow the steps below
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
string username;
string pwd;
string CurrentUser = "";
string CurrentPwd = "";
bool LoginStatus = false;
username = Login1.UserName;
pwd = Login1.Password;
XmlDocument xmxdoc = new XmlDocument();
xmxdoc.Load(Server.MapPath("Register.xml"));
XmlNodeList xmlnodelist = xmxdoc.GetElementsByTagName("user");
foreach (XmlNode xn in xmlnodelist)
{
XmlNodeList xmlnl = xn.ChildNodes;
foreach (XmlNode xmln in xmlnl)
{
if (xmln.Name == "Name")
{
if (xmln.InnerText == username)
{
CurrentUser = username;
}
}
if (xmln.Name == "Password")
{
if (xmln.InnerText == pwd)
{
CurrentPwd = pwd;
}
}
}
if ((CurrentUser != "") & (CurrentPwd != ""))
{
LoginStatus = true;
}
}
if (LoginStatus == true)
{
Session["UserAuthentication"] = username;
Session.Timeout = 1;
Response.Redirect("welcome.aspx");
}
else
{
Session["UserAuthentication"] = "";
}
}
in your xml file
<user>
<Name>smashcode</Name>
<Password>smashcode</Password>
</user>
I guess this would be better approach than a arraylist approach
if you want to try in using arraylist follow steps
step1:username_list{uesr1,user2,user3}
password_List{pass1,pass2,pass3}
step:check all entries with entered userid and password in a loop as follows
int flag = 0;
while(username_list.get(i)!=null)
{
if((username_list.get(i).equals(enteredusername))&&((password_list.get(i).equals(enteredpassword)))
{
flag = 1;
}
}
if(flag==1)
{
System.out.println("login successful ");
Response.Redirect("welcome.aspx");
}
I had written second code implementation in cut short
Hope my work will be helpful.Keep coding
Not a full answer here but a few suggestions....
You could create a "bank" class... It might hold the arraylist of accounts, also holding
createAccount()
delAccount()
findAccount()...
So on and so forth
Having posted this I now see it is an answer, my bad guys
I assume you need to be able to keep this information after the execution is complete, which means you need to store the information somewhere besides the running program.
Of the top of my head, you can use a file to store this store of information, where each line of the file would equal a match of last name - account. When opening the program, you read the file. Try reading:
http://www.tutorialspoint.com/java/java_files_io.htm or
https://docs.oracle.com/javase/tutorial/essential/io/file.html
The solution is similar to using a database, so I don't know if it will do or not. Hope it does.

Change specific data from an ArrayList

The exercise is, to create an arraylist for a class, where a User can enter "Guestnumber" + "Guestname" + "Guestemail".
In the menu you could remove an existing "Guest" with all the Information. Thats the code for it: (it works)
public void gastAendern() {
System.out.println("Guestnumber to delete:");
Scanner sc = new Scanner(System.in);
String input = sc.next();
for (Gast test : verwaltungG) {
int nummer = Integer.parseInt(input);
if (test.getgNr() == nummer) {
verwaltungG.remove(test);
a = 1;
break;
}
}
if(a==0) {
System.out.println("Guestnumber is not used");
verwaltungG is the ArrayList
Gast is the class for get+set
But now I got a problem to change an existing Guest, like for example:
I ask to type in the Guestnumber OR the Guestname OR the Guestmail to change it (I have to do it for all 3). So I have really no idea how to change it. I looked through Stackoverflow, google etc. but it only shows how to change them with List.set, but I don't know if it works with my kind of Problem, because I don't know how to use it.
You can do something similar as you are doing for delete, instead of remove - you need to change the details you need update :
System.out.println("Guestnumber to update :");
Scanner sc = new Scanner(System.in);
String input = sc.next();
for (Gast test : verwaltungG) {
int nummer = Integer.parseInt(input);
if (test.getgNr() == nummer) {
System.out.println("Enter new guest name for guest number : "+nummer );
String name = sc.nextLine();
System.out.println("Enter new guest email for guest number : "+nummer );
String email = sc.nextLine();
// now update the details
test.setName(name);
test.setEmail(email);
break;
}
}

Why won't this method call work?

I'm creating a method to take an input by a user and validate it to make sure it's correct. If it's correct it will call a method and input the user input in to it. But for some reason, the method call is not working. It doesn't produce any errors, it just simply doesn't do it. I placed a print statement at the end of the code to make sure it actually reaches there and it does, but for some reason it's just not calling the method like it's supposed to. The other method works fine if I call it by itself and input a string via the parameters.
The code is:
public void getGetScheduledShowByFilmInput()////new - omar////
{
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(System.in));
String filmInput;
filmInput = "";
boolean foundFilm;
foundFilm = false;
System.out.println("Here is a list of films that are currently showing:");
for(Film film : films){
System.out.println(film.getFilmName());
}
System.out.println("");
System.out.println("Please type the film name that you wish to view the corresponding shows for and press enter.");
System.out.println("Type 'exit' and press enter to exit this process.");
while(foundFilm == false){
try{
filmInput = reader.readLine();
}
catch (IOException e){
System.out.println("Error");
}
//If user enters "exit" then return.
if(filmInput.equals("exit")){
return;
}
//Check to see if the film name input by the user corresponds to any film showing.
for(Film film : films){
if(film.getFilmName() == filmInput){
foundFilm = true;
break;
}
}
if(foundFilm = true){
System.out.println("Film found.");
}
else{
System.out.println("The film name you entered has not been recognised. Please try again.");
}
}
//Call the function and input the film name input by the user.
getScheduledShowsByFilm(filmInput); ////This is the code that seems to be the problem.
System.out.println("reached bottom");
}
and the second method is:
public void getScheduledShowsByFilm(String inputFilmName)
{
ArrayList<Show> scheduledShows;
scheduledShows = new ArrayList<Show>();
for(Film film : films){
if(inputFilmName == film.getFilmName()){
for(Schedule schedule : schedules){
scheduledShows.add(schedule.getShowsOfFilm(film));
if(scheduledShows.get(scheduledShows.size() - 1) == null){
scheduledShows.remove(scheduledShows.size() - 1);
}
}
}
}
for(Show show : scheduledShows){
System.out.println("**********************************");
show.getShowDetails();
System.out.println("**********************************");
}
}
The second method works perfectly when I call it on its own and enter parameters manually though.
It's probably something extremely simple that I'm not understanding! haha, thank you for your help :)
foundFilm can never be false because you always assign true to it:
if(foundFilm = true){
System.out.println("Film found.");
}
try changing it to this:
if(foundFilm)
{
System.out.println("Film found.");
}
In getGetScheduledShowByFilmInput() and getScheduledShowsByFilm(String) avoid doing string comparison using the equality operator (==). The == operator tests for object equality, but you want to test whether two strings contain the same sequence of characters. Therefore, use equals instead:
//Check to see if the film name input by the user corresponds to any film showing.
for(Film film : films){
if(film.getFilmName().equals(filmInput)){
foundFilm = true;
break;
}
}
and
for(Film film : films){
if(inputFilmName.equals(film.getFilmName())){
for(Schedule schedule : schedules){
scheduledShows.add(schedule.getShowsOfFilm(film));
if(scheduledShows.get(scheduledShows.size() - 1) == null){
scheduledShows.remove(scheduledShows.size() - 1);
}
}
}
}

Categories

Resources