pasword masking in console window and recursive function call in java - java

the following java code is executed in the console window in DR.java IDE.
i have the following two problems please help me friends.
Is it possible to make password masking ?? i tried a lot by googling but none worked for me (should use only console window for excecution).
When i call the "GetLoginDetails();" inside the "ShowAdminMainMenuFun(String EmpName)" method it is showing error ([line: 148] Error: Unhandled exception type java.io.IOException).
i thought of making recursive function but it dint worked can u correct the coding and post it back.
thanking u friends
{
import java.io.*;
import java.awt.*;
import java.io.Console;
import java.util.Scanner;
/*
UserLoginAuthentiction UserLoginAuthentictionObj = new UserLoginAuthentiction();
UserLoginAuthentictionObj.GetLoginDetails();
*/
class UserLoginAuthentiction
{
static String EmployeeID,Password;
public static byte resultRole = 0;
public static void main(String[] args) throws Exception
{
GetLoginDetails(); // it works well here but not works when called againin the following code
}
static void GetLoginDetails() throws IOException
{
Scanner sc = new Scanner(System.in);
byte resultRole = 0;
byte CountForLogin = 0;
System.out.println("Totally 3 attempts ");
do
{
if(CountForLogin<3){
System.out.print("\nEnter User Name:");
EmployeeID = sc.nextLine();
System.out.print("Enter Password :");
Password = sc.nextLine();
resultRole = ValidateUserIDAndPassword(EmployeeID,Password);
// if result is zero then the login is invalid,
// for admin it is one ,
// for quality analyser it is 2
// for project developer it is 3
// for developer it is 4
if(resultRole==0)
{
System.out.println("Username & Password does not match ");
System.out.print("Retry ::");
CountForLogin++;
if(CountForLogin>2)
{System.out.println("ur attempts are over is locked");}
}
else
{
System.out.println("here t should call the appropriate employe function");
GetRoleAndAssignFun(EmployeeID,resultRole);
break;
}
}
}while(resultRole==0);
}
static byte ValidateUserIDAndPassword(String EmployeeID,String Password)
{
byte resultRole = 0;
if((EmployeeID.equals("tcs"))&&(Password.equals("tcs")))
{
resultRole = 1;
}
/*
Code for checking the arraylist and returning the validations
this method should return the roles of the users password
*/
return resultRole;
}
static void GetRoleAndAssignFun(String EmpName ,int EmpRole)
{
// System.out.println(" ");
switch(EmpRole)
{
case 1:
System.out.println(" hi " +EmpName+ " u are logged in as admin ");
ShowAdminMainMenuFun(EmpName);
break;
case 2:
System.out.println(" hi " +EmpName+ " u are logged in as QA ");
// QualityAnalyserMainMenu(EmpName);
break;
case 3:
System.out.println(" hi " +EmpName+ " u are logged in as PM ");
// ProjectMAnagerMainMenu(EmpName);
break;
case 4:
System.out.println(" hi " +EmpName+ " u are logged in as DEVeloper ");
// DeveloperMainMenu(EmpName);
break;
default:
// System.out.println(EmpName +" You dont have any roles asigned ");
break;
}
}
public static void ShowAdminMainMenuFun(String EmpName)
{
Scanner sc = new Scanner(System.in);
int loop_option=0;
do
{
//BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println(" Hi "+ EmpName + " you can perform task ussing the menu given below");
System.out.println("press the appropriate option only");
System.out.println("1.Create New Employe Profile ");
System.out.println("2.See Employee's Profile ");
System.out.println("3. LogOut ");
System.out.println("Enter the Option u need:");
int option = sc.nextInt();
switch(option)
{
case 1:
System.out.println("1.Creating New Employe Profile");
//CreateNewEmployeeProfile();
break;
case 2:
System.out.println("2.See Employee's Profile ");
// ViewEmployeeProfile();
break;
case 3:
System.out.println("3. LogOut");
System.out.println("Do u want to continue logging out ?? If yes Press 1 ..");
boolean ConformLogout = false;
ConformLogout = sc.nextBoolean();
if(ConformLogout)
{
**GetLoginDetails();** //**** error is here */ how can i call this function please help me
}
else
{
}
// LogOut();
break;
default :
System.out.println(" You .. ");
}
System.out.println("Do u want to continue to main menu ?? Press 1 to continue..");
loop_option = sc.nextInt();
}while(loop_option==1);
}
}
}

