Java email validation (No regex allowed) - java

I need to write an email validation script. It needs to take the email typed in from the user and verify is certain criteria are met and give a true/false. Regex is NOT allowed.
//This is my scanner:
Scanner isValidEmail = new Scanner(System.in);
System.out.print("Please enter your email: ");
String email = isValidEmail.nextLine();
I now need to check using various methods is it has letters, numbers, underscore, only 1 #, etc.
I have written booleans to verify those (examples):
//methos isValidPrefixChar to verify character
public static boolean isValidPrefixChar(char a) {
if (isAlphanumeric(a) || a == '-' || a == '_' || a == '.') {
return true;
} else {
return false;
}
}
//method getDomain() that takes as input a String representing a possible email address.
public static String getDomain(String possibleEmail) {
int i;
for (i = 0; i < possibleEmail.length(); i++) {
if (possibleEmail.charAt(i) == '#') {
break;
}
}
//use a loop to have the character from second half
String domain = "";
int k = i + 1;
while (k < possibleEmail.length()) {
domain = domain + possibleEmail.charAt(k);
k++;
}
return domain;
}
And I have some code that doesn't yet work...
However, I need help in getting the email the user typed in to be the string that gets verified. How do I get the code to check my 'isValidEmail' for these requirements?
EDIT:
Unfortunately, I need to validate each method individually, not as a whole. This doesn't work either because I'm verifying chars in a string.
import java.util.Scanner;
public class Main {
public static void main (String[] args) {
Scanner isValidEmail = new Scanner(System.in);
System.out.print("Please enter your email: ");
String email = isValidEmail.nextLine();
public static boolean isAlphanumeric(String email) {
if (email >= 'a' && email <= 'z' || email >= '0' && email <= '9' || s >= 'A' && email <= 'Z') {
return true;
}
return false;
}
}
}
And this for some reason does not work either, which i thought would work!
public static void main(String[] args) {
Scanner isValidEmail = new Scanner(System.in);
String email = isValidEmail.nextLine();
isAlphaNumeric();
}
public static boolean isAlphaNumeric(String email) {
for (int i = 0; i < email.length(); i++) {
char s = email.charAt(i);
if (s >= 'a' && s <= 'z' || s >= '0' && s <= '9' || s >= 'A' && s <= 'Z')
return false;
}
return true;
}
Etc, etc, per method I need to check against?

I had the simple idea to just replace alphanumeric characters by an 'x', and then check if the remaining pattern matches "x#x".
import java.util.Scanner;
class Main {
private static String alphanumericChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.";
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter your email: ");
String email = scanner.nextLine();
boolean isValidEmail = isEmail(email);
System.out.println(isValidEmail ? "Thank you." : "This is not a valid email.");
}
public static boolean isEmail(String str) {
String pattern = "";
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (isAlphanumeric(c)) {
if (pattern.length() == 0 || pattern.charAt(pattern.length() - 1) != 'x') {
pattern += "x"; // add an x as marker for an alphanumeric string.
}
} else {
pattern += c; // add not matching character
}
}
return pattern.equals("x#x"); // check if pattern matches your email-pattern
}
public static boolean isAlphanumeric(char c) {
boolean found = false;
for (int i = 0; i < alphanumericChars.length(); i++) {
if (alphanumericChars.charAt(i) == c) {
found = true;
break;
}
}
return found;
}
}

Related

Valid Username without Regex

