Change specific data from an ArrayList - java

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;
}
}

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)

Can't get my code to return an object from my ArrayList

I am trying to get it so that when a user enters, for example, the model of a guitar that it will return all the details for that specific model from my ArrayList. However, I get no errors when I run the program just no results. I have no clue what to do, any help would be greatly appreciated.
P.S. In my switch cases I kept trying multiple different ways to get results with no luck so please ignore if it is all over the place.
package guitarsrentalmanagementsystem;
import StockManagement.Guitar;
import java.util.ArrayList;
import java.util.Scanner;
public class GuitarsRentalManagementSystem {
public static void main(String[] args) {
// TODO code application logic here
ArrayList<Guitar> data = new ArrayList<>();
data.add(new Guitar(100, 150.99, "Gibson", "Les Paul",
"Acoustic", "INDIAN_ROSEWOOD", "MAHOGANY", 1995, 8.99, "Red",
true));
data.add(new Guitar(101, 180.00, "Fender", "Stratocaster",
"Electric", "BRAZILIAN_ROSEWOOD", "MAHOGANY", 2001, 10.99, "Brown",
true));
data.add(new Guitar(102, 110.50, "Martin", "Noisemaker",
"Acoustic", "INDIAN_ROSEWOOD", "BRAZILIAN_ROSEWOOD", 2005, 5.99, "Black",
true));
for(Guitar g : data){
g.printDetail();
}
//Show data from the adobe arraylist
System.out.println("Valid search parameters are as follows :");
System.out.println("1. Model, eg Les Paul");
System.out.println("2. Serial number, eg 101");
System.out.println("3. Year of manufacture, eg 2001");
Scanner input = new Scanner(System.in);
System.out.println("Please select how you would like to search");
int search = input.nextInt();
for(Guitar g : data){
switch(search){
case 1:
System.out.println("You have chosen to search by model");
System.out.println("Valid models are Les Paul, Stratocaster or Noisemaker");
System.out.println("Please enter a model to search");
Scanner inputO1 = new Scanner(System.in);
String modelSearch = input.next();
if("Les Paul".equals(modelSearch)){
g.printDetail();
}
break;
case 2:
System.out.println("You have chosen to search by Serial number");
System.out.println("valid serial numbers are between 100 and 105");
System.out.println("Please enter a serial number to search");
Scanner inputO2 = new Scanner(System.in);
int serialSearch = input.nextInt();
System.out.println(g.getSerialNumber());
break;
case 3:
System.out.println("You have chosen to search by year of manufacture");
System.out.println("Valid manufacture dates are 1995, 2001 and 2005");
System.out.println("Please enter a manufacture year to search");
Scanner input03 = new Scanner(System.in);
int yearSearch = input.nextInt();
System.out.println(g.getYearOfManufacture());
break;
}
break;
}
}
}
There's issue with the way you are reading input: when you use scanner object and call nextInt() on it. it reads just the number. similarly when you call next it reads just one string value, i.e.
if you have entered "Les Paul" as input, scanner object next() method will ready only Les, so it wouldn't match with your condition.
so once you read integer call nextLine() method, so the cursor moves to next line, now read input from the next line by calling again the nextLine() method
case 1:
System.out.println("You have chosen to search by model");
System.out.println("Valid models are Les Paul, Stratocaster or Noisemaker");
System.out.println("Please enter a model to search");
Scanner inputO1 = new Scanner(System.in);
input.nextLine();
String modelSearch = input.nextLine();
if ("Les Paul".equals(modelSearch)) {
g.printDetail();
}
break;
the above code will work if the user enters model as "Les Paul".

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.

Java for loop with if statement only iterating once

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.

Categories

Resources