Remove User Duplicate From Array String - java

I am trying to create a program that accepts as many Social Security Numbers as the user wants to input. The only restriction is that the numbers must follow the format XXX-XX-XXXX and not accept duplicated entries. This is what I have so far:
Subclass 2
package SSNServerStorageExpanded;
class SSNArray{
final String[] ssnNumber;
int arrayCount;
public SSNArray(){//defult contructor
ssnNumber = new String[9999];
arrayCount = 0;
}
public SSNArray(int arraySize){
ssnNumber = new String[arraySize];
arrayCount = 0;
}
public String[] getSSNNumber(){
return ssnNumber;
}
public int getArrayCount(){
return arrayCount;
}
public boolean validateSSNNumber(String SSNFormat){
return SSNFormat.matches("\\d{3}-\\d{2}-\\d{4}");
}
public String addSSN(String SSNFormat){
if(validateSSNNumber(SSNFormat)){
return ssnNumber[arrayCount++] = SSNFormat;
}else{
return null;
}
}
#Override
public String toString(){
String str = "\nThe Social Security Number(s) you entered is(are):\n";
for(int x = 0; x < arrayCount; x++){/
str += ssnNumber[x] + "\n";
}return str;
}
}
Subclass 1
package SSNServerStorageExpanded;
public class SSNArrayExpanded extends SSNArray{
public SSNArrayExpanded(){
super();
}
public SSNArrayExpanded(int arraySize){
super(arraySize);
}
#Override
public boolean validateSSNNumber(String SSNFormat){
if(super.validateSSNNumber(SSNFormat)){
boolean duplicate = false;
for(int y = 0; y < arrayCount; y++){
if(ssnNumber[y].equals(ssnNumber[arrayCount])){
System.out.println("No duplicates allowed, please try again");
duplicate = true;
break;
}
}
if(!duplicate){
arrayCount++;
}
}
return true;
}
}
Mainclass
package SSNServerStorageExpanded;
import java.util.Scanner;
public class SSNArrayTestExpanded{
public static void main(String[] args){
SSNArrayExpanded SSNArrayExpandedObject = new SSNArrayExpanded();
Scanner input = new Scanner(System.in);
System.out.println("Initiating SSN Server Storage Expanded");
System.out.println("► Type 'EXIT' at any moment to close the program ◄\n");
boolean run = true;
while(run){
System.out.print("Enter your Social Security Number(XXX-XX-XXXX): ");
String ssnNumber = input.next();
if(ssnNumber.equalsIgnoreCase("EXIT")){
System.out.print(SSNArrayExpandedObject.validateSSNNumber(ssnNumber));
return;
}else if(SSNArrayExpandedObject.validateSSNNumber(ssnNumber)){
SSNArrayExpandedObject.addSSN(ssnNumber);
}else{
System.out.println("!Please use the format XXX-XX-XXXX!");
}
}
}
}
What am I doing wrong with my public boolean validateSSNNumber method under Subclass 1 or are there more errors in my code that I am not aware of?

In your subclass1 can you try this. You need to compare the SSNFormat String entered by user with the array values (you were comparing array values itself). Do not increase the array count here instead do it in addSSN function as you were doing.
#Override
public boolean validateSSNNumber(String SSNFormat){
if(super.validateSSNNumber(SSNFormat)){
boolean duplicate = false;
for(int y = 0; y < arrayCount; y++){
if(ssnNumber[y].equals(SSNFormat)){
System.out.println("No duplicates allowed, please try again");
duplicate = true;
break;
}
}
if(!duplicate){
return true;
}
}
return false;
}
In the SSNArray class use this function for adding SSN number without validating the SSNFormat again.
public String addSSN(String SSNFormat){
return ssnNumber[arrayCount++] = SSNFormat;
}

You can try using a Set, which will easily help you to check for any duplicates and will reduce your iteration over array.

Why cant you go for LinkedHashSet data structure for storing the ssn number.?, provides easy retrieval and duplicate check in an order of O(1).
final LinkedHashSet<String> ssnNumber;
also the code
#Override
public boolean validateSSNNumber(String SSNFormat){
if(super.validateSSNNumber(SSNFormat)){
boolean duplicate = ssnNumber.add(SSNFormat);
if(duplicate){
System.out.println("No duplicates allowed, please try again");
return false;
}
return true;
}
return false
}