Regarding your first question,
Is it possible to make password
masking?
You can use java.io.Console class to hide the password on console window.

Related

My login method returns both true and false output, why?

I still cannot figure out what is wrong with my code.
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("[1] Register");
System.out.println("[2] LogIn as Client");
System.out.println("[3] LogIn as Admin");
System.out.println("[4] Exit");
System.out.print("Enter your choice here: ");
int choice = input.nextInt();
switch(choice){
case 1:
System.out.println("[Register Your Account]");
System.out.print("-----Enter your name: ");
String name = input.next();
System.out.print("-----Enter your desired 4-digit pin: ");
int pin = input.nextInt();
System.out.print("-----Enter your first deposit: ");
int balance = input.nextInt();
account client = new account(name,pin,balance);
client.setName(name);
client.setPin(pin);
client.setBalance(balance);
addToArrayList(client);
case 2:
System.out.println("[LogIn Your Account]");
System.out.println("----Enter Your Pin: ");
int logPin = input.nextInt();
logIn(logPin);
break;
case 3:
System.out.println("Case 3");
break;
case 4:
System.out.println("Case 4");
break;
}
}
static void addToArrayList(account client){
userList.add(client);
displayRegister(userList);
}
static void displayRegister(ArrayList<account> users){
for (account client : users){
System.out.println("(Here's what we received)");
System.out.println(client.getName());
System.out.println(client.getPin());
System.out.println(client.getBalance());
}
}
Why does my login give an output of both TRUE AND FALSE when I entered a correct pin after register, and if I entered a wrong pin the program ends?
static void logIn (int logPin){
if(!userList.isEmpty()){
int i = 0;
boolean isNotExist = false;
for(var acc: userList){
int pinCode = acc.getPin();
if(logPin==acc.getPin()){
System.out.println("(LogIn Successfully!)");
isNotExist=true;
mainMenu();
}
else{
i++;
}
}
if(isNotExist){
System.out.println("(Account does not exist...)");
}
}else{
System.out.println("(No data...)");
}
}
With this method that you have written:
static void logIn (int logPin){...}
You receive nothing when you call it. As it is of void return type. However,
static boolean logIn (int logPin){...}
Will give you a return of true or false as it is of boolean. Then call it like so:
boolean success = logIn(logPin);
EDIT for additional information
With a boolean return type on that
method, you will need to return the value isNotExist instead of just declaring and assing a value to it in the method:
{
boolean isNotExist = false;
...
// Code to assign value
...
return isNotExist;
}

Java CSV printing relevant information in relation to User input

