I was wondering if its possible to store an object into a arraylist where the user wants it. For my program its storing the users data into a cell of their choice via an "account number" but every time I type in a new account number it says that the array isn't big enough basically. Here is my code. If anyone could help that would be appreciated.
ArrayList <Account> account = new ArrayList<Account>();
int accountNumber;
String nCity;
String nState;
String nZipCode;
String nLastName;
String nAddress;
String firstName;
String nAccount;
public void newAccount()
{
Account a = new Account();
a.firstName = JOptionPane.showInputDialog("What's your first name?");
a.nLastName = JOptionPane.showInputDialog("What's your last name?");
a.nAddress = JOptionPane.showInputDialog("What's your current address?");
a.nCity= JOptionPane.showInputDialog("What's your current city?");
a.nState = JOptionPane.showInputDialog("What's your current State?");
a.nZipCode = JOptionPane.showInputDialog("What's your current Zip Code?");
String num = JOptionPane.showInputDialog("What do you want your account number to be?");
accountNumber = Integer.parseInt(num);
account.add(accountNumber, a);
Use a HashMap and use the account number as the key
Map<Integer,Account> account =new Hashmap<Integer,Account>();
account.put(accountNumber,a);
You have created an ArrayList<Account> and you are adding elements into it in the form of key-value pair.
If you want to add that way, you probably need a HashMap: -
Map<Integer, Account> accounts = new HashMap<Integer, Account>();
then, to add entry in it, you can use Map#put() method: -
accounts.put(accountNumber, a);
Agree with the above suggestions about using Map.
Your "array isn't big enough" is simply because you are trying to specify the index of the List while you haven't initialize the indexes yet.
Simply, you are using this method of List:
add(int index, E element)
Inserts the specified element at the specified position in this list.
The keyword is INSERT.
So, imagine if your "accountNumber" is 100, and you don't have the 99 elements before it, trying to insert will make no sense in logic because you are inserting into nowhere.
JavaSE6 API says under this method:
IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())
By the way, another solution, if available to you, besides using Map is to have accountNumber as another field of Account, and you can use List now with the single-argument add() method.
Related
I'm trying to create a program that keeps track of a bunch of different Strings, and "ties them together" with the current user's entered name (another String), meaning every person should have their own wallets. I tried to do this using a Map inside another Map, but this is where my brain overloads. How do I tie every wallet to the correct name and then display all of that? The comment in my code gives a good example of it. Here is what I have so far:
Scanner sysin = new Scanner(System.in);
boolean firstTime = true;
Map<String, Set<Long>> walletTracker = new HashMap<String, Set<Long>>();
Map<String, Map<String, Set<Long>>> nameTracker = new HashMap<String, Map<String, Set<Long>>>();
if(!firstTime) {
/* Here it should display every entered name, wallet and time of deposit, like this:
Jack:
JacksWallet:
[12345], [123456], [1234567]
JacksOtherWallet:
[123], [1234]
Jonathan:
JonsWallet:
[12345678]
*/
}
for(int i = 0; i < 1;) {
System.out.print("Enter your name: ");
String name = sysin.nextLine();
System.out.print("Please enter a wallet name: ");
String wallet = sysin.nextLine();
Set<Long> deposits = walletTracker.getOrDefault(name, new HashSet<>());
deposits.add(System.currentTimeMillis());
walletTracker.put(wallet, deposits);
nameTracker.put(name, walletTracker);
System.out.println("You successfully withdrew money from "+ wallet +". Press enter to continue...");
firstTime = false;
String enter = sysin.nextLine();
}
Here's what I found & noticed:
The if(!firstTime) {} block should be within the for loop, so that it actually prints on every iteration.
You attempt to use walletTracker.getOrDefault(name, new HashSet<>());, but the name variable is not the correct variable to use here. You should be using the wallet input variable.
Here is my "print it out" code, that matches your recommended formatting:
nameTracker.forEach((name, wallet) -> {
System.out.println(name);
wallet.forEach((walletName, dates) -> {
System.out.printf("\t%s\n\t\t%s\n",
walletName, Arrays.toString(dates.toArray(new Long[0])));
});
});
Outside of this, the code you used to actually populate the map(s) is correct.
#rzwitserloot Made some good points about using OOP to your advantage, and I would recommend those suggestions as well.
Set<Long> deposits = walletTracker.getOrDefault(name, new HashSet<>());
This returns new HashSet<>() if there is no mapping for name but it does not add that to the map. What you want is .computeIfAbsent, which will just return the mapping that goes with name, but if it is not there at all, it evaluates your lambda and then adds that to the map and then returns that:
Set<Long> deposits = walletTracker.computeIfAbsent(name, k -> new HashSet<>());
That's 'lambda' syntax - you don't write an expression that resolves to a new hashset, you write an expression that resolves to a function that produces a new hashset when provided with the key (which we don't need here, and is equal to name anyway).
Java-esque strategy here is to make a Wallet class at least. In general, once you start putting <> inside `<>, especially if you're 3 levels deep, stop, and start writing classes instead.
That should be a Map<String, Wallet> and a Map<String, Person> or whatnot.
Right now I'm creating a bankApp and I don't have an idea how can I assign e.g. string name; double balance; etc. to a right one int PIN;. There is gonna be many accounts with different PINs and different values assigned to it . I tried making many objects :
perInfo card1 = new perInfo();
card1.PIN = 1994;
card1.balance = 24.68;
card1.isValid = true;
perInfo karta2 = new perInfo();
card2.PIN = 2002;
card2.balance = 522.2;
card2.isValid = false;
but I think it's too much work to do and it'll worsen performance of the app. I also tried making a list
public bApp(int pin, double balance){
this.pin = pin;
this.balance = balance;}
List<bApp> pass = new ArrayList<>();
pass.add(new bApp(1994, 568.45));
pass.add(new bApp(2002, 13866.24));
but it didn't work ,because I couldn't call the PIN to check that if user has provided the right one PIN . Arrays are also not suited for this.
You could use a HashMap for this and use the pin as a key and store the object in the HashMap. This would allow you to access each card using only the pin. However, this would not allow for duplicate pins. I would recommend that you reference each account by a unique ID and check the pin within the object itself.
HashMap<Integer, Account> accounts = new HashMap<Integer, Account>();
accounts.put(12345678, new Account(1994, 568.4));
You can then get the account using the unique ID and check if the pin is correct.
Account acc = accounts.get(uniqueID);
if(acc.pin == enteredPin){
//Whatever you need to do
}
The data structure you are looking for is a Map. Take a look at HashMap and you'll want to key off of whatever value you are using to lookup.
For example if you wanted to lookup a user by pin:
Map<Integer, bApp> passes = new HashMap<>();
passes.put(1994, new bApp(1994, 568.45));
passes.put(2002, new bApp(2002, 13866.24));
I think it would be simpler to just have an array of the different cards, with each pin being set to the array address:
bApp[] cards = new bApp[NUMBER_OF_CARDS];
cards[0] = new bApp(0, 568.45);
// ...
cards[2002] = new bApp(2002, 13866.24);
I'm writing a program that can grade multiple choice exercises for a class.
I wanted to store each answer key as a String array, and then have the user enter a String (the name of the exercise) which would be able to summon the stored String array. From there I know how to compare the stored String to the user's inputs.
I just have no idea how to take the input String and use it to summon the stored String array. Any tips?
thanks!
Using individual arrays to store each answer is grossly inefficient. What you need is an object that can store values which can be referenced by a key and a Hashmap provides just that. Study the illustration below:
//Declare your hashmap:
Map <String, String> myAnswers = new HashMap<>();
/*
*Put the values you want
*The put method takes in two parameters, the key and the value.
*The key represents the name you want to call this element by.
*The value is the actual value (so to speak)
*/
myAnswers.put("firstQuestion", "Answer of firstQuestion");
myAnswers.put("secondQuestion", "Answer of secondQuestion");
myAnswers.put("thirdQuestion", "Answer of thirdQuestion");
//You can go on and on: key, value.. Just like we did up there.
If you need the value of any of these keys, just do something like this:
myAnswers.get(firstQuestion);
I hope this helps.. Merry coding!
There are many ways to do this, it kind of all depends on your code design, but in general you can retrieve specific positions of any String[] by using a simple for loop (assuming this is a long test quiz):
class Grades {
Grades grades = new Grades();
String [] test1 = {"A", "B", "A", "C"};
for (int i = o; i < test1.length; i++) {
//this will retrieve every grade at every array position in order for 0 to
however long the array is.
grades.get[i]
}
}
I'm sorry if this is a very obvious question, I guess I simply don't know the proper vocabulary to use to find the answer. My question is: Say I instantiate several objects, and each object has a unique integer that serves as its ID, and I want the user to be able to choose which object to modify by entering the object's ID. How should I go about that?
int ID;
Scanner keyboard = new Scanner(System.in);
Object obj1 = new Object(9897);
Object obj2 = new Object(2817);
System.out.println("Input the ID of the object you wish to modify:");
ID = keyboard.nextInt();
Assume I have a class written so that the objects instantiated in the previous code have their IDs equal to the argument passed to the constructors. Now say in the next line of code I want to change either object 1 or object 2 depending on whether the user inputs 9897 or 2817. How would I go about doing that without using a ton of if statements?
Short answer: you don't. Change your approach, put your instances in a Map<Integer, Object> and then you can look them up by ID.
Map<Integer, Object> map = new HashMap<>();
map.put(9897, new Object());
map.put(2817, new Object());
// ...
int ID = keyboard.nextInt();
Object obj = map.get(ID);
I am having an option in my website for the user i.e: "Settings" in that I given 3 options(TextBoxes) to enter details: 1.E-mail, 2.SMS, 3.MMS.. in this user can enter another mail id: its an optional thing but, if he enter the both or same which is neccesary e-mail and optional or same then, I have to tell that "given e-mail" alredy exist.
I am sending this data as ArrayList that to coverted as JSON object.
What is the best way to find the duplicate and notify that to user
Help me in this
Thanks in advance
Either parse it into Java collections with a JSON framework of your choice, then check for duplicates or use JavaScript to directly work on the JSON.
If you have the ArrayList anyway, why don't iterate over that?
Please do the following
HashSet hashSet = new HashSet(arrayList1);
ArrayList arrayList2 = new ArrayList(hashSet) ;
if(arrayList2.size()<arrayList1.size()){
//duplicates exits
}
You can do what Ammu posted, but this will not identify the duplicate entry. If you have the ArrayList as a Java object (if not, convert it into one), convert the ArrayList into a HashSet, compare the size to identify if there are duplicate entries. If so, you need to sort the ArrayList in order to find the duplicate entry.
Collections.sort(arrayList);
for(int i = 1; i < arrayList.size() - 1; i++){
if (arrayList.get(i).equals(arrayList.get(i - 1))){
// found duplicate
System.out.println("Duplicate!");
}
}
this works only if the entries of the ArrayList implement the sortable interface. But since your ArrayList is filled with strings this is the case.
Based on what you described
"... in this user can enter another
mail id: its an optional thing but, if
he enter the both or same which is
neccesary e-mail and optional or same
then, I have to tell that "given
e-mail" alredy exist."
I would alert the user using Javascript and avoid the HTTP Request/Response round-trip to the server:
...
// before submitting the form
if (document.getElementById('requiredEmail').value == document.getElementById('optionalEmail').value) {
alert("The optional email must be different than the required email");
}
...
As suggested before by other user, you can just create a Set based on the ArrayList if you are validating the input in the backend...
String[] parsedInput = new String[] { "SMS-Value", "MMS-Value", "email#domain.com", "email#domain.com" }
List<String> receivedList = Arrays.asList(parsedInput);
Set<String> validatedList = new HashSet<String>(receivedList);
if (validatedList.size() < receivedList.size()) {
throw new IllegalArgumentException("The email addresses provided are incorrect.");
}
If you want to find the duplicates then you can iterate over the list and find.
like:
Map<Object, Integer> map = new HashMap<Object, Integer>();
for(Object obj : list)
{
if(map.containsKey(obj))
{
map.put(obj, map.get(obj)+1);
}
else
{
map.put(obj, 1);
}
}
Objects in the map having value more than 1 are duplicate.
If you just want to get rid of duplicates (rather than knowing which are actually duplicates)
Ex:
Set set = new HashSet(list);
set can not have duplicate elements, so it will remove all duplicates.