Here is your complete Solution, with this you can add N-number of SSN-Number as you want,
import java.util.HashSet;
import java.util.Scanner;
class SSNSet{
final HashSet<String> allSsnNumber = new HashSet<String>();
public HashSet<String> getAllSsnNumber() {
return allSsnNumber;
}
public boolean validateSSNNumber(String SSNFormat){
return SSNFormat.matches("\\d{3}-\\d{2}-\\d{4}");
}
public boolean addSSN(String SSNFormat){
if(validateSSNNumber(SSNFormat)){
boolean flag;
if(allSsnNumber.add(SSNFormat)){
System.out.println("Added Successfully");
flag = true;
}else{
System.out.println("Duplicate Not Allow");
flag = false;
}
return flag;
}else{
System.out.println("!Please use the format XXX-XX-XXXX!");
return false;
}
}
}
public class SSNArrayTestExpanded{
public static void main(String[] args){
SSNSet SSNArrayExpandedObject = new SSNSet();
Scanner input = new Scanner(System.in);
System.out.println("Initiating SSN Server Storage Expanded");
System.out.println(" Type 'EXIT' at any moment to close the program \n");
boolean run = true;
while(run){
System.out.print("Enter your Social Security Number(XXX-XX-XXXX): ");
String ssnNumber = input.next();
if(ssnNumber.equalsIgnoreCase("EXIT")){
break;
/*System.out.print(SSNArrayExpandedObject.validateSSNNumber(ssnNumber));
return;*/
}else{
SSNArrayExpandedObject.addSSN(ssnNumber);
}
}
System.out.println("===============================================");
System.out.println("You have entered SSN Numbers are : ");
System.out.println(SSNArrayExpandedObject.getAllSsnNumber());
System.out.println("===============================================");
System.out.println("Program Ended Successfully");
}
}
and Output is :
Initiating SSN Server Storage Expanded
Type 'EXIT' at any moment to close the program
Enter your Social Security Number(XXX-XX-XXXX): 111-11-1111
Added Successfully
Enter your Social Security Number(XXX-XX-XXXX): 222-22-222
!Please use the format XXX-XX-XXXX!
Enter your Social Security Number(XXX-XX-XXXX): 111-11-1111
Duplicate Not Allow
Enter your Social Security Number(XXX-XX-XXXX): 333-33-333
!Please use the format XXX-XX-XXXX!
Enter your Social Security Number(XXX-XX-XXXX): 333-33-3333
Added Successfully
Enter your Social Security Number(XXX-XX-XXXX): EXIT
===============================================
You have entered SSN Numbers are :
[111-11-1111, 333-33-3333]
===============================================
Program Ended Successfully

public boolean validateSSNNumber(String SSNFormat) {
if (super.validateSSNNumber(SSNFormat)) {
/*
*Hashset add() - Returns true if this set did not already contain
*the specified element.
*If this set already contains the element, the call leaves the set
* unchanged and returns
*/
boolean duplicate = !uniqueSSNNum.add(SSNFormat);
return duplicate;
}
return false;
}
//To use HastSet it's better if you override equals and hashcode
//using the fields that you'll use for comparison equality
// generated using eclipse
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + arrayCount;
result = prime * result + Arrays.hashCode(ssnNumber);
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SSNArray other = (SSNArray) obj;
if (arrayCount != other.arrayCount)
return false;
if (!Arrays.equals(ssnNumber, other.ssnNumber))
return false;
return true;
}

Related

Refer to a method and check Input

I have created a method that checks if an Input is between the size of column in a csv File.
public static boolean isValidNumber(String uInput) {
Long convert = Long.parselong (uInput);
int convert2 = (int) convert;// Need to do this because of the JOptionPane
if(colmn.length > convert) {
System.out.println("The Column exists.");
}
else { System.out.println("The Column doesn't exists.");}
return true; }}
And in the main method i refer to the isValidNumber-Method
// some previous code
do { String userInput = JOptionPane.showInputDialog);
} while(isValidNumber(userInput));}
//next code
So i can't get out of the Loop even if the userInput is correct and exists in the csv-file. Can someone help me out?
Your isValidNumber always returns true and that's why you are not able to get out of the loop.
Try using below--
public static boolean isValidNumber(String uInput) {
Long convert = Long.parselong (uInput);
int convert2 = (int) convert;// Need to do this because of the JOptionPane
if(colmn.length > convert) {
System.out.println("The Column exists.");
return true;
}
else { System.out.println("The Column doesn't exists."); return false;}
}
Assuming that your issue is that anything you enter is valid, the problem lies within the isValidNumber method itself:
public static boolean isValidNumber(String uInput) {
Long convert = Long.parselong (uInput);
int convert2 = (int) convert;// Need to do this because of the JOptionPane
if(colmn.length > convert) {
System.out.println("The Column exists.");
}
else {
System.out.println("The Column doesn't exists.");
}
return true;
}
This will yield true regardless, what you need to do is to move your return statements. After printing, you will need to return true/false accordingly:
public static boolean isValidNumber(String uInput) {
Long convert = Long.parselong (uInput);
int convert2 = (int) convert;// Need to do this because of the JOptionPane
if(colmn.length > convert) {
System.out.println("The Column exists.");
return true;
}
else {
System.out.println("The Column doesn't exists.");
return false;
}
}
Alternatively:
public static boolean isValidNumber(String uInput) {
Long convert = Long.parselong (uInput);
int convert2 = (int) convert;// Need to do this because of the JOptionPane
if(colmn.length > convert) {
System.out.println("The Column exists.");
return true;
}
System.out.println("The Column doesn't exists.");
return false;
}

