I'm creating a banking system and can't seem to store the name of the customer names in an array. The last customer name is just overridden on the next customer. These are the lines concerning the array.
ArrayList<String> allnames1 = new ArrayList<String>();
System.out.println("Please enter account holders name:");
allnames1.add(sc.nextLine());
System.out.println("Account Created. Overview and Balance: " + "\n" + allnames1);
After this happens the user is taken back to the "Main Menu" in another class.
allnames1.add ("a")
allnames1.add ("b") is enough.
If it doesn't work; I think its because allnames1 is newly created every time.. or sc.nextline is wrong.
Related
I'm trying to prevent user to add 2 attendee with the same passport I tried many things as making Boolean variable to check if attendee was added before or no but I have failed all of my attempts can't really think of a way to make this
public class Test {
public static void main(String[] args) {
try {
Workshop Available_Work_Shops = new Workshop();
Scanner sc = new Scanner(System.in);
String passportNumber, workshop;
boolean isAttendeeMatch;
ArrayList<Attendee> attendeeList = new ArrayList<>();
int choice;
do {
System.out.println("1. Add New Attendee");
System.out.println("2. Add Existing Attendee to Workshop");
System.out.println("3. Remove Attendee from Workshop");
System.out.println("4. Print WorkShop List");
System.out.println("5. Print All Attendees");
System.out.println("0. Close Program");
System.out.println("Please Enter a number to choose");
choice = sc.nextInt();
sc.nextLine();
switch (choice) {
case 1 -> {
System.out.println();
System.out.println("Adding New Attendee");
System.out.println("____________________");
System.out.print("Please Enter Attendee Name: ");
String Attendee_name = sc.nextLine();
System.out.print("Please Enter Attendee Passport Number: ");
String Attendee_passport = sc.nextLine();
System.out.print("Please Enter Attendee Age: ");
String Attendee_Age = sc.nextLine();
System.out.print("Please Enter Attendee Phone Number: ");
String phone = sc.nextLine();
attendeeList.add(new Attendee(Attendee_name, Attendee_Age, Attendee_passport, phone));
for (Attendee attendee : attendeeList) {
if (attendeeList.contains(attendee.PassportNumber)) {
System.out.println("Existing User Found please enter '3' to remove the duplicate user");
}
}
}
The Issue
Let's focus on these two lines
...
for (Attendee attendee : attendeeList) {
if (attendeeList.contains(attendee.PassportNumber)) {
...
Since you've defined the attendeeList to be an ArrayList holding Attendee objects, you should be passing Attendee objects to attendeeList.contains(). While the contains() function does accept any Object, it will only return true if one of the List's elements .equals() the object you pass in.
The Solution
I'd recommend changing this block of code...
attendeeList.add(new Attendee(Attendee_name, Attendee_Age, Attendee_passport, phone));
for (Attendee attendee : attendeeList) {
if (attendeeList.contains(attendee.PassportNumber)) {
System.out.println("Existing User Found please enter '3' to remove the duplicate user");
}
}
... to something like this
Attendee potentialAttendee = new Attendee(Attendee_name, Attendee_Age, Attendee_passport, phone)
// Check if the potentialAttendee's passport number is already used by someone in the list.
boolean passportRegistered = false;
for (Attendee attendee : attendeeList) {
if (attendee.PassportNumber.equals(potentialAttendee.PassportNumber) {
System.out.println("That user passport number has already been registered. It can't be added again.");
passportRegistered = true;
}
}
// Only add the potentialAttendee if his/her passport number wasn't already used by someone in the list.
if (!passportRegistered) {
attendeeList.add(potentialAttendee);
}
The key difference is that you shouldn't add the potentialAttendee to the list until you've first validated that he/she meets the requirements to be added to that list.
Potential Enhancements
Store the Attendees in a HashMap instead of an ArrayList. If you key off of the PassportNumber, then by definition you can't have two participants with the same PassportNumber in the collection of attendees.
Java has a nice Streaming API that could make the validation even closer to a one liner.
Right off the bat, I see a few issues that would break the code:
You're adding the attendee to the list and then checking if it exists in the list afterwards (which it always will after adding it if checking correctly).
if (attendeeList.contains(attendee.PassportNumber)) will never return true because you're checking if the entire List has an object that is equal to the PassportNumber in it (as opposed to the PassportNumber in the object). It should be if(attendee.getPassportNumber().equals(Attendee_passport)).
Not sure how much of a beginner you are but it might also be useful to look into things like naming conventions (in general Java variables should be named with a lowercase first letter and each new word has an uppercase letter), using List<Attendee> as the declared variable type instead of ArrayList, and things like filtering lists using Java Streams to see if something exists already. Java also has Set as an alternative to List for when you only want to store unique values (there's other differences between List and Set so make sure you look into it if you want to use it).
This question already has answers here:
Local variables of same name in same scope, IDE display error but when I run the program, no run time error results
(3 answers)
Closed 4 years ago.
I just wanted to say that I am new at java and I have been practicing and getting a LITTLE better. I'm trying to make a very simple banking system where you have the options to create an account, deposit and withdraw money. I'm a bit stuck at this current time though and hoping someone could help me out.
I'm trying to take input from the user and then create a new object instance with the user input in the parameters and it's giving me and error. Here is the code line it's giving me the error on, thank you!
It's prompting me with the error on the: bankAccount object creation line for the userName String variable.
case 1:
System.out.println("Please Enter Your Name: ");
String userName = input.nextLine();
System.out.println("Please Enter a 4 digit pin number: ");
int pinNumber = input.nextInt();
int accountNumber = rand.nextInt(5100 - 1100) + 1000;
System.out.println("Account Created with the following credentials:\n " +
"Name: " + userName + "\n" +
"Account Number: " + accountNumber + "\n" +
"Pin Number: " + pinNumber);
bankAccount userName = new bankAccount(userName, accountNumber);
break;
With java, you cannot make a local variable with the same name, even though the data types are different.
userName is already used as a String variable so you cannot make a new bankAccount named userName. You could name it userAccount though.
Example:
bankAccount userAccount = new bankAccount(userName, accountNumber);
You could then add this to an array or Map to reference that particular userAccount later.
bankAccount[] accounts = new bankAccount[];
//several lines of code
bankAccount[0] = userAccount;
or
Map<String, bankAccount> bankAccount accounts = new HashMap<String, bankAcount>();
//several lines of code
bankAccount.put(userAccount.userName, userAccount);
To retrieve the userAccount of a certain user, you can do this later in the program.
bankAccount userAccount = bankAccount.get("bob");
This is get the bankAccount that has "bob" as the userName.
I imagine you're doing this as an independent project. If you have the time, it could be a good idea to learn some java from codecademy to get a better understanding of the basics.
You have created the variable userName twice in line number 2 and 10. in java you cannot create the same variable name even though they have two types.
I wrote code to store the values of user-inputted dollar amounts. Whenever the program prompts the user, "would you like to input items - y/n?" the user can then put in values stored in an ArrayList.
The initial prompt is below. It seems to work as I am able to put in values with no visible errors.
System.out.print("Would you like to input item/s - y/n: ");
String response = textReader.nextLine();
System.out.println();
// create while loop to restrict responses to single characters
while ((!response.equalsIgnoreCase("y")) && (!response.equalsIgnoreCase("n")))
{
System.out.print("Sorry - we need a y/n: ");
response = textReader.nextLine();
System.out.println();
}
But when I go to put in values a second time, I notice the program doesn't clear out the values from my first entry. The code I wrote to prompt the user for another cluster of values is identical to the code I wrote for the initial prompt. I nested these second prompt in a while loop triggered by the user selecting "y" to the initial prompt.
while ((response.equalsIgnoreCase("y")))
{
System.out.print("Please enter an item price, or -1 to exit: $");
double values = numberReader.nextDouble();
while ((values > (-1)))
{
cartItems.add(values);
System.out.print("Please enter another item price, or -1 to exit: $");
values = numberReader.nextDouble();
}
System.out.println();
System.out.println("********** Here are your items **********");
// I omitted the code here to make this more concise.
// prompt the user to input a second round of values
System.out.print("Would you like to input item/s - y/n: ");
response = textReader.nextLine();
System.out.println();
// create while loop to restrict responses to single characters
while ((!response.equalsIgnoreCase("y")) && (!response.equalsIgnoreCase("n")))
{
System.out.print("Sorry - we need a y/n: ");
response = textReader.nextLine();
System.out.println();
}
}
My output is below. When I am prompted a second time, I select 'y' to add more items. However, my newly added item $3.00, gets added to the list from the first prompt. Is there anyway to refresh or erase the ArrayList so that it is brand new each time the user wants to input new values?
cartItems.clear();
put it at the end of the loop, after the results are printed to the console.
It will refresh the list and remove all the elements within it.
In no place you are resetting the ArrayList.
You can call cartItems.clear() when you are done with your processing and you are looping for a next round (at the bottom of the outter while).
...
while ((!response.equalsIgnoreCase("y")) && (!response.equalsIgnoreCase("n")))
{
System.out.print("Sorry - we need a y/n: ");
response = textReader.nextLine();
System.out.println();
}
cartItems.clear();
}
Create instance of list in the while loop
List<Double> cartList = new ArrayList<Double>();
So now everytime user selects yes, the program enters in the while loop and then a new instance of list is created without any values. If you want to store the values in the previous list, write it to a persistence storage like file or database before creating a new instance of list.
Alternatively, you can also use
cartList.clear();
But, i don't recommend doing so.It can give you junk values and takes more amount of time. The clear method basically iterates over all the elements of list and does them null like this.
for(int i = 0; i < cartList.size(); i++){
cartList.get(i) = null;
}
User input from scanner method to array of 5 indexes also gives user ability to delete any index matching with string from one of the index.
ALL I want to achieve in this is in this while loop I would like to settle city (option 1), which means creating one as you can probably see from my code. This is where user will type any name they like no restrictions. once they settle the city loops starts again. However it does remember that user created a city earlier. I can have upto 5 cities. There is cost associate with settling new city. I know how to do those conditionals. I am just not sure about this string array.
ArrayList or Array class is not allowed.
where as, option 2 I can demolish any of the city i have created by giving user lists of city they have made earlier. I have to keep minimum of at least one city.
IF you are wondering then this is based on Civilization game.
Please ask for clarification as this may not be
straight forward. thanks
while (playing) {
System.out.println("\nPlease make your selection!");
System.out.println("\n1. Settle a City"
+ "\n2. Demolish a City"
+ "\n3. Build Militia"
+ "\n4. Research Technology"
+ "\n5. Attack Enemy City"
+ "\n6. End Turn\n");
String gameChoice = userinput.nextLine();
if (gameChoice.equals("1")) {
System.out.println("\nWhat would you like to"
+ " name your city?");
String cityname = userinput.nextLine();
cityname = cityNames[0];
} else if (gameChoice.equals("2")) {
System.out.println("What city would you like to demolish?");
for (int i = 0; i < 5 ; i++) {
System.out.print(cityNames[i]);
System.out.print("");
}
} else if (gameChoice.equals("3")) {
System.out.println("You have military points");
} else if (gameChoice.equals("4")) {
System.out.println("You have Research Technology points");
} else if (gameChoice.equals("5")) {
System.out.println("You have zero points");
} else {
System.out.println(" Thanks for playing ");
}
playing = false;
}
First, here:
String cityname = userinput.nextLine();
cityname = cityNames[0];
You are assigning cityname to user input and then you are assigning it to something in cityNames array, that doesn't make sense, maybe you pasted wrong or something, but just in case, this should be the other way around, like this:
cityNames[0] = cityname;
You have playing = false at the end so the loop is gonna just end when user types the city name, you need to either remove this playing = false or use continue; after cityNames[0] = cityName;, that's gonna go to the next iteration of a loop, without going all the way down to playing = false.
import java.util.*;
public class PersonList{
public static void arraylist() {
// create an array list
ArrayList Employee = new ArrayList();
// add elements to the array list
Scanner input = new Scanner (System.in);
System.out.println("Name: ");
Employee.add(input.next());
System.out.println("Year of birth: ");
Employee.add(input.next());
System.out.println("");
Employee.add(input.next());
System.out.println("");
Employee.add(input.next());
System.out.println("");
Employee.add(input.next());
System.out.println("Contents of al: " + Employee);
}
}
I have an arraylist that takes user entered data and I need to store data that has a space into one block.
I haven't added the other things that I will include. I want to be able to put a name such as "John Smith" into the Name, instead of it printing John, Smith in two separate blocks. I am very new to programming and I apologize if it is sloppy and/or annoying.
Replace input.next() with input.nextLine(). The former will usually split your input based on whitespaces, whereas the latter will give you the whole line.
On a side note, there is a naming convention for variables, which requires them to start with a lowercase letter. Moreover, it is discouraged to use raw types for lists and it is prudent to always explicitly specify the type. You can change the whole arraylist creation line to something like ArrayList<String> employees = new ArrayList<>();.