Validating username part of email address - java

Consider an email id which is being provided in the starter class in the main method.
String emailId = "Hellooo_hell#gmail.com";
THE PROBLEM DESCRIPTION:
The overall length of the emailId should be >3 and <20.
The emailId must include "#" followed by a minimum of 1 and maximum of 2 "." characters.
The substring before "#" must contain a combination of Upper Case, Lower Case and "_"(underscore) symbols.
The first letter of the emailId must be in Upper Case.
If all the above conditions are valid it must display a success message or should display an appropriate ERROR message.
This is the code which does not work how I want it to.
public class EmailCheck {
String emailId;
public void setEmailId(String emailId){
this.emailId=emailId;
}
public String getEmailId(){
return emailId;
}
public static void main(String[] args) {
EmailCheck em = new EmailCheck();
em.setEmailId("Hell_ooo#gmail.com");
String email = em.getEmailId();
int length = email.length();
boolean flag1 = false;
boolean flag2 = false;
boolean flag3 = false;
boolean flag4 = false;
boolean flag5 = false;
boolean flag6 = false;
boolean flag7 = false;
int count = 0;
int count2 = 0;
//Condition 1
if((length>3 && length<20)== true)
flag1 = true;
else
flag1 = false;
//Condition 2
for(int i=0;i<length;i++){
if(email.charAt(i)=='#'){
flag2 = true;
for(int j=i+1;j<length;j++){
if(email.charAt(j)=='.')
{
flag3 = true;
count=++count;
}
else
flag3 = false;
}
if(count<1 || count>2)
{
flag4 = false;
//System.out.println("Invalid position of special characters");
}
else
flag4 = true;
}
else
flag2 = false;
}
//Condition 3
if(email.matches("[a-zA-Z_]+#.*"))
flag5 = true;
else
flag5 = false;
//Condition4
if(Character.isUpperCase(email.charAt(0))==true)
flag6 = true;
else
flag6=false;
if(flag1==true && flag2==true && flag3==true && flag4==true && flag5==true &&flag6==true)
System.out.println("Email ID is valid");
else{
if(flag1==false)
System.out.println("Inavlid length of Email ID");
if(flag2==false||flag3==false||flag4==false)
System.out.println("Invalid Position of Special Characters");
if(flag5==false)
System.out.println("Invalid combination for username");
if(flag6==false)
System.out.println("Invalid case of first letter");
}
}
}

You can use the matches method from the String class
if(emailId.matches("[a-zA-Z_]+#.*")) {
// ok matches;
} else {
// does not match
}

Related

Error: Password validation "reached end of file while parsing"