The Question is to check a valid username:
Conditions are:
1.The username consists of 8 to 30 characters inclusive. If the username consists of less than 8 or greater than 30 characters, then it is an invalid username.
2.The username can only contain alphanumeric characters and underscores (_). Alphanumeric characters describe the character set consisting of lowercase characters [a-z], uppercase characters [A-Z], and digits [0-9].
3.The first character of the username must be an alphabetic character, i.e., either lowercase character [a-z] or uppercase character [A-Z].
Sample Input:
8
Julia
Samantha
Samantha_21
1Samantha
Samantha?10_2A
JuliaZ007
Julia#007
_Julia007
Sample Output:
Invalid
Valid
Valid
Invalid
Invalid
Valid
Invalid
Invalid
I am getting wrong output to some cases.
For Input: JuliaZ007 , I should get Valid but getting Invalid. Remaining are correct.
Can I know what's wrong in the code.
https://www.hackerrank.com/challenges/valid-username-checker/problem?isFullScreen=false
import java.io.*;
import java.util.*;
public class Solution {
private static final Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
int flag=1;
int n = Integer.parseInt(scan.nextLine());
while (n-- != 0) {
String userName = scan.nextLine();
char a[] = userName.toCharArray();
String specialCharactersString = "!##$%&*()'+,-./:;<=>?[]^`{|}";
for (int i=0;i<userName.length();i++)
{
char ch = userName.charAt(i);
if(specialCharactersString.contains(Character.toString(ch)) && Character.isLetterOrDigit(ch)==false)
{
flag=0;
}
}
if (userName.length()>=8 && userName.length()<=30 && Character.isLetter(a[0])==true && flag==1) {
System.out.println("Valid");
} else {
System.out.println("InValid");
}
}
}
}
With Regex
In your case regular expression is most appropriate:
import java.util.Scanner;
import java.util.regex.Pattern;
public class Solution {
private static final Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
final String regex = "^[a-zA-Z][\\w_]{7,29}$";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
int n = Integer.parseInt(scan.nextLine());
while (n-- != 0) {
String userName = scan.nextLine();
if (pattern.matcher(userName).matches())
System.out.println("Valid");
else
System.out.println("InValid");
}
}
}
Without Regex
import java.util.Scanner;
public class Solution {
private static final Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
int n = Integer.parseInt(scan.nextLine());
while (n-- != 0) {
String userName = scan.nextLine();
if (isValid(userName))
System.out.println("Valid");
else
System.out.println("InValid");
}
}
public static boolean isValid(String userName) {
if (!Character.isAlphabetic(userName.charAt(0))
|| userName.length() < 8
|| userName.length() > 30)
return false;
for (char c : userName.toCharArray()) {
if (!Character.isLetterOrDigit(c) && c != '_')
return false;
}
return true;
}
}
Explain what causes the problem in the program
Your problem is caused by the flag.
Before JuliaZ007, you have the name Samantha?10_2A, but this name sets the flag to 0.
And when you are in the JuliaZ007, the flag is always 0 and you get a InValid.
To correct this problem, you can reset flag to 1 on each new name.
For this, you can simply move the int flag = 1 in the while.
Example :
import java.io.*;
import java.util.*;
public class Solution {
private static final Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
int n = Integer.parseInt(scan.nextLine());
while (n-- != 0) {
int flag = 1;
String userName = scan.nextLine();
char a[] = userName.toCharArray();
String specialCharactersString = "!##$%&*()'+,-./:;<=>?[]^`{|}";
for (int i = 0; i < userName.length(); i++) {
char ch = userName.charAt(i);
if (specialCharactersString.contains(Character.toString(ch))
&& Character.isLetterOrDigit(ch) == false) {
flag = 0;
}
}
if (userName.length() >= 8 && userName.length() <= 30 && Character.isLetter(a[0]) == true && flag == 1) {
System.out.println("Valid");
} else {
System.out.println("InValid");
}
}
}
}
The username consists of 8 to 30 characters inclusive. If the username consists of less than 8 or greater than 30 characters, then it is an invalid username.
boolean valid = true;
if (userName.length() < 8 || userName.length() > 30) {
valid = false;
}
The username can only contain alphanumeric characters and underscores
if (valid) {
for (int i = 0; i < userName.length(); i++) {
boolean temp = c
Character c = userName.charAt(i);
valid = Character.isLetterOrDigit(c);
// before invalidating, check to see if it is an underscore
if (!valid) {
valid = c == '_';
if (!valid)
break;
}
}
}
The first character of the username must be an alphabetic character
if (valid) {
valid = Character.isLetter(userName.charAt(0));
}
Once you execute all validation steps, simply return valid;. On a side note, you can check the rule of the first character while looping to check the validity of the remaining character. I just did separate checks for clarity and for separating all three requirements for validation.
LASTLY, I want to point out this is most likely NOT the most optimal solution for non-regex. However, I broke it down in these steps because I feel strongly that as a beginner developer, you should attack problems in this manner: first break down the problem into individual, smaller problems. Then, come up to the solution of each independently, and lastly, integrate the smaller solutions into the final product.
Note that methods in class java.lang.Character, such as isLetterOrDigit, will check for characters (or digits) in any language.
Since your question stipulates that the digits must be those commonly referred to as arabic numerals and the letters must be those in the English alphabet, the below code uses the unicode code points of each character in the user-entered userName.
import java.util.Scanner;
public class Solution {
private static final Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
String result;
int n = Integer.parseInt(scan.nextLine());
while (n-- != 0) {
result = "invalid";
String userName = scan.nextLine();
int len = userName.length();
if (len >= 8 && len <= 30) {
char[] letters = userName.toCharArray();
if ((letters[0] >= 65 && letters[0] <= 90) || (letters[0] >= 97 && letters[0] <= 122)) {
int i = 1;
for (; i < len; i++) {
if ((letters[i] >= 48 && letters[i] <= 57) ||
(letters[i] >= 65 && letters[i] <= 90) ||
(letters[i] >= 97 && letters[0] <= 122) ||
(letters[i] == 95)) {
continue;
}
break;
}
if (i == len) {
result = "valid";
}
}
}
System.out.println(result);
}
}
}
Edit
Just for the sake of it, here is a solution that uses the stream API.
import java.util.Scanner;
public class Solution {
private static final Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
String result;
int n = Integer.parseInt(scan.nextLine());
while (n-- != 0) {
result = "invalid";
String userName = scan.nextLine();
int len = userName.length();
if (len >= 8 && len <= 30) {
char letter = userName.charAt(0);
if ((letter >= 65 && letter <= 90) || (letter >= 97 && letter <= 122)) {
if (userName.chars()
.skip(1L)
.allMatch(c -> (c >= 48 && c <= 57) || // c is a digit
(c >= 65 && c <= 90) || // c is uppercase letter
(c >= 97 && c <= 122) || // c is lowercase letter
(c == 95))) { // c is underscore
result = "valid";
}
}
}
System.out.println(result);
}
}
}