"Duplicate" entries in ArrayList?

i have this class thats going to fill a list with All employees that are pre made in an array. I can populate an ArrayList with employees but the only problem is that i get a few "Duplicate" entries, i use quotes cause they are not EXACTLY the same but they could share the same name or employee number but may not have the same hire year or salary ect.
heres the employee class :
public class Employee {
public String EmployeeName;
public String EmployeeNumber;
public int hireyear;
public double WeeklyEarning;
public Employee()
{
EmployeeName = null;
EmployeeNumber = null;
hireyear = 0;
WeeklyEarning = 0;
}
public static final String[] Empnum = new String[] {
"0001-A", "0002-B","0003-C","0004-D","0002-A",
"0003-B","0004-C","0005-D","0011-A", "0012-B",
"0013-C","0014-D","0121-A", "0122-B","0123-C",
"0321-A", "0312-B","1234-D","4321-C","1122-D"};
public static final String[] Ename = new String[] {
"Josh", "Alex", "Paul", "Jimmy", "Josh", "Gordan", "Neil", "Bob",
"Shiv", "James", "Jay", "Chris", "Michael", "Andrew", "Stuart",
"Dave","Benjamin","Dan","Brian","Michelle"};
public String getEmployeeName()
{
return this.EmployeeName;
}
public String getEmployeeNumber()
{
return this.EmployeeNumber;
}
public int gethireyear()
{
return this.hireyear;
}
public double getWeeklyEarning()
{
return this.WeeklyEarning;
}
public String setEmployeeName(String EName)
{
return this.EmployeeName = EName;
}
public String setEmployeeNumber(String ENumber)
{
return this.EmployeeNumber = ENumber;
}
public int setEmployeehireyear(int Ehireyear)
{
return this.hireyear = Ehireyear;
}
public double setEmployeeweeklyearning(double Eweeklyearning)
{
return this.WeeklyEarning = Eweeklyearning;
}
public String toString(){
String data = "\n Employee Name : " + EmployeeName + " \n Employee Number: " + EmployeeNumber + " \n Hire Year : " + hireyear + "\n Weekly Earnings : " + WeeklyEarning;
return data;
}
public boolean equals(Object o){
if(this == null){
return false;
}
if(this == o){
return true;
}
if(!(o instanceof Employee)){
return false;
}
Employee temp = (Employee) o;
if(this.getEmployeeName().equals(temp.getEmployeeName())){
return true;
}
if(this.getEmployeeNumber().equals(temp.getEmployeeNumber())){
return true;
}
if(this.gethireyear() == temp.gethireyear()){
return true;
}
if(this.getWeeklyEarning() == temp.getWeeklyEarning()){
return true;
}
return false;
}
}
Heres the generateList method that will populate the list:
public ArrayList<Employee> generateEmpList(){
empList = new ArrayList <Employee>();
Random empPicker = new Random();
for(int i = 0; i < 20; i++){
int id = empPicker.nextInt(20);
if(id < 12) // roll for production worker
{
//System.out.println("Adding Production Worker");
ProductionWorker temp = new ProductionWorker();
temp = temp.generateProductionWorker();
prodWorker = temp;
empList.add(prodWorker);
}
else //roll for Shift supervisor
{
//System.out.println("Adding Shift supervisor");
ShiftSupervisor supervisor = new ShiftSupervisor();
supervisor = supervisor.generateShiftSupervisor();
shiftWorker = supervisor;
empList.add(shiftWorker);
}
}
Iterator iterator = empList.iterator();
while (iterator.hasNext()) {
System.out.println("");
System.out.println(iterator.next());
}
return empList;
}
and also which could be helpful is the "generateProductionWorker()" and shiftSupervisor methods - to keep it short ill only post prod worker method cause they are basically the same:
public ProductionWorker generateProductionWorker(){
Random rng = new Random();
int numberOfEmployeeNames = Ename.length;
ProductionWorker tempPworker = new ProductionWorker();
String employeeName = Ename[rng.nextInt(numberOfEmployeeNames)];
tempPworker.setEmployeeName(employeeName);
int numberOfEmployeeNumbers = Empnum.length;
String employeeNumber = Empnum[rng.nextInt(numberOfEmployeeNumbers)];
tempPworker.setEmployeeNumber(employeeNumber);
int yearHired = rng.nextInt(35) + 1980;
tempPworker.setEmployeehireyear(yearHired);
double weeklySalary = rng.nextInt((100) * 100);
tempPworker.setEmployeeweeklyearning(weeklySalary);
int hourlyRate = rng.nextInt(20) + 10;
tempPworker.setHourlyRate(hourlyRate);
return tempPworker;
}
I'm sure I'm missing something trivial but any ideas why i get similar entries when i have a list of 20 names and numbers?
ex:
empname - josh
empnum - 0000-A
hireyear - 1994
salary - 40,000
empname - josh
empnum - 0000-A
hireyear - 1999
salary - 60,500
any advice would help, Thanks!
Look at the equals method in your Employee class. If their name are the same, you return true, which means these are equals. The same is for the other attributes. You must replace your if statements.
I agree with Georgi, you equals method is the culprit.
Currently it is returning true after the first if statement at the line that reads
if(this.getEmployeeName().equals(temp.getEmployeeName())){
return true;
}
Because it is a return statement it stops the method from continuing to the other statements. You might try this:
public boolean equals(Object o){
if(this == null){
return false;
}
if(this == o){
return true;
}
if(!(o instanceof Employee)){
return false;
}
//set all the elements in the array to false and change to true when true.
boolean [] doesItMatch = new boolean[4];
doesItMatch[0] = false;
doesItMatch[1] = false;
doesItMatch[2] = false;
doesItMatch[3] = false;
Employee temp = (Employee) o;
if(this.getEmployeeName().equals(temp.getEmployeeName())){
doesItMatch[0] = true;
}
if(this.getEmployeeNumber().equals(temp.getEmployeeNumber())){
doesItMatch[1] = true;
}
if(this.gethireyear() == temp.gethireyear()){
doesItMatch[2] = true;
}
if(this.getWeeklyEarning() == temp.getWeeklyEarning()){
doesItMatch[3] = true;
}
int check = 0;
//Now that you have checked all the values, check the array. Using a simple counter.
for(int i = 0; i < doesItMatch.length; i++){
if(doesItMatch[i]){
check++;
} else {
check--;
}
}
//The counter should be 4 when the if statements above are all true. Anything else is false.
if(check == 4){
return true;
} else {
return false;
}
}
This method now checks each of the attributes in the Employee class. (Name, Number, Hire year and so on. If you create more attributes to the class it is easy to add more elements to the array just be sure to set them to false.)
Hope this helps
This also would take a little maintenance if you expanded the Employee class so you might want to find a way to make it a little easier on yourself.