//This program validates passwords, must have 8 characters, 1 upper, 1 lower, 1 digit, once the password is validated the program should include a method that asks the user to reenter the password to make sure they match if the passwords does not match the program will ask the user to reenter the password until they do. I'm getting a "reached end of file while parsing" error.
Please help!
import java.util.Scanner;
public class PassChecker2 {
public static void main (String [] args) {
String inputPassword;
Scanner input = new Scanner(System.in);
System.out.println(" Please enter your Password:");
inputPassword = input.next();
System.out.println(passminChecker(inputPassword));
System.out.println("");
main(args);
}
public static boolean passminChecker(String password)
{
if (password.length () > 7)
{
if(passminChecker(password))
{
return true;
}
else
{
return false;
}
}
else
{
System.out.println("Password must be at least 8 characters long.");
return false;
}
}
public static boolean checkerPass(String password)
{
boolean hasUpperCase = false;
boolean hasLowerCase = false;
boolean hasDigit = false;
char c;
for (int i = 0; i < password.length(); i++)
{
c = password.charAt(i);
if(Character.isUpperCase(c))
{
hasUpperCase = true;
}
else if(Character.isLowerCase(c))
{
hasLowerCase = true;
}
else if(Character.isDigit(c))
{
hasDigit = false;
}
if(hasUpperCase && hasLowerCase && hasDigit)
{
return true;
}
else
{
System.out.println("Password is invalid must meet all requiremennts.");
return false;
}
}
}
That error most often occurs when you have an unclosed block in your code. You're missing a } at the end of the class. This will be easier to spot yourself if you're more consistent with where you put your opening and closing curly brackets. Put them either all on their own line, or all on the same line as the code that starts the block.
import java.util.Scanner;
public class PassChecker2 {
public static void main (String [] args) {
String inputPassword;
Scanner input = new Scanner(System.in);
System.out.println(" Please enter your Password:");
inputPassword = input.next();
System.out.println(passminChecker(inputPassword));
System.out.println("");
main(args);
}
public static boolean passminChecker(String password) {
if (password.length () > 7) {
if(passminChecker(password)) {
return true;
} else {
return false;
}
} else {
System.out.println("Password must be at least 8 characters long.");
return false;
}
}
public static boolean checkerPass(String password) {
boolean hasUpperCase = false;
boolean hasLowerCase = false;
boolean hasDigit = false;
char c;
for (int i = 0; i < password.length(); i++) {
c = password.charAt(i);
if(Character.isUpperCase(c)) {
hasUpperCase = true;
} else if(Character.isLowerCase(c)) {
hasLowerCase = true;
} else if(Character.isDigit(c)) {
hasDigit = false;
}
if(hasUpperCase && hasLowerCase && hasDigit) {
return true;
} else {
System.out.println("Password is invalid must meet all requiremennts.");
return false;
}
}
}
}//this is the one that was missing

I have java code for entering a password following certain rules

Some websites impose certain rules for passwords. I am writing a method that checks whether a string is a valid password.
The rules of the password are:
A password must have at least eight characters
A password consists of only letters and digits
A password must contain at least two digits
I figured out most of the code, I think I got some concept correct just right now no matter what password I enter it prints out "invalid password"..I tried running the debugger but got really confused.
This is my code below:
import java.util.Scanner;
public class practice {
public static void main(String[] args) {
System.out.print("Enter a password");
Scanner input = new Scanner(System.in);
String password = input.nextLine();
boolean isCorrect = checkPassword(password);
if(isCorrect)
{
System.out.println("Valid Password");
}
else
{
System.out.println("Invalid Password");
}
}
//this method checks the password
public static boolean checkPassword(String password)
{
int countDigit = 0;
if (password.length() >=8 ){
return false;
}
for(int i = 0; i <password.length(); i++)
{
if(!(Character.isLetterOrDigit(password.charAt(i))))
{
return false;
}
}
for(int i = 0; i<password.length(); i++){
if((Character.isDigit(password.charAt(i)))){
countDigit = countDigit + 1;
}
}
if (countDigit >= 2){
return true;
}
else
return false;
}
}
The error is here:
if (password.length() >=8 ){
return false;
}
Here you say that if password is longer than or equal to 8 characters, the password is invalid, which is the complete opposite of the requirement. Change it to:
if (password.length() < 8 ){
return false;
}
Also, you can reduce the number of for loops to make the code faster. You can count the number of digits and check isLetterOrDigit in the same for loop:
int countDigit = 0;
if (password.length() < 8) {
return false;
}
for (int i = 0; i < password.length(); i++) {
if (!(Character.isLetterOrDigit(password.charAt(i)))) {
return false;
}
if ((Character.isDigit(password.charAt(i)))) {
countDigit = countDigit + 1;
}
}
if (countDigit >= 2) {
return true;
} else {
return false;
}

Using stack to check equal number of letters and digits in password

I have to write a program to check a password whereby the password should
should be at least 8 characters long
contain only letters and digits(special characters)
contain an equal number of letters and digits
The program should check if it is valid and displays an appropriate message.
Also, only the stack class should be used as the data structure.
Here is what I have come up with so far:
public class dsa_1c {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc= new Scanner(System.in);
String pass;
System.out.println("Enter a password");
pass= sc.nextLine();
if(checkPass(pass)){
System.out.println("Valid Password");
}
else{
System.out.println("Invalid Password");
}
}
public static boolean checkPass(String password){
Stack<Character> stack= new Stack<Character>();
int count1=0, count2=0;
if(password.length()<8){
return false;
}
else{
for(int i=0; i<password.length();i++){
char c= password.charAt(i);
if (!Character.isLetterOrDigit(c)){
return false;}
if(Character.isLetterOrDigit(c)){
stack.push(c);
}
char top= stack.peek();
if(Character.isLetter(top)){
count1++;
stack.pop();
}
else if(Character.isDigit(top)){
count2++;
stack.pop();
}
if(count1==count2){
return true;
}
if(!stack.isEmpty()){
return false;
}
}
}
return true;
}
}
The program when run displays "Valid Password" for any password I type in with more than 8 characters and with no special characters.
It's this part which is apparently the issue
if(count1==count2){
return true;}
because when I change it
if(count1!=count2)
return false; }
it returns Invalid Password for any valid ones.
It's return true in the end that causes an issue. Instead of comparing two counts and returning the values, you can just use return count1 == count2;. Below is an example:
public static boolean checkPass(String password) {
Stack<Character> stack = new Stack<Character>();
int count1 = 0, count2 = 0;
if (password.length() < 8) {
return false;
} else {
for (int i = 0; i < password.length(); i++) {
char c = password.charAt(i);
if (!Character.isLetterOrDigit(c)) {
return false;
} else {
stack.push(c);
}
}
while(!stack.isEmpty()){
char c = stack.pop();
if(Character.isLetter(c)){
count1++;
}else{
count2++;
}
}
return count1 == count2;
}
}
Using a stack seems like overkill to me - it's enough to iterate over the characters, count the digits and the letters, and make sure they have the same number:
private static boolean isValidPassword(String password) {
int letterCount = 0;
int digitCount = ;
for (int i = 0; i < password.length(); ++i) {
char c = password.charAt(i);
if (Character.isLetter(c)) {
++letterCount;
} else if (Character.isDigit(c)) {
++digitCount;
} else {
return false;
}
}
return (letterCount + digitCount) >= 8 &&
letterCount == digitCount;
}
Assuming this is an exercise just to manipulate a stack, here is my 2 cents:
public class dsa_1c {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a password");
String pass = sc.nextLine();
if (checkPass(pass)) {
System.out.println("Valid Password");
} else {
System.out.println("Invalid Password");
}
}
private static boolean checkPass(String pass) {
boolean result = false;
if (pass.length() == 8) {
Stack stack = new Stack();
for (char current : pass.toCharArray()) {
if (stack.isEmpty()) {
stack.push(current);
continue;
}
char previousChar = stack.pop();
if (sameType(current, previousChar)) {
stack.push(previousChar);
stack.push(current);
}
}
if (stack.isEmpty()) {
result = true;
}
}
return result;
}
public static boolean sameType(char current, char previousChar) {
boolean result = false;
if (Character.isAlphabetic(current) && Character.isAlphabetic(previousChar)) {
result = true;
}
else if (Character.isDigit(current) && Character.isDigit(previousChar)) {
result = true;
}
return result;
}
static class Stack extends ArrayList {
public static final char NULL_CHARACTER = 0x0;
public void push(Character letter) {
add(letter);
}
public Character pop() {
Character result = NULL_CHARACTER;
if (!isEmpty()) {
result = (Character)remove(size()-1);
}
return result;
}
}
}