Creating a password with only numbers and digits using for loops

I am making a program that takes a string from a user to create a password. However, this password needs to be at least 8 characters or more, and it can only include letters(uppercase and lowercase) and digits. I already did this, however, when I enter in the user input a blank space(ex: "pass word") or a special symbol such as "%" or "&", the method still returns the value true, making the password valid when it shouldn't return this, how do I correct this?
import java.util.Scanner;
public class Password
{
public static void main(String[] args)
{
System.out.println("Enter your password");
Scanner input = new Scanner(System.in);
String pass = input.nextLine();
System.out.println("Is the password valid? " + passwordCheck(pass));
}
public static boolean passwordCheck(String password)
{
boolean pass = false;
for(int i=0; i < password.length(); i++)
{
char c = password.charAt(i);
if(password.length() >= 8)
{
if(c >= 48 && c <= 57)
{
pass = true;
}
else if(c>= 97 && c<= 122)
{
pass = true;
}
else if(c>=65 && c<=90)
{
pass = true;
}
else if(c == 32)
{
pass = false;
}
}
}
return pass;
}
}
you need to break out of the loop once it encounters a space or any other special character.
import java.util.Scanner;
public class Password
{
public static void main(String[] args)
{
System.out.println("Enter your password");
Scanner input = new Scanner(System.in);
String pass = input.nextLine();
System.out.println("Is the password valid? " + passwordCheck(pass));
}
public static boolean passwordCheck(String password)
{
boolean pass = false;
for(int i=0; i < password.length(); i++)
{
char c = password.charAt(i);
if(password.length() >= 8)
{
// also you can directly mention the character instead of looking for its respective ASCII value
if(c >= '0' && c <= '9')
{
pass = true;
}
else if(c>= 'a' && c<= 'z')
{
pass = true;
}
else if(c>='A' && c<='Z')
{
pass = true;
}
else // loop will break if it encounters a space or any other
special character
{
pass = false;
break;
}
}
}
return pass;
}
}

