Unique User Input Array List - java

I have a class as defined below:
public class CarHireSystem{
private static final Car[] carList = new Car[100];
private static int carCount = 0;
In this class, I have a menu where the user can add new Car. When they select this option they will be prompted with the following:
System.out.print("Enter car ID: ");
String carID = sc.nextLine();
System.out.print("Enter car description: ");
String cardescription = sc.nextLine();
System.out.print("Enter hire fee: $");
Double hireFee = sc.nextDouble();
sc.nextLine();
carList[carCount] = new Car(carID,carDescription,hireFee);
carCount++;
I would like a way to validate that the car ID entered into the array has not already been entered by the user and print an error message if it has been entered and go back to the main menu. How do I do this without using Hashmap.
Thanks

Check if it is already in the list or not, If not add it.
List<AdventureRide> list = new List();
AdventureRide ride = new AdventureRide(ID,description,admissionFee);
if(!list.contains(ride))
list.add(ride);
If you want to make it with the ID references, you can use a HashMap.
HashMap<Integer, AdventureRide> = new HashMap();
AdventureRide ride = new AdventureRide(ID,description,admissionFee);
if(!hm.containsKey(ID))
hm.put(ID,ride);

You have 2 options:
Go through the array each time you want to enter something and check that the current ID is not present within the array.
Have your AdventureRide override the equals and hashCode methods such that two elements are the same if they have the same ID. Once you have that, replace the array with Set<AdventureRide>. This will make sure you have entries with a unique ID.
I'd recommend you go for option 2, reason being that:
If down the line you need to check some other field, you would just need to change your equals and hashCode methods.
Since the Set is a dynamic data structure, you can add/remove from it without knowing the amount of entries before hand.

You could also use a Set<String> to store the ID, and call contains() or get() with a null check. Or store the AdventureRide instances in a Map<String,AdventureRide>. For example:
Map<String,AdventureRide> adventureMap = new HashMap<String,AdventureRide>();
...
private static final void addNewAdventure()
{
boolean idExists = false;
System.out.print("Enter ID: ");
String id;
do {
id = sc.nextLine();
if(null != adventureMap.get(id)) {
idExists = true;
System.out.println("The ID you entered already exists.\n Please enter a new ID: ");
}
} while(idExists);
System.out.print("Enter story: ");
String description = sc.nextLine();
System.out.print("Enter fee: $");
Double admissionFee = sc.nextDouble();
sc.nextLine();
adventureMap.put(id, new AdventureRide(id,description,admissionFee));
//keep track of objects in array
adventureCount++;
}

boolean exists = false;
for (AdventureRide ar : adventureList) {
if (ar != null && ar.getID().equals(ID)) {
exists = true;
break;
}
}
if (!exists) {
adventureList[adventureCount++] = new AdventureRide(ID, description, admissionFee);
}
Iterate over the array; if an element with the same ID exists, break the for loop and set the exists flag. Then at the end, check if the exists flag has been set. If not, then add the new element into the array.

You can auto generate a unique ID instead of letting user input it. This way, you don't even have to check the duplicated ID.
In your codes, instead of doing this:
adventureList[adventureCount] = new AdventureRide(ID,description,admissionFee);
Change it to:
adventureList[adventureCount] = new AdventureRide(description,admissionFee);
Then in your AdventureRide class:
class AdventureRide
{
private static int count = 0;
private String id;
public AdventureRide(String desc, double adminFee){
autoGenerateID(); //Auto generate formatted ID
}
private void autoGenerateID(){
DecimalFormat fmt = new DecimalFormat("T-00000");
id = fmt.format(count++);
}
}
DecimalFormat to format your ID to specific format. This is of course optional.
Output:
T-00000
T-00001
T-00002
T-00003

Related

How to do linearSearch to two ArrayList<String>?

I received a homework assignment to create a shopping list program where it will ask the user for a list of ingredients, and after the user enters them, it will compare the inputs to a "pantry list" to see if everything is available. If yes, then it will print out "You got everything you need!" and if no, it will print out "You still need" + "item that is missing." The specific instructions are:
A pre-created list for pantry items
User input into an ingredient list
Pass the ingredient list to a method
Use a conditional and loop in the method
Print out the results of whether the user needs to go shopping based on the items in the ingredient list that are not in the pantry.
Below is my code:
import java.util.Scanner;
import java.util.ArrayList;
public class TheList
{
public static String linearSearch(ArrayList<String> pantry, ArrayList<String> input)
{
for (int i = 0; i < pantry.size(); i++)
{
if (pantry == input)
{
return "You got everything you need!";
}
}
return "You still need something!";
}
public static void main(String[] args)
{
// Create list for pantry items
ArrayList<String> pantry = new ArrayList<String>();
pantry.add("Bread");
pantry.add("Peanut Butter");
pantry.add("Chips");
pantry.add("Jelly");
//Create list for input items
ArrayList<String> input = new ArrayList<String>();
input.add("ingredientOne");
input.add("ingredientTwo");
input.add("ingredientThree");
input.add("ingredientFour");
// Execution
input();
System.out.println(linearSearch(pantry, input));
}
private static void input()
{
Scanner ingredientScan = new Scanner(System.in);
System.out.println("Please enter an ingredient: ");
String ingredientOne = ingredientScan.nextLine();
System.out.println(ingredientOne + " Done.");
System.out.println("Please enter an ingredient: ");
String ingredientTwo = ingredientScan.nextLine();
System.out.println(ingredientTwo + " Done.");
System.out.println("Please enter an ingredient: ");
String ingredientThree = ingredientScan.nextLine();
System.out.println(ingredientThree + " Done.");
System.out.println("Please enter an ingredient: ");
String ingredientFour = ingredientScan.nextLine();
System.out.println(ingredientFour + " Done.");
}
}
What am I missing? This is pretty amateur, but I am a beginner and really need some help!
My main question is the if part for the loop in the linearSearch string. When I execute the program, it always print out "You still need something!" As for which thing is missing, I have no clue where to start in that aspect.
I am assuming by linear search you mean searching if the pantry has everything in one pass.
For scenarios such as these using a Set is the best option because in a set you can search for a key in constant time.
private void search(Set<String> pantry,Set<String> ingredients){
for(String ingredient : ingredients){
if(!pantry.contains(ingredient)){
System.out.println("Something is missing");
return;
}
}
System.out.println("Everything is available");
return;
}
//Create a set like this
public void main(){
Set<String> pantry = new HashSet<>();
}
The answer is not hard, and since it's an assignment, maybe you need some adviceļ¼š
The loop in the code is not utilized.
Also objects can't be compared using ==, it can only be compared using equals and in general you need to rewrite it.
Your problem is not that you need to use equals to compare, but that you need to do difference sets

How do I search for null in this ArrayList and then replace it with another Object?

I have been writing code of a car parking structure for a bit now and i've gotten kinda stuck. So far I have an ArrayList that the user adds Vehicle properties to aswell as an ArrayList for a parking space with a "SpaceID" and the "Vehicle" from earlier.
So far I can make it so that the user adds the vehicle, and the vehicle gets added to a parking space, However I have made a temporary parking space with the index 0: and the element (vehicle) being null.
From here, I wanted to check the parking space ArrayList for "null" and then if it's found, replace null with the vehicle, However, I do not know how to go about implementing this. I will attach the current code i'm using, or at least a minimal version of it.
I have already tried using a Contains(null) method, but I can't seem to get that to work properly, I'm not sure if it even can work, but I have since then removed it from my code.
First of all, I have the function to create the vehicle and store it in an Array.
```
public void carInfo(Vehicle tempVehicle, parkingSpace vehicle) {
array = new MCP();
System.out.println("Please enter number plate: ");
input = new Scanner(System.in);
String plate = input.nextLine();
System.out.println("Please enter car make: ");
input = new Scanner(System.in);
String make = input.nextLine();
System.out.println("How would you best describe your Vehicle? ");
System.out.println("(Car, Small Van, Tall Van, Long Van, Coach,
Motorbike)");
type = new Scanner(System.in);
String type1 = input.nextLine();
if (type1.equalsIgnoreCase(vehicleType.CAR.toString())) {
tempVehicle.setPlate(plate);
tempVehicle.setCarMake(make);
tempVehicle.setVehicle(vehicleType.CAR);
inv.createInvoice();
tempVehicle.setInvoiceNumber(inv.invoiceNumber);
array.addStandard(tempVehicle);
array.parkVehicle(vehicle);
System.out.println(tempVehicle.toString());
System.out.println(vehicle.toString());
```
I also have my Arrays, which are on another class.
```
public MCP(){
vehicles = new ArrayList<>();
parkingSpaces = new ArrayList<>();
parkingSpaces.add(0, null);
parkingSpaces.add(1, null);
}
public void addStandard(Vehicle tempVehicle) {
vehicles.add(tempVehicle);
}
public void parkVehicle(parkingSpace vehicle) {
parkingSpaces.add(vehicle);
}
```
This is the way I tried to do it, but I couldn't figure this way out, so I stopped, i'm open to any other ways too.
// public void checkIfEmpty(parkingSpace vehicle){
// if(parkingSpaces.contains(null)){
// parkingSpaces.add(vehicle);
// }
// else{
// System.out.println("There is no room in this Zone");
// }
// }
I am also looking for a better way to populate parking spaces, but that's not the main concern, just something else just incase someone has any ideas
Thanks in Advance.
Since you are using an array list, when an item is deleted from it, there will be no empty element between two elements in it. When you delete an element, the elements shift. So in the case of this code, it checks if the number of elements in the array list is smaller than maximum number of cars
int maxSize = 10; //suppose that the maximum number of cars is 10
public void checkIfEmpty(parkingSpace vehicle){
if(parkingSpaces.size() < maxSize){
parkingSpaces.add(vehicle);
}
else{
System.out.println("There is no room in this Zone");
}
}
Try doing something like this:
public void checkIfEmpty(parkingSpace vehicle) {
boolean addedVehicle = false;
for (int i = 0; i < parkingSpaces.size(); i++){
if (parkingSpaces.get(i) == null) {
parkingSpaces.add(vehicle);
addedVehicle = true;
break;
}
}
if (!addedVehicle)
System.out.println("There is no room in this Zone");
}

How to set the name of an instance of something to the value of an integer?

I already tried this:
public static void accountTypeSavings() {
boolean b = true;
while (b) {
String startBalanceString = JOptionPane.showInputDialog(null, "Enter the starting balance in dollars without the dollar sign.");
try {
double startBalance = Double.parseDouble(startBalanceString);
int accountID = 1;
SavingsAccount accountID = new SavingsAccount(holder, startBalance);
accountID += 1;
b = false;
}
catch (final Exception ignored) {
JOptionPane.showMessageDialog(null, "Only enter numbers, please.");
}
}
}
Creating an integer and setting the name of the savings account to the integer. But that's giving me the error "Duplicate local variable accountID".
When using my application, I want to get this:
SavingsAccount sa1 = new SavingsAccount(holder, startBalance);
SavingsAccount sa2 = new SavingsAccount(holder, startBalance);
SavingsAccount sa3 = new SavingsAccount(holder, startBalance);
The parameters are variables whose are already initialized!
I want to set the name of the new SavingsAccount to the accountID's value. So if I create a new instance of a SavingsAccount, I want my application to set it's name to sa1. And if I create another one after that, name it sa2, sa3, sa4, etc.
PS: Holder is a string, it contains the name of someone! It's not an integer!
I hope you understand what I mean!
But if there comes a second savings account, how do I make the application create a savings account with the name sa2, and after that one with the name sa3 etc?
Declare a global int, let's say index.
private int index;
Set it to 1 in your constructor:
this.index = 1;
Each time someone creates a savings account, increase index.
SavingsAccount accountID = new SavingsAccount(holder + index++, startBalance);
This will add the current value of index to the end of the holder string, then increase the value of index.
Edit
Okay, so I get what you mean, but a variable can not start with, or be named solely a number. Instead, why not add those accounts to an array or a List implementation?
List<SavingsAccount> accounts = new ArrayList<SavingsAccount>();
accounts.add(new SavingsAccount("Dave", something);
accounts.add(new SavingsAccount("Bill", somethingElse);
Then to get each account, you can use something like this:
accounts.get(1);
NOTE: This list is 0 based. Which means accounts.get(0); will get the first item.
int accountID = 1;
SavingsAccount accountID = new SavingsAccount(holder, startBalance);
You can't have 2 variables with the same name.
You probably want to store the savings in a list outside of your method. I suggest a field:
private static List<SavingsAccount> savingsAccounts = new ArrayList<SavingsAccount>();
and your method could go like this:
public static void accountTypeSavings() {
boolean b = true;
while (b) {
String startBalanceString = JOptionPane.showInputDialog(null, "Enter the starting balance in dollars without the dollar sign.");
try {
double startBalance = Double.parseDouble(startBalanceString);
savingAccounts.add(new SavingsAccount(holder, startBalance));
b = false;
}
catch (final Exception ignored) {
JOptionPane.showMessageDialog(null, "Only enter numbers, please.");
}
}
}
Later you can access the saving accounts from the list to modify their properties:
savingAccounts.get(0).addAmount(amount); // something like this to add money to the first account
What you need is a list.So add another static variable savingsAccountList
public static List<SavingsAccount> savingsAccountList = new ArrayList<SavingsAccount>();
You can take an auto incrementing variable m and use it as a static class variable:
public static int m=0;
public static void accountTypeSavings() {
boolean b = true;
holder="holderName"
while (b) {
String startBalanceString = JOptionPane.showInputDialog(null, "Enter the starting balance in dollars without the dollar sign.");
try {
double startBalance = Double.parseDouble(startBalanceString);
SavingsAccount sa = new SavingsAccount(holder + m, startBalance);
m++
savingsAccountList.add(sa)
b = false;
}
catch (final Exception ignored) {
JOptionPane.showMessageDialog(null, "Only enter numbers, please.");
}
}
}
Also you need to import java.util.List.

How do I add an element to the end of my array?

I don't know if this is right, so I need your comments guys. I have an array of employee names. It will be displayed on the console, then will prompt if the user wants to insert another name. The name should be added on the end of the array(index 4) and will display again the array but with the new name already added. How do I do that? Btw, here's my code. And I'm stuck. I don't even know if writing the null there is valid.
public static void list() {
String[] employees = new String[5];
employees[0] = "egay";
employees[1] = "ciara";
employees[2] = "alura";
employees[3] = "flora";
employees[4] = null;
for(int i = 0; i < employees.length; i++) {
System.out.println(employees[i]);
}
}
public static void toDo() {
Scanner input = new Scanner(System.in);
System.out.println("What do you want to do?");
System.out.println("1 Insert");
int choice = input.nextInt();
if(choice == 1) {
System.out.print("Enter name: ");
String name = input.nextLine();
You can't, basically.
Arrays have a fixed size when they've been constructed. You could create a new array with the required size, copy all the existing elements into it, then the new element... or you could use a List<String> implementation instead, such as ArrayList<String>. I'd strongly advise the latter approach.
I suggest you read the collections tutorial to learn more about the various collections available in Java.
Also note that you've currently just got a local variable in the list method. You'll probably want a field instead. Ideally an instance field (e.g. in a class called Company or something similar) - but if you're just experimenting, you could use a static field at the moment. Static fields represent global state and are generally a bad idea for mutable values, but it looks like at the moment all your methods are static too...
Arrays are fixed in size. Once you declare you can not modify it's size.
Use Collection java.util.List or java.util.Set. Example ArrayList which is dynamic grow-able and backed by array.
If you really have to use arrays then you will have to increase the size of the array by using an intermediate copy.
String[] array = new String[employees.length + 1];
System.arraycopy(employees, 0, array, 0, employees.length);
array[employees.length] = newName;
employees = array;
However, the best way would be to use a List implementation.
It depends on whether the user can enter more than 4 employee names. If they can then using ArrayList is the better choice. Also the employees variable needs to be a static property of your class since being used in a static method.
private static String[] employees = new String[5];
static {
employees[0] = "egay";
employees[1] = "ciara";
employees[2] = "alura";
employees[3] = "flora";
employees[4] = null;
}
public static void list() {
for(int i = 0; i < employees.length; i++) {
System.out.println(employees[i]);
}
}
public static void addEmployeeName(String name, int index) {
employees[index] = name;
}
Here you are using static array which is fixed at the time of creation.I think you should use
java.util.Arraylist which will provide you facility of dynamic array.

Email method not working

Hey i have an EmployeeStore which i have used a hashmap for this. The variables that the map stores are email name and id. I have a method called SearchByEmail but there is a problem with this. The method returns false when the user inputs a correct employee email into the UI.
Here is my code:
This is in the MainApp
case 2:
System.out.println("Search by Email.");
Employee employeeSearchEmail = MenuMethods.userInputByEmail();
Store.searchByEmail(employeeSearchEmail.getEmployeeEmail());
MenuMethods
//Imports
import java.util.Scanner;
//********************************************************************
public class MenuMethods
{
private static Scanner keyboard = new Scanner(System.in);
//Methods for the Company Application menu.
//Method for validating the choice.
public static int getMenuChoice(String menuString, int limit, String prompt, String errorMessage)
{
System.out.println(menuString);
int choice = inputAndValidateInt(1, limit, prompt, errorMessage);
return choice;
}
//********************************************************************
//This method is used in the getMenuChoice method.
public static int inputAndValidateInt(int min, int max, String prompt, String errorMessage)
{
int number;
boolean valid;
do {
System.out.print(prompt);
number = keyboard.nextInt();
valid = number <= max && number >= min;
if (!valid) {
System.out.println(errorMessage);
}
} while (!valid);
return number;
}
//********************************************************************
public static Employee userInput()
{
String temp = keyboard.nextLine();
Employee e = null;
System.out.println("Please enter the Employee Name:");
String employeeName = keyboard.nextLine();
System.out.println("Please enter the Employee ID:");
int employeeId = keyboard.nextInt();
temp = keyboard.nextLine();
System.out.println("Please enter the Employee E-mail address:");
String employeeEmail = keyboard.nextLine();
return e = new Employee(employeeName , employeeId, employeeEmail);
}
//********************************************************************
public static Employee userInputByName()
{
//String temp is for some reason needed. If it is not included
//The code will not execute properly.
String temp = keyboard.nextLine();
Employee e = null;
System.out.println("Please enter the Employee Name:");
String employeeName = keyboard.nextLine();
return e = new Employee(employeeName);
}
//********************************************************************
public static Employee userInputByEmail()
{
//String temp is for some reason needed. If it is not included
//The code will not execute properly.
String temp = keyboard.nextLine();
Employee e = null;
System.out.println("Please enter the Employee Email:");
String employeeEmail = keyboard.nextLine();
//This can use the employeeName's constructor because java accepts the parameters instead
//of the name's.
return e = new Employee(employeeEmail);
}
//********************************************************************
}
SearchByEmail
public boolean searchByEmail(String employeeEmail)
{
//(for(Employee e : map.values()) {...})
//and check for each employee if his/her email matches the searched value
boolean employee = map.equals(employeeEmail);
System.out.println(employee);
return employee;
}
First of all,
map.equals(employeeEmail);
doesn't really make sense. map is a Hashmap, and employeeEmail is a String. Under what conditions would they be equal?
It is unclear what you store in the map and how, since you have neither included the declaration of the map, nor the code that inserts new values. I'll assume for now that you store mappings like name -> Employee. If you want to search for an employee based on an email address I suggest you do something like
Employee findByEmail(String email) {
for (Employee employee : yourMap.values())
if (employee.getEmail().equals(email))
return employee;
// Not found.
return null;
}
then to check if an employee with email exists, you could do
public boolean searchByEmail(String employeeEmail) {
boolean employee = findByEmail(employeeEmail) != null;
System.out.println(employee);
return employee;
}
I assume map is of type Map<S,T> for some S,T, and thus it is not of the same type as employeeEmail, and specifically it does not equals() it.
I suspect you are looking for Map.containsValue() (if the email is the value in the map) or Map.containsKey() (if the email is the key of the map), depending on what exactly map is mapping, if the mapping is to/from the string value.
EDIT: based on clarifications on comments:
Since the email is not a key nor value in map, the suggested solution won't work as it is. So you can chose one of those:
Use #aioobe's solution to iterate and check each email.
Add an extra field to the class: Map<String,Employee> map2 which will map: email_address->employee. Given this map, you can search for an email using map2.containsKey(email). It will ensure faster lookup for an employee from an email and the expanse of holding an extra map. I'd go with this choice if I were you.

Categories