Password Always Returning Invalid

Here's my code:
import java.util.*;
import java.lang.String;
import java.lang.Character;
public class password {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter a Password: ");
String password = input.next();
if (isValid(password))
{
System.out.println("valid Password");
System.out.print("Please verify your Password: ");
String vrfypassword = input.next();
if (vrfypassword.equals(password)){
System.out.println("Password Verfied");
} else {
System.out.println("Unable to verify password");
}
}
else
{
System.out.println("InValid Password");
}
}
public static boolean isValid(String password) {
if (password.length() < 10) {
return false;
} else {
char c;
int count = 1;
for (int i = 0; i < password.length() - 1; i++) {
c = password.charAt(i);
if (!Character.isLetterOrDigit(c)) {
return false;
} else if (!Character.isDigit(c))
return false;
}
}
return true;
}
}
Im not sure why but it always is returning a invalid password even when i use a password that "should" go through. The requirements are less than 10 characters, one letter, and one number. Is there anything im doing wrong?
if (password.length() < 10) { return false; }
The requirements are less than 10 characters
Your requirement isn't reflected in the code.
Invert the statement:
if (password.length() > 10) { return false; }
And this:
if (!Character.isDigit(c)) { return false; }
curses at this:
The requirements are less than 10 characters, one letter, and one number
Just leave this check away.
Try this:
public static boolean isValid(String password) {
if (password.length() < 10) {
return false;
} else {
char c;
int digitCount, letterCount;
for (int i = 0; i < password.length(); i++) {
c = password.charAt(i);
if (Character.isLetter(c)) {
letterCount++;
} else if (Character.isDigit(c))
digitCount++;
}
if(digitCount < 1 || lettercount < 1) { return false; }
}
return true;
}
The problem is that, whenever there is a letter in the password, it will return false, because of this clause:
...
else if (!Character.isDigit(c)){
System.out.println("H2");
return false;
}
Check if you're reading \r or \n from the input.
This is neither digit, nor letter and might break things.
Also is this correct:
i < password.length() - 1
Shouldn't it be:
i < password.length()
change this
if (!Character.isLetterOrDigit(c)) {
return false;
} else if (!Character.isDigit(c))
return false;
}
to
if (!Character.isLetterOrDigit(c)) {
return false;
}