my current code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
public class Menu {
private static final String DEFAULT_DATE_FORMAT = "MM/dd/yyyy";
public static void main(String[] args) {
boolean exit = false;
int userInputt;
do {
userInputt = printMenu();
switch(userInputt) {
case 1:
inputLocation();
break;
case 2:
inputType();
break;
case 3:
inputRating();
break;
case 4:
System.out.println("Goodbye!");
exit = true;
break;
default:
System.out.println("Invalid Option.");
break;
}
}
/* an int varible that allows the storing of an integer */
while(userInputt > 4);
}
/* an int varible that allows the storing of an integer */
public static int printMenu () {
int selection;
Scanner sc = new Scanner (System.in);
System.out.println("Welcome to Melbnb!");
System.out.println("------------------------------------------------");
System.out.println("> Select from main menu");
System.out.println("------------------------------------------------");
System.out.println(" 1) Search by location");
System.out.println(" 2) Browse by type of place");
System.out.println(" 3) Filter by rating");
System.out.println(" 4) Exit");
System.out.print("Please Select: ");
selection = sc.nextInt();
return selection;
}
private static char inputLocation() {
Scanner userInput = new Scanner(System.in);
File file = new File("C:/Users/andys/OneDrive/Desktop/Melbnb (2).csv");
String fileData = "";
try (Scanner reader = new Scanner(file)) {
// Read the header line so we don't deal with it again
fileData = reader.nextLine();
System.out.print("Please provide a location: ");
String location1 = userInput.nextLine().trim();
List<String> foundRecords = new ArrayList<>();
boolean found = false;
while (reader.hasNextLine()) {
fileData = reader.nextLine().trim();
// Skip blank lines (if any).
if (fileData.isEmpty()) {
continue;
} String regex = ",";
String[] lineParts = fileData.split(regex);
found = (location1.isEmpty() ||
(lineParts[0].contains(location1) ||
(location1.isEmpty() ||
(lineParts[1].contains(location1)))));
if (found) {
foundRecords.add(fileData);
found = false;
}
}
// Display found records (if any)
System.out.println();
System.out.println("Found Records:");
System.out.println("====================================");
if (foundRecords.isEmpty()) {
System.out.println(" No Records Found!");
}
else {
for (String str : foundRecords) {
System.out.println(str);
}
}
System.out.println("====================================");
}
catch (FileNotFoundException ex) {
}
char userInputt;
do {
userInputt = location();
switch(userInputt) {
case 1:
System.out.println("------------------------------------------------");
break;
case 2:
inputType();
break;
case 3:
inputRating();
break;
case 4:
printMenu();
break;
default:
break;
}
}
while(userInputt > 4);
return userInputt;
}{
}
private static char location() {
// TODO Auto-generated method stub
return 0;
}
private static void inputType() {
System.out.println("------------------------------------------------");
}
private static void inputRating() {
}
/* ---------------------------------- Locations ---------------------------------- */
private static void Southbank() {
int southbankPrice = 42;
int southbankClean = 11;
int southbankService = 10;
double southbankDiscount = 0.05;
Scanner checkIn = new Scanner (System.in);
System.out.println("------------------------------------------------");
System.out.println("> Provide dates");
System.out.println("------------------------------------------------");
System.out.print("Please provide check-in date (dd/mm/yyyy): ");
Date inDate = getInputDate(checkIn);
System.out.print("Please provide checkout date (dd/mm/yyyy): ");
Date outDate = getInputDate(checkIn);
System.out.println("------------------------------------------------");
Scanner pInfo = new Scanner (System.in);
System.out.println("> Provide personal information");
System.out.println("------------------------------------------------");
System.out.print("Please provide your given name: ");
String southName = pInfo.nextLine();
System.out.print("Please provide your surname: ");
String southLast = pInfo.nextLine();
System.out.print("Please provide your email address: ");
String southEmail = pInfo.nextLine();
System.out.print("Please provide number of guests: ");
String southGuest = pInfo.nextLine();
System.out.print("Confirm and pay (Y/N): ");
String southConfirm = pInfo.nextLine();
System.out.println("------------------------------------------------");
System.out.println("> Show property details");
System.out.println("------------------------------------------------");
System.out.printf("%-25s%-20s\n", "Property:","Private room in the heart of Southbank hosted by " + southName);
System.out.printf("%-25s%-20s\n", "Type of place:","Private room");
System.out.printf("%-25s%-20s\n", "Location:","Southbank");
System.out.printf("%-25s%-20s\n", "Rating:","4.5");
System.out.printf("%-25s%-20s\n", "Description:","The apartment is situated in the heart of Southbank with an easy access to shops and cafes. It has a warm and spacious living room with an amazing view of the gardens.");
System.out.printf("%-25s%-20s\n", "Number of guests: ", southGuest);
System.out.printf("%-25s%-20s\n", "Price:", "asd");
System.out.printf("%-25s%-20s\n", "Discounted price:","asd");
System.out.printf("%-25s%-20s\n", "Service fee:","asd");
System.out.printf("%-25s%-20d\n", "Cleaning fee: ", southbankClean );
System.out.printf("%-25s%-20s\n", "Total:","asd");
}
/* ---------------------------------- Date Validation ---------------------------------- */
private static Date getInputDate(final Scanner checkIn) {
try {
return new SimpleDateFormat(DEFAULT_DATE_FORMAT).parse(checkIn.nextLine());
} catch (ParseException ex) {
System.out.println("Invalid Date. Please Try again!");
Southbank();
}
return null;
}
}
The first image is my Desired output
The second is my current output
and the third image is my CSV
My program has a feature which will allow the user to a hotel apartment by inputting a specific location for example 'South', as shown in the screenshots of my current output once the term 'South' gets inputted to prints out all the columns for any fields relating to the search term in the CSV file, However i only want the first column to be printed out. How can i achieve this output?
What can i do to achieve my desired output?
I have tried removing the 'for' statement in the following code and replacing the print element with foundrecords.get(0)