What is wrong with this Vowel question? Out of index

I'm doing a homework task that is:
Find a unique vowel in the string that is preceded by a consonant, and this consonant is preceded by a vowel.
Example: "eeaaAOEacafu"
Result is: u
What i already did:
Main.class
public class Principal {
public static void main(String[] args) {
// TODO Auto-generated method stub
Stream str = new Stream();
str.setText("eeaaAOEacafu");
System.out.println(str.returnChar(str.getVowel()));
}
Stream.class
public class Stream {
String text;
char vowel;
public String getText() {
return texto;
}
public void setText(String text) {
this.text = text;
}
public char getVowel() {
return vowel;
}
public void setVowel(char vowel) {
this.vowel = vowel;
}
public boolean isVowel(String str) {
str = str.toLowerCase();
for(int i=0; i<str.length(); i++) {
char c = str.charAt(i);
if(c=='a' || c=='e' || c=='i' || c=='o'|| c=='u') {
return true;
} else {
return false;
}
}
return false;
}
public char returnChar(String str) {
char last;
char next;
char result = '0';
int j=1;
for(int i=0; i<str.length(); i++) {
last = str.charAt(i-1);
next = str.charAt(i+1);
j++;
if(!vogal(str.charAt(i))) {
if(vogal(last) && vogal(next)) {
result = next;
}
}
}
this.setVowel(result);
return result;
} }
This returns: String index out of range: -1
This j=1, was to fix this -1 out of range. It fix but i got new one: out of range 11 because of the next.
The thing is: I have to use pure java and no API.
Can you guys help me?
use regular expressions for the test and locating the character
[aeiouAEIOU][bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ]([aeiouAEIOU])
Use a String as a cheap map to keep track of which vowels you've already seen. Also, keep a count of how many consecutive consonants you've encountered. Then, when you hit a vowel that you haven't seen before preceded by a single consonant you've found your answer.
public static void main(String[] args)
{
String s = "eeaaAOEacafu".toLowerCase();
int consCount = 0;
String seenVowels = "";
for(int i=0; i<s.length(); i++)
{
char c = s.charAt(i);
if("aeiou".indexOf(c) >= 0)
{
if(seenVowels.indexOf(c) == -1)
{
if(consCount == 1)
{
System.out.println("Result: " + c);
break;
}
seenVowels += c;
}
consCount = 0;
}
else consCount++;
}
}
Output:
Result: u
The above works if we take 'unique' to mean that we haven't seen the vowel before. If the vowel has to be unique within the input string then things are a little more complicated. Now we have to keep track of each vowel that meets the original criteria, but remove the solution if we subsequently encounter another instance of the same vowel.
Here's some code to illustrate:
public static void main(String[] args)
{
String s = "afuxekozue".toLowerCase();
int consCount = 0;
String seenVowels = "";
String answer = "";
for(int i=0; i<s.length(); i++)
{
char c = s.charAt(i);
if("aeiou".indexOf(c) >= 0)
{
if(seenVowels.indexOf(c) == -1)
{
if(consCount == 1)
{
answer += c;
}
seenVowels += c;
}
else if(answer.indexOf(c) >= 0)
{
answer = answer.replaceAll(String.valueOf(c), "");;
}
consCount = 0;
}
else consCount++;
}
if(answer.length() > 0)
System.out.println("Result: " + answer.charAt(0));
}
Output:
Result: o

IndexOutOfBound error with string manipulation

this is the code for a pig-latin translator in JAVA, it works with one word but never with a sentence. It seems that the code at line 30 is messing everything up, and I'm not sure how it is doing that or how I can fix it. IndexOutOfBoundError on line 8 and line 30. I'm not sure how to fix this, help.
public class Practice
{
public static void main(String[] args)
{
String a = "hello Stranger";
System.out.println(translate(a)); //8
}
private static String translate(String a)
{
String XD = a;
boolean repeat = true;
int first = 1;
int second = 0;
do
{
second = XD.indexOf(" ");
if (second == -1)
{
repeat = false;
XD = vowelFinder(a);
break;
}
else
{
XD = XD + vowelFinder(a.substring(first, second)); //30
}
first = second +1;
}while(repeat == true);
return XD;
}
private static boolean isVowel (char c)
{
if (c == 'a'|| c== 'e'|| c== 'i' || c == 'o' || c== 'u')
{
return true;
}
return false;
}
private static String vowelFinder(String s)
{
String nope = s;
for(int i = 0; i <= s.length(); i++)
{
if(isVowel(s.charAt(i)) == true)
{
nope = nope.substring(i) + "-"+nope.substring(0, i);`
return nope;
}
}
return nope;
}
}
Try this;
import java.util.Scanner;
public class PigLatin {
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
String yourSentence="";
do {
String[] words;
System.out.print("Enter your words here: ");
yourSentence = input.nextLine();
words = yourSentence.split(" ");
for (String word : words) {
if (word.startsWith("a") || word.startsWith("e") || word.startsWith("i") || word.startsWith("o") || word.startsWith("u"))
System.out.print(word + "way ");
else if (word.startsWith("sh") || word.startsWith("ch") || word.startsWith("th"))
System.out.print(word.substring(2)+word.substring(0,2)+"ay ");
else
System.out.print(word.substring(1)+word.substring(0,1)+"ay ");
}
System.out.println();
} while(!yourSentence.equals("quit"));
}
}

Parsing String in java with Special Char

i'm trying to tokenize a string in such a way that ...
Example String
Public Static void main(String[args])
String tokenizer tokenize like
public
static
void
main
String
args
but i want to tokenize in such way
public
static
void
main
(
String
[
args
]
)
means its also print the char on which string moves to tokenized
public String[] tokenise(String str){
String progress = "";
LinkedList<String> list = new LinkedList<String>();
for(int c = 0; c < str.length(); c++){
char ch = str.charAt(c);
// Skip next char if the current char is an escape character
if(ch == '\\'){
c++;
continue;
}
// If current char is to be tokenised, add progress and char to list
if(ch == ' ' || ch == '(' || ch == ')' || ch == '[' || ch == ']'){
if(!progress.equals("")) list.add(progress);
list.add(ch+"");
progress = "";
}else{
progress += ch;
}
}
String[] result = new String[list.size()];
for(int c = 0; c < result.length; c++) result[c] = list.get(c);
return result;
}
import java.util.Scanner;
import java.util.ArrayList;
public class SOQ17
{
public Scanner scan;
public String test;
public boolean check = true;
public SOQ17()
{
System.out.print("Enter your string.\n");
scan = new Scanner(System.in);
test = scan.nextLine();
for(int i = 0; i < test.length(); i++)
{
if((test.charAt(i) >= 'A' && test.charAt(i) <= 'Z') || (test.charAt(i) >= 'a' && test.charAt(i) <= 'z'))
{
System.out.print(test.charAt(i) + "");
check = true;
}
else
{
if(check)
{
System.out.println("");
}
System.out.println(test.charAt(i));
check = false;
}
}
}
public static void main(String[] args)
{
while(true)
{
SOQ17 soq = new SOQ17();
}
}
}
Here is how mine works, it will create a new line for every thing that is not a letter. If it is a letter, however, it will simply print it out. Also, I used boolean 'check' to ensure that the proper formatting is applied when alternating back and forth between letter and not.

Categories

Resources