I get an error message as follows: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0

I get an error message as follows: Exception in thread "main"
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at emp.MainClass.main(MainClass.java:52)
Using the following code, how do I alleviate this problem?
public class MainClass {
//main class
public static void main(String[] args){
// variable
String input;
boolean salaryError = true;
boolean dependentError = true;
boolean nameError = true;
boolean charError = true;
Employee emp1 = new Employee();
displayDivider("EMPLOYEE INFORMATION");
do{
input = getInput(" First Name");
nameError = nameValidate(input);
if(!nameError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!nameError);
emp1.setfirstName(input);
do{
input = getInput(" Last Name");
nameError =nameValidate(input);
if(!nameError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!nameError);
emp1.setlastName(input);
do{
input = getInput(" Gender: M or F");
charError = characterChecker(input.charAt(0));
if(!charError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!charError);
char g = input.charAt(0);
emp1.setgender(g);// validates use of M or F for gender
do{
input = getInput(" number of dependents");
dependentError = integerChecker(input);
if(!dependentError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!dependentError);
emp1.setdependents(Integer.parseInt(input));
do{
input = getInput(" annual salary");
salaryError = doubleChecker(input);
if(!salaryError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
} while(!salaryError);
emp1.setannualSalary(Double.parseDouble(input));
emp1.displayEmployee();//displays data for emp1
Employee emp2 = new Employee("Speed","Racer",'M',1,500000.00);
displayDivider("EMPLOYEE INFORMATION");
emp2.displayEmployee();// displays data for emp2
terminateApplication(); //terminates application
System.exit(0);//exits program
}//end of main
// gets Input information
public static String getInput(String data)
{
String input = "";
input = javax.swing.JOptionPane.showInputDialog(null,"Enter your " + data);
return input;
}// end getInput information
// The display divider between employees
public static void displayDivider(String outputLab)
{
System.out.println("********" + outputLab + "********");
}// end display divider
// Terminates the application
public static void terminateApplication()
{ javax.swing.JOptionPane.showMessageDialog(null,"Thanks for the input!");
}// end terminateApplication
public static boolean doubleChecker(String inStr){
boolean outBool = true;
double tmpDbl = 0.0;
try{
tmpDbl = Double.parseDouble(inStr);
if(tmpDbl <= 0)
throw new IllegalArgumentException();
}
catch (Exception e){
outBool = false;
}
return outBool;
}
public static boolean integerChecker(String intStr){
boolean outBool = true;
int tmpInt = 0;
try{
tmpInt = Integer.parseInt(intStr);
if(tmpInt <= 0)
throw new IllegalArgumentException();
}
catch (Exception e){
outBool = false;
}
return outBool;
}
public static boolean nameValidate(String str){
for(char ch : str.toCharArray()){
if(!Character.isDigit(ch)){
return true;
}
}
return false;
}
public static boolean characterChecker(char gen){
boolean outBool = true;
try{
if(!( gen ==( 'M') || gen ==('F')))
throw new IllegalArgumentException();
}
catch (Exception e){
outBool = false;
}
return outBool;
}
}//end of Main Class
Your string is length 0. Make sure string.length() > 0 before accessing its elements. The problem is at the line the exception says the problem is on.
Better answer: are you using an IDE? If so, observe the line the exception tells you you have an error on. Set a breakpoint before that line, debug, and note the contents of the object on which the error happened (in this case the string). Then check the javadoc for the method that threw the exception to see if there is any problem calling that method on that string.
If you are not using an IDE, you will either need to use one or find a standalone debugger. Having a good debugger is a requirement of Java development.
This should save you a lot of SO questions going forward.
StringIndexOutofBoundsException means you're try to access the String using an index and the index is either negative or greater than the size of the string.
You're wrong in this part:
charError = characterChecker(input.charAt(0));
Because you're not check if the input length is 0.
Try to change that line to this:
charError = input != null && input.length() > 0 && characterChecker(input.charAt(0));

How do I check if a class' return of a method equals null?

In my program, I have a while loop that will display a list of shops and asks for an input, which corresponds with the shop ID. If the user enters an integer outside the array of shops, created with a Shop class, it will exit the loop and continue. Inside this loop is another while loop which calls the sellItem method of my Shop class below:
public Item sellItem()
{
displayItems();
int indexID = Shop.getInput();
if (indexID <= -1 || indexID >= wares.length)
{
System.out.println("Null"); // Testing purposes
return null;
}
else
{
return wares[indexID];
}
}
private void displayItems()
{
System.out.println("Name\t\t\t\tWeight\t\t\t\tPrice");
System.out.println("0. Return to Shops");
for(int i = 0; i < wares.length; i++)
{
System.out.print(i + 1 + ". ");
System.out.println(wares[i].getName() + "\t\t\t\t" + wares[i].getWeight() + "\t\t\t\t" + wares[i].getPrice());
}
}
private static int getInput()
{
Scanner scanInput = new Scanner(System.in);
int itemID = scanInput.nextInt();
int indexID = itemID - 1;
return indexID;
}
The while loop in my main class method is as follows:
boolean exitAllShops = true;
while(exitAllShops)
{
System.out.println("Where would you like to go?\nEnter the number which corresponds with the shop.\n1. Pete's Produce\n2. Moore's Meats\n3. Howards Hunting\n4. Foster's Farming\n5. Leighton's Liquor\n6. Carter's Clothing\n7. Hill's Household Products\n8. Lewis' Livery, Animals, and Wagon supplies\n9. Dr. Miller's Medicine\n10. Leave Shops (YOU WILL NOT BE ABLE TO RETURN)");
int shopInput = scan.nextInt();
if(shopInput >= 1 && shopInput <= allShops.length)
{
boolean leaveShop = true;
while(leaveShop)
{
allShops[shopInput - 1].sellItem();
if(allShops == null)
{
System.out.println("still null"); // Testing purposes
leaveShop = false;
}
}
}
else
{
System.out.println("Are you sure you want to leave?\n1. Yes\n2. No");
int confirm = scan.nextInt();
if(confirm == 1)
{
exitAllShops = false;
}
}
The problem is here:
boolean leaveShop = true;
while(leaveShop)
{
allShops[shopInput - 1].sellItem();
if(allShops == null)
{
System.out.println("still null"); // Testing purposes
leaveShop = false;
}
}
No matter what I do, I can't get "still null" to print to confirm that I'm correctly calling the return statement of the method sellItem of the class Shop. What am I doing wrong?
After calling allShops[...].sellItem(), allShops is still a valid array reference -- there's no way it could be null! You probably want to test the return value from sellItem:
if(allShops[shopInput-1].sellItem() == null)

How to obscure Scanner input text? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Hide input on command line
I'm making a password security checker program and my question is odd in that my program runs just fine. What I'm wondering is whether there is any way of making text entered to the console appear as it would in a password field. i.e the word entered will appear as "****" BEFORE the user presses the return key.
I am aware that JFrame has a JPasswordField method but I don't think that helps me when in just using Scanner.
Here is my code:
import java.util.Scanner;
public class SecurityCheckerMain {
static String enteredPassword;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter your password: ");
enteredPassword = input.nextLine();
Checker tc = new Checker(enteredPassword);
tc.checkSecurity();
}
}
public class Checker {
//number of chars : the Higher the Better("password must be greater than 8 chars"){done}
//combination of uppercase and lowercase{done}
//contains numbers{done}
//non repeated characters (every char is different ascii char){done}
//is not a consecutive password ie 123456789 or 987654321{done}
//is not blank ("[space]"){done}
int pLength;
final int MAX_STRENGTH = 10;
int pStrength = 0;
String pass;
public Checker(String pwd){
pass = pwd;
pLength = pwd.length();
}
public void checkSecurity(){
if(pass.isEmpty()){
System.out.println("Password Field is Empty! Password is Very Insecure.");
}
if(pLength >= 8){
pStrength++;
if(pLength >= 12){
pStrength++;
if(pLength >= 16){
pStrength++;
}
}
}
if(hasUpperCase(pass) && hasLowerCase(pass)){
pStrength+=2;
}
if(containsNumbers(pass)){
pStrength+=2;
}
if(hasNoRepeats(pass)){
pStrength+=2;
}
if(!containsConsecutiveNums(pass)){
pStrength++;
}
System.out.println("Your password strength is rated at " + pStrength +"/" + MAX_STRENGTH);
}
//Component Methods
public boolean hasUpperCase(String str){
for(int i = 0; i<pLength; i++){
if(Character.isUpperCase(str.charAt(i))){
return true;
}
}
return false;
}
public boolean hasLowerCase(String str){
for(int i = 0; i<pLength; i++){
if(Character.isUpperCase(str.charAt(i))){
return true;
}
}
return false;
}
public boolean containsNumbers(String str){
for(int i = 0; i<pLength; i++){
if(Character.isDigit(str.charAt(i))){
return true;
}
}
return false;
}
public boolean hasNoRepeats(String str){
for(int i = 0; i<pLength; i++)
if(containsChar(str, str.charAt(i))){
return false;
}
return true;
}
public boolean containsChar(String s, char search) {
if (s.length() == 0)
return false;
else
return s.charAt(0) == search || containsChar(s.substring(1), search);
}
public boolean containsConsecutiveNums(String str){
for(int i = 0; i<pLength; i++){
if(Character.isDigit(str.charAt(i))){
if(str.charAt(i)-1 == str.charAt(i-1) || str.charAt(i)+1 == str.charAt(i+1)){
return true;
}
}
}
return false;
}
}
You can use Console.readPassword instead.
readPassword(String fmt, Object... args)
Provides a formatted prompt, then reads a password or passphrase from
the console with echoing disabled
public class SecurityCheckerMain {
static String enteredPassword;
public static void main(String[] args) {
Console console = System.console();
enteredPassword =
new String(console.readPassword("Please enter your password: "));
Checker tc = new Checker(enteredPassword);
tc.checkSecurity();
}

Categories