Why are the switch-case part and runtime polymorphism is not working?

I've got a problem with (switch-case) part and I've tried to test some run-time polymorphism in main. It is not working. And in switch case ; it always says:
Your choice is not available.
And at the end it does not quit the program. It continuous with a loop.
How should I do to get rid of this problem?
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String tempName;
int tempQueue;
double tempKilo, tempCalibre;
String tempAgri;
ArrayList<Farmer> farmers = new ArrayList<>();
final int capacity = 2;
for(int i=0; i<capacity; i++) {
System.out.println(" Please enter the farmer's name : ");
tempName = sc.nextLine();
System.out.println(" Please enter the queue number : ");
tempQueue = Integer.parseInt(sc.nextLine());
System.out.println(" Please enter the calibre of the cherry : ");
tempCalibre = Double.parseDouble(sc.nextLine());
System.out.println(" Please enter the kilo of the cherry : ");
tempKilo = Double.parseDouble(sc.nextLine());
Cherry cherry1 = new Cherry(tempName, tempQueue, tempCalibre, tempKilo);
farmers.add(cherry1);
cherry1.displayMenu();
cherry1.Price();
}
for(int i=0; i<capacity; i++) {
System.out.println(" Please enter the farmer's name : ");
tempName = sc.nextLine();
System.out.println(" Please enter the queue number : ");
tempQueue = Integer.parseInt(sc.nextLine());
System.out.println(" Please enter the production type of Apple : ");
tempAgri = sc.nextLine();
System.out.println(" Please enter the kilo of the apple : ");
tempKilo = Double.parseDouble(sc.nextLine());
Apple apple1 = new Apple(tempName, tempQueue, tempAgri, tempKilo);
farmers.add(apple1);
apple1.displayMenu();
apple1.Price();
}
ArrayList<Farmer>farmers1=new ArrayList<>();
int checkpoint;
boolean isPFruitAvailable;
double totalPrice;
while(true) {
display();
checkpoint=Integer.parseInt(sc.nextLine());
switch(checkpoint) {
case 1:
System.out.println(" Please enter the name of the farmer that you want... ");
tempName=sc.nextLine();
isPFruitAvailable=false;
for(Farmer fruit : farmers1) {
if(fruit.getName().equals(tempName)) {
farmers1.add(fruit);
System.out.println("Your choice is successfully added.");
isPFruitAvailable=true;
break;
}
}
if(!isPFruitAvailable) {
System.out.println(" Your choice is not available");
}
break;
case 2:
totalPrice=0.0;
System.out.println(" Please enter the name in the cart . ");
System.out.println(" Checking out...");
for(Farmer fruit1 : farmers1) {
fruit1.displayMenu();
totalPrice+=fruit1.Price();
}
System.out.println(" Price is "+totalPrice);
break;
default:
System.out.println(" Thanks for your informations...");
System.out.println(" The program quits within a second... ");
break;
}
}
}
public static void display() {
System.out.println(" Welcome to fruit transfer system... ");
System.out.println(" Press 1 to add fruit into the system... ");
System.out.println(" Press 2 to check fruit you want... ");
System.out.println(" Press any key to quit the program.... ");
}
}
you never populated your farmers1 list, it is always empty therefore isFruitAvailable is always false. Also, your while loop never terminates, it just keeps spinning ("break" statements that you have are inside switch and have nothing to do with "while")
for(Farmer fruit : farmers1) {
if(fruit.getName().equals(tempName)) {
farmers1.add(fruit); //the only place where you add something, but it never gets executed
break;
}
}
As per my understanding you want to compare the new farmer with the list of farmers alredy populated i.e. farmers and if it matches any add it to farmers1 list.
Therefore inside the switch case change the for loop as shown below:
// Compare the farmer tempName with the list of farmers already populated
for(Farmer fruit : farmers) {
if(fruit.getName().equals(tempName)) {
farmers1.add(fruit);
System.out.println("Your choice is successfully added.");
isPFruitAvailable=true;
break;
}
}