Password Verifier Issue

Edit: This is probably very bad code in the PasswordVerifier.Java
I'm doing a password verifier that checks if the entered password is at least 6 characters long, has an Uppercase letter, lowercase letter, and a digit.
I think I have the logistics of it somewhat correct, but for some reason my program isn't going to the next prompt. It asks me for my password and then hangs up and doesn't tell me whether my password is valid or not. I'm thinking that my for loops are correct so I don't know what my issue is.
PasswordVerifier.Java
import java.util.*;
public class PasswordVerifier{
//field
private static int MIN_PASSWORD_LENGTH = 6;
//methods
public static boolean isValid(String str){
boolean valid = false;
PasswordVerifier pass = new PasswordVerifier();
if(pass.hasUpperCase(str)|| pass.hasLowerCase(str) || pass.hasDigit(str)){
valid = true;
}
if (str.length() < 6){
valid = false;
}
return valid;
}
//UpperCase Boolean check
private boolean hasUpperCase(String str){
boolean valid = false;
int i = 0;
while (i < str.length()){
if (Character.isUpperCase(str.charAt(i)))
valid = true;
}
i++;
return valid;
}
//Lowercase Boolean Check
private boolean hasLowerCase(String str){
boolean valid = false;
int i = 0;
while (i < str.length()){
if (Character.isLowerCase(str.charAt(i)))
valid = true;
}
i++;
return valid;
}
//Number boolean check
private boolean hasDigit(String str){
boolean valid = false;
int i = 0;
while (i < str.length()){
if ((Character.isDigit(str.charAt(i))))
valid = true;
}
i++;
return valid;
}
}
PasswordDemo.Java
import javax.swing.JOptionPane;
public class PasswordDemo{
public static void main(String[] args){
String input; //To hold the user's input
input = JOptionPane.showInputDialog("Enter a Password");
if (PasswordVerifier.isValid(input)){
JOptionPane.showMessageDialog(null, "Valid Password");
}
else{
JOptionPane.showMessageDialog(null, "invalid Password, try again.");
}
}
}
Your while loops never increment i, because you placed i++ just past the end of the loop. The result is an infinite loop and the "hanging" you describe.
E.g. replace
while (i < str.length()){
if (Character.isUpperCase(str.charAt(i)))
{
valid = true;
// Added break because we found an uppercase letter already.
break;
}
i++; // Inside the while loop.
}
You'll need to make a similar change to each of your while loops.
Additionally, if you want to enforce all 3 provisions, don't use the logical-OR operator ||, use logical-and, &&:
if (pass.hasUpperCase(str) && pass.hasLowerCase(str) && pass.hasDigit(str)) {
valid = true;
}
That will make sure that the password has an uppercase letter and it has a lowercase letter and it has a digit.
I think your problem is that you are counting i++ outside the while loop.
Put it in the while like this:
private boolean hasUpperCase(String str){
boolean valid = false;
int i = 0;
while (i < str.length()){
if (Character.isUpperCase(str.charAt(i)))
valid = true;
i++;
}
return valid;
}
This is the problem in every while loop you got.
Right now you're making three passes through the password in order to verify the three character conditions - you can condense this down to one pass. In addition, you're checking the password's length last - you should check this first, as it's the fastest condition to verify.
public static boolean isValid(String str) {
if(str.length() < 6) return false;
int i = 0;
boolean hasDigit = false;
boolean hasLower = false;
boolean hasUpper = false;
while(i < str.length() && !hasDigit && !hasLower && !hasUpper) {
if(Character.isDigit(str.charAt(i))) {
hasDigit = true;
} else if(Character.isLowerCase(str.charAt(i))) {
hasLower = true;
} else if(Character.isUpperCase(str.charAt(i))) {
hasUpper = true;
}
i++;
}
return hasDigit && hasUpper && hasLower;
}
In your case the performance gain is probably negligible, but bear this in mind for the future when you may be dealing with more than three conditions and a string (or whatever) with a length much greater than six.

Categories

Resources