Create a program that allows to receive multiples entry data, shows the data from the list

i was told to make a program like that, after input i can see the data
This is my code, please help i had search how to do it but i mostly only if the data is already known not by user input.
is it using an array or using for?
i search many time but i still dont find like mine
ive tried using array but i dont know how to get the array like, there is 3 user input in one array. mostly i found just using one user input
and sometime i get the error where the string cannot meet the int type
import java.util.Scanner;
public class Case7{
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int choose=0;
String name ="";
String pos = "";
int age = 0;
do{
System.out.println("JOB VACANCY");
System.out.println("===========");
System.out.println("1. Insert new data");
System.out.println("2. List of staff");
System.out.println("3. Search staff");
System.out.println("4. Exit");
System.out.print("Choose: ");
choose = input.nextInt();
if (choose == 1)
{
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
do{
System.out.print("Input staff name: ");
name = input.nextLine();
}while(name.length() < 3 || name.length() > 20);
do{
System.out.print("Input staff position [Manager | Analyst | Programmer]: ");
pos=input.nextLine();
}while(!pos.equalsIgnoreCase("Manager") && !pos.equalsIgnoreCase("Analyst") && !pos.equalsIgnoreCase("Programmer"));
do{
System.out.print("Input staff age: ");
age=input.nextInt();
}while(age <= 17);
System.out.println("Data has been added!");
input.nextLine();
input.nextLine();
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
}
else if (choose == 2)
{
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
for (int i = 1; i < 6 ; i++ )
{
System.out.println("Staff ID :" + i);
System.out.println("==============");
System.out.println("1. name : " +name );
System.out.println("2. position : " +pos );
System.out.println("3. age : " +age );
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
}
}
Can I suggest a radically different implementation?
You can use a switch to score the options and You can use a LinkedList to store all the new staff member dinamically.
Here's my commented code:
static LinkedList<Staffer> staff=new LinkedList<>(); //ours database
static Scanner input = new Scanner (System.in);
public static void main(String[] args) {
String s="";
int number=-1;
while(number!=4){ //if your choice is 4, we can exit!
//Chooser:
System.out.print("JOB VACANCY\n===========\n1. Input data\n2. Show Data\n3.Delete Data\n4.£xit\nYour choice: ");
s=input.nextLine();
if(s.matches("\\d+")){ //Check if s is a number
number=Integer.parseInt(s);
switch(number){
case 1: input(); break;
case 2: showData(); break;
case 3: deleteData(); break;
case 4: System.out.println("Goodbye!"); break;
default: System.out.println("Number not valid. Try again!");
}
}else
System.out.println("Number not valid. Try again!");
}
}
private static void showData() {
for(Staffer st:staff)
System.out.println(st);
}
private static void deleteData(/*parameters*/) {
// You can delete a staffer by passing the name, for example
}
private static void input() {
//Plese, implements your data control options...
String name, position;
int age;
System.out.print("Name: ");
name=input.nextLine();
System.out.print("Position: ");
position=input.nextLine();
System.out.print("Age: ");
age=(Integer.parseInt(input.nextLine()));
Staffer staffer=new Staffer(name,position, age);
staff.add(staffer);
}
public static class Staffer{ //a staff member has 3 parameter: name, position and age... You can add others
/*You should store the name using only upperCase or LowerCase, or
* John Williams != john williams != JOHN WILLIAMS and you can have three times
* the same people.
*
* The position can be converted in enum for the same reason.
*/
private String name, position;
private int age;
public Staffer(String name, String position, int age){
this.name=name;
this.position=position;
this.age=age;
}
#Override
public String toString(){
return "Mr. "+name+", "+position+" (age: "+age+")";
}
}
You can see the following example output:
.
Obviously, you have to improve the output and all the data check options.

Method to Find ArrayList Index to Where the Object Will be Added

I have an ArrayList that is being filled with customer information using a Customer class. In my addCustomerRecord method, I am calling findAddIndex within the addCustomerRecord method so the data entered will be sorted prior to displaying the data. Here is my code and do not mind the fileWhatever method, I don't use it.
public class CustomerDemo
{
//arrayList of customer objects
public static ArrayList<Customer> customerAL = new ArrayList<>();
public static void main (String[] args)
{
//to hold menu choice
String menuChoice = "";
Scanner kb = new Scanner(System.in);
System.out.println("To add a record press 'A': \n"
+ "to display all records press 'D': \n"
+ "to exit press 'Q': \n");
//loop priming read
menuChoice = kb.nextLine();
//make input case insensitive
menuChoice = menuChoice.toLowerCase();
do
{
if(menuChoice.equals("a"))
addCustomerRecord(kb);
else if(menuChoice.equals("d"))
{
displayCustomerRecords();
}
else if(menuChoice.equals("q"))
{
System.out.println("Program exiting..");
System.exit(0);
}
else
{
System.out.println("incorrect entry. Please re-enter a valid entry: \n");
menuChoice = kb.nextLine();
menuChoice = menuChoice.toLowerCase();
}
System.out.println("To add a record press 'A': \n"
+ "to display all records press 'D': \n"
+ "to exit press 'Q': \n");
menuChoice = kb.nextLine();
menuChoice = menuChoice.toLowerCase();
}while(menuChoice.equals("a") || menuChoice.equals("d") || menuChoice.equals("q"));
kb.close();
}
/* public static void displayCustomerRecords()
{
System.out.println();
for (int i = 0; i < customerAL.size(); ++i)
{
System.out.printf("%-15s", customerAL.get(i).getLastName());
System.out.printf("%-15s", customerAL.get(i).getFirstName());
System.out.printf("%-6s", customerAL.get(i).getCustID());
System.out.printf("%15s\n", customerAL.get(i).getPhoneNumber());
}
System.out.println();
}
/**
* prompts to enter customer data and mutator methods called
* with a Scanner object passed as an argument to set data
* #param location index position of where the element will be added.
* #param kb a Scanner object to accept input
*/
public static void addCustomerRecord(Scanner kb)
{
Customer currentCustomerMemoryAddress = new Customer();
System.out.println("Enter first name: \n");
String fName = kb.nextLine();
currentCustomerMemoryAddress.setFirstName(fName);
System.out.println("Enter last name: \n");
String lName = kb.nextLine();
currentCustomerMemoryAddress.setLastName(lName);
System.out.println("Enter customer phone number: \n");
String pNum = kb.nextLine();
currentCustomerMemoryAddress.setPhoneNumber(pNum);
System.out.println("Enter customer ID number: \n");
String ID = kb.nextLine();
currentCustomerMemoryAddress.setCustID(ID);
int addLocation = findAddLocation(currentCustomerMemoryAddress);
customerAL.add(addLocation, currentCustomerMemoryAddress);
currentCustomerMemoryAddress = null;
}
public static int findAddLocation(Customer cust)
{
int location = 0;
if(!customerAL.isEmpty())
{
for(int i = 0; i < customerAL.size(); i++)
{
//Stumped here
}
}
else
return location;
return location;
}
}
It looks like you are reinventing the wheel here William
Replace your code for displayCustomerRecords with this:
public static void displayCustomerRecords()
{
System.out.println();
customerAL.stream().map(c -> String.format("%-15s%-15s%-6s%15s\n",
c.getLastName(), c.getFirstName(), c.getCustID(), c.getPhoneNumber()))
.sorted()
.forEach(System.out::print);
System.out.println();
}
Update
Taking into account your comment you can replace your findAddLocationmethod by the following:
private static Comparator<Customer> comparator = Comparator.comparing(Customer::getLastName)
.thenComparing(Customer::getFirstName)
.thenComparing(Customer::getCustID)
.thenComparing(Customer::getPhoneNumber);
public static int findAddLocation(Customer cust)
{
int location = 0;
if(!customerAL.isEmpty())
{
for(Customer customerInList : customerAL)
{
if(comparator.compare(customerInList, cust) > 0) {
break;
}
location++;
}
}
return location;
}
We are traversing the array using Java's enhanced for-loop and comparing the objects using a Java 8 declared comparator (which I believe is the key to this assignment).
It would be a good idea if you could look into the Comparable interface and implement it in your Customer class. That way you could simply do a simple call to customerInList.compareTo(cust) to compare both objects.
As already stated, this is not a good practice and shouldn't be used in production code.

Categories

Resources