Java appending unexpectedly - java

I'm trying to run a check whether or not a user has entered the #gmail.com suffix to their input. If not, then append it. I'm having a little difficulty because this loop seems to be written correctly to me. I'm at a loss. Anyone? I'm sure it's simple, I just can't see it.
String UN;
Scanner sc = new Scanner(System.in);
String suf = "#gmail.com";
boolean sufd;
// your code goes here
UN = sc.nextLine(); //
if(UN.length() >= 11){
sufd = UN.substring(UN.length()-11,UN.length()-1).equals("#gmail.com");
if(!sufd) {
UN += suf;
}
} else if(UN.length() < 11) {
UN += suf;
}
System.out.print(UN);

Using the official java email package is the easiest:
public static boolean isValidEmailAddress(String email) {
boolean result = true;
try {
InternetAddress emailAddr = new InternetAddress(email);
emailAddr.validate();
} catch (AddressException ex) {
result = false;
}
return result;
}

public boolean isValidEmailAddress(String email) {
String ePattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$";
java.util.regex.Pattern p = java.util.regex.Pattern.compile(ePattern);
java.util.regex.Matcher m = p.matcher(email);
return m.matches();
}
Test Cases:
.

Related

Validating e-mail username and password using try/catch block

I'm trying to write a code that validates an email as a username and a password that has at least one uppercase, one lowercase, and one special character. When I run the program, I'm getting "Successfully signed up." no matter what I input. I believe my error is in my try/catch block.
import java.util.Scanner;
public class UserSignUp {
public static void main(String[] args) {
Scanner input1 = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
String username;
String password;
try {
System.out.print("Enter your username: ");
username = input1.nextLine();
System.out.print("Enter your password: ");
password = input2.nextLine();
}
catch (IllegalArgumentException e) {
System.out.println(e);
}
System.out.println("Successfully signed up.");
}
public static void validateUsername(String username) throws IllegalArgumentException {
String pattern = ".+#.+\\.com";
if (username.matches(pattern)) {
throw new IllegalArgumentException("Invalid username.");
}
}
public static void validatePassword(String password) throws IllegalArgumentException {
boolean isUppercase = false;
boolean isLowercase = false;
boolean isDigit = false;
boolean hasSpecialCharacter = false;
char ch = 0;
for (int i = 0; i < password.length(); i++) {
ch = password.charAt(i);
if (Character.isUpperCase(ch)) {
isUppercase = true;
} else {
throw new IllegalArgumentException("Password must contain an uppercase letter.");
}
if (Character.isLowerCase(ch)) {
isLowercase = true;
} else {
throw new IllegalArgumentException("Password must contain a lowercase letter.");
}
if (Character.isDigit(ch)) {
isDigit = true;
} else {
throw new IllegalArgumentException("Password must contain a digit.");
}
if (!Character.isDigit(password.charAt(ch)) && !Character.isLetter(password.charAt(ch))) {
hasSpecialCharacter = true;
} else {
throw new IllegalArgumentException("Password must contain a special character.");
}
}
}
}
Here is my solution to it, the explanation is already embedded:
import java.util.Scanner;
public class UserSignUp {
public static void main(String[] args) {
// No need for two scanners, one scanner can accept multiple (also
// multiple-lined) inputs.
Scanner in = new Scanner(System.in);
try {
// Put validation inside the try block.
// Regarding there are no other use of the variables, it is unnecessary to give
// the two variables "Method Level Scope" instead of "Block Scope".
System.out.print("Enter your username: ");
String username = in.nextLine();
validateUsername(username);
System.out.print("Enter your password: ");
String password = in.nextLine();
validatePassword(password);
// Put the println() inside the try block.
System.out.println("Successfully signed up.");
} catch (IllegalArgumentException e) {
System.out.println(e);
}
}
public static void validateUsername(String username) throws IllegalArgumentException {
String pattern = ".+#.+\\.com";
// If not matches the pattern,
if (!username.matches(pattern)) {
throw new IllegalArgumentException("Invalid username.");
}
}
public static void validatePassword(String password) throws IllegalArgumentException {
boolean isUppercase = false;
boolean isLowercase = false;
boolean isDigit = false;
boolean hasSpecialCharacter = false;
char ch = '\0';
for (int i = 0; i < password.length(); i++) {
ch = password.charAt(i);
if (Character.isUpperCase(ch))
isUppercase = true;
if (Character.isLowerCase(ch))
isLowercase = true;
if (Character.isDigit(ch))
isDigit = true;
// ch is already defined as a character.
if (!Character.isDigit(ch) && !Character.isLetter(ch))
hasSpecialCharacter = true;
}
// Ask for the constraints after read through all characters.
if (isUppercase != true)
throw new IllegalArgumentException("Password must contain an uppercase letter.");
else if (isLowercase != true)
// Fix the error message of lower-case letters.
throw new IllegalArgumentException("Password must contain a lowercase letter.");
else if (isDigit != true)
throw new IllegalArgumentException("Password must contain a digit.");
else if (hasSpecialCharacter != true)
throw new IllegalArgumentException("Password must contain a special character.");
}
}
Hope this answer helps and please leave this question as it is as someone might need it, unless there is important changes.

Password Validation regex android

I need to have following password validations :
At least Min Characters 8 and Maximum Characters 15
At least One Number and 1 special characters from (! ##$%^&*-=+?.);
At least One lower case letter
Password shouldn't be sub strings of username and email (min length 3 and max length 15).
Password should be case sensitive.
I have also looked these answers but I am confuse , should I use Input filters to achieve this or Regex?
Any help will be appreciable. It will be great if you guyz provide a working solution.
public class Validation {
public static void main(String[] args) {
String pass = "1AB%CDef555";
String username = "manna";
String email = "mannx#rtt.com";
System.out.println(validiate2(pass, username,email));
}
// if you don't care why it fails and only want to know if valid or not
public static boolean validiate (String pass, String username, String email){
String pattern = "^(?=.*[0-9])(?=.*[a-z])(?=.*[!##$%^&*+=?-]).{8,15}$";
if(pass.matches(pattern)){
for(int i=0;(i+3)<username.length();i++){
if(pass.contains(username.substring(i,i+3)) || username.length()<3 || username.length()>15){
return false;
}
}
for(int i=0;(i+3)<email.length();i++){
if(pass.contains(email.substring(i,i+3)) || email.length()<3 || email.length()>15){
return false;
}
}
return true;
}
return false;
}
// if you want to know which requirement was not met
public static boolean validiate2 (String pass, String username, String email){
if (pass.length() < 8 || pass.length() >15 ){
System.out.println("pass too short or too long");
return false;
}
if (username.length() < 3 || username.length() >15 ){
System.out.println("username too short or too long");
return false;
}
if (!pass.matches(".*\\d.*")){
System.out.println("no digits found");
return false;
}
if (!pass.matches(".*[a-z].*")) {
System.out.println("no lowercase letters found");
return false;
}
if (!pass.matches(".*[!##$%^&*+=?-].*")) {
System.out.println("no special chars found");
return false;
}
if (containsPartOf(pass,username)) {
System.out.println("pass contains substring of username");
return false;
}
if (containsPartOf(pass,email)) {
System.out.println("pass contains substring of email");
return false;
}
return true;
}
private static boolean containsPartOf(String pass, String username) {
int requiredMin = 3
for(int i=0;(i+requiredMin)<username.length();i++){
if(pass.contains(username.substring(i,i+requiredMin))){
return true;
}
}
return false;
}
}
There is great library for that.
It's uses anotations for field and has rich customatization.
I think that #4 still needs to be done by hand but you should definitly check out the library.
Here's the example from github:
#Password(min = 6, scheme = Password.Scheme.ALPHA_NUMERIC_MIXED_CASE_SYMBOLS)
private EditText passwordEditText;
Cheers.
You can try this one:
^(?!.*(user|emailaddress))(?=.*\d)(?=.*[! ##$%^&*=+?.-])(?=.*[a-z]).{8,15}$
Make sure you replace the user and emailaddress by your variable
Explanation
This code works fine for me:
public class NewClass1 {
public static void main(String[] args) {
NewClass1 nc = new NewClass1();
nc.check("abcd123-", "userName", "abc#yahoo.com");
nc.check("userName1-", "userName", "abc#y.c");
nc.check("abc#y.c1b", "userName", "abc#y.c");
nc.check("abcy.c1b", "userName", "abc#y.c");
nc.check("abcd123-", "userName", "abc#yahoo.com");
}
public void check(String string, String userName, String email) {
final String regex = "^(?!.*(" + userName + "|" + email + "))(?=.*\\d)(?=.*[! ##$%^&*=+?.-])(?=.*[a-z]).{8,15}$";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
if (matcher.find()) {
System.out.println(string + "Full match: " + matcher.group(0));
} else {
System.out.println("no match");
}
}
}

Password Check Program - checking capitals, lowercase letters, digit and special character

I have an assignment that requires me to create a password checking program.
The password must be at least 8 characters, contain both capital and lower case letters, a digit and a special character.
I believe I am close to solving this problem but my skills are still developing and I've hit a wall.
package project1;
/**
*
* #author danechristian
*/
import java.util.*;
public class Project1
{
static Scanner console = new Scanner(System.in);
static final String SPECIAL_CHARACTERS = "!,#,$,%,^,&,*,|";
static String password;
public static void main(String[] args)
{
System.out.println("Create a password: ");
password = console.next();
if (validPassword(password))
{
System.out.println("Password Saved");
}
else
{
System.out.println("Invalid Passowrd. Password "
+ "must contain atleast 1 capital letter"
+ "1 lower case letter, 1 digit, 1"
+ "special character (!#$%^&*|) and "
+ "be atleast 8 characters long");
}
}
public static boolean validPassword(String password)
{
boolean upCase = false;
boolean loCase = false;
boolean isDigit = false;
boolean spChar = false;
if (password.length() >= 8)
{
for (int i = 0; i < password.length() - 1; i++)
{
if (Character.isUpperCase(password.charAt(i)))
{
upCase = true;
}
if (Character.isLowerCase(password.charAt(i)))
{
loCase = true;
}
if (Character.isDigit(password.charAt(i)))
{
isDigit = true;
}
if (SPECIAL_CHARACTERS.contains(password))
{
spChar = true;
}
}
}
return (upCase && loCase && isDigit && spChar);
}
}
In order to check have something like this:
public static boolean validPassword(String password){
boolean upCase = false;
boolean loCase = false;
boolean isDigit = false;
boolean spChar = false;
if (password.length()>7){
if (password.matches(".+[A-Z].+")){
upCase = true;
}
if (password.matches(".+[a-z].+")){
loCase = true;
}
if (password.matches(".+[1-9].+")){
isDigit = true;
}
if (SPECIAL_CHARACTERS.contains(password)){
spChar = true;
}
}
return (upCase && loCase && isDigit && spChar);
}
solved by changing
if (SPECIAL_CHARACTERS.contains(password)){
spChar = true;
to
if (SPECIAL_CHARACTERS.contains(password.substring(i,i+1))){
spChar = true;
this checks for the string within the string.
also, I removed the "- 1" from my for statement so that the bounds were corrects. also removed the commas from the SPECIAL_CHARACTERS constant.
the program now runs without issue, thanks for the advice everyone.

Trouble checking if a string is a palindrome

I am a beginner learning Java and have been asked to check if a given string is a palindrome.
Here is what I have so far:
int namel = name.length();
for (int i =0; i<=namel; i++)
{
char letter = name.charAt(i);
char namerev = name.charAt(namel-i);
String letterS =txtNamePali.getText();
if(letter==namerev)
{
txtNamePali.setText("Palindrone");
}
else
{
txtNamePali.setText( "Not a Palindrone");
}
}
Unfortunately my textbox isn't showing any output. I have searched for how to fix the issue but couldn't find an answer relating to what I have learnt in class.
What did I do wrong, and how can I correct it?
I think the easiest test is to use the StringBuilder.reverse() to construct the reverse of the input. Also, the word is usually spelled palindrome.
StringBuilder sb = new StringBuilder(name);
sb.reverse();
String msg = (sb.toString().equals(name)) ? "Palindrome" : "Not a Palindrome";
txtNamePali.setText(msg);
You can do it using a StringBuilder
Use the reverse function in that.
Example:
public static void main(String args[]){
String str = "1234";
String str1 = "1234321";
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(str);
if(stringBuilder.reverse().toString().equals(str)){
System.out.println("Palindrome");
} else {
System.out.println("Not Palindrome");
}
stringBuilder = new StringBuilder();
stringBuilder.append(str1);
if(stringBuilder.reverse().toString().equals(str1)){
System.out.println("Palindrome");
} else {
System.out.println("Not Palindrome");
}
}
Output:
Not Palindrome
Palindrome
Int short you can just do
new StringBuilder().append(yourString).reverse().toString().equals(yourString)
This return a boolean true if the string is palindrome else false.
Your code is on the right track, but as some people have said, there are a few errors you need to account for, which should appear as compiler issues.
int namel = name.length();
boolean isPalindrome = true;
//add a tracking value, it's a palindrome unless we prove it otherwise
for (int i =0; i< namel/2; i++)
//change from <= to < because arrays are 0-index, we also only have to check halfway so we can use namel/2
{
char letter = name.charAt(i);
char namerev = name.charAt(namel-i);
//String letterS =txtNamePali.getText(); <-- not sure what this was for, possibly a debug statement
if(letter!=namerev)
{
isPalindrome = false; //we have found a non-matching value, it'll stay false, and we'll output correctly
}
}
//then we set the text once. Keeping the text inside would have returned an erroneous "abbc" is a palindrome.
if(isPalindrome) {
txtNamePali.setText("Palindrone");
}
else {
txtNamePali.setText( "Not a Palindrone");
}
1.The result of the method should be given when the whole string got checked. So first put
if(letter==namerev)
{
txtNamePali.setText("Palindrone");
}
else
{
txtNamePali.setText( "Not a Palindrone");
}
outside the loop (and change the condition - like in my proposal below).
you can break the loop when the first mismatch of two chars occured.
2.Instead of char namerev = name.charAt(namel-i); you have reduce the position one more.
So use: char namerev = name.charAt(namel-1-i);
try something like this:
String s = "stringtotest";
boolean result = true;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != s.charAt(s.length()-1-i)) {
result = false;
break;
}
}
if (result)
System.out.println("Palindrom");
else
System.out.println("Not palindrom");
Same general idea as the others, but I think that this is cleaner and easier to read. Just a thought - everyone has their own style. :) If you're a beginner, I highly suggest getting into the habit of moving redundant logic to its own method. It's cleaner and may prove to be much more useful later.
public class Main {
public static void main( String args[] ) {
for ( String string : args ) {
if ( isPalendrome( string ) {
System.out.println("Palindrome");
} else {
System.out.println("Not a Palindrome");
}
}
}
private static boolean isPalindrome( String string ) {
return string.equals( reverse( string ) );
}
private static String reverse( String original ) {
return new StringBuilder(original).reverse().toString();
}
}
String name="pop"; // string to check if it palindrome or not
String revName="";
int namel = name.length();
for (int i =1; i<=namel; i++)
{
char namerev = name.charAt(namel-i);
revName += namerev;
}
if(name.equals(revName))
{
System.out.println("Palindrome");
}
else
{
System.out.println( "Not a Palindrome");
}

NumberFormatExceptions

I am trying with a Utility function to get int and check if bad input results in
NumberFormat Exceptions,is there a way to work with Non-decimal Int for below function
//--- Utility function to get int using a dialog.
public static int getInt(String mess) {
int val;
while (true) { // loop until we get a valid int
String s = JOptionPane.showInputDialog(null, mess);
try {
val = Integer.parseInt(s);
break; // exit loop with valid int
} catch (NumberFormatException nx) {
JOptionPane.showMessageDialog(null, "Enter valid integer");
}
}
return val;
}
//end getInt
If I understand you... maybe you can do this:
public static int getInt(String mess) {
int val;
while (true) { // loop until we get a valid int
String s = JOptionPane.showInputDialog(null, mess);
try {
if(mess.match("^\d+$")){ // Check if it's only numbers (no comma, no dot, only numeric characters)
val = Integer.parseInt(s); // Check if it's in the range for Integer numbers.
break; // exit loop with valid int
} else {
JOptionPane.showMessageDialog(null, "Enter valid integer");
}
} catch (NumberFormatException nx) {
JOptionPane.showMessageDialog(null, "Enter valid integer");
}
}
return val;
}
Try what u want , one for decimal checker and one for non-decimal int
// for deciaml
public static Boolean numberValidate(String text) {
String expression = "^[+-]?(?:\\d+\\.?\\d*|\\d*\\.?\\d+)[\\r\\n]*$";
CharSequence inputStr = text;
Pattern pattern = Pattern.compile(expression);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.find()) {
MatchResult mResult = matcher.toMatchResult();
String result = mResult.group();
return true;
}
return false;
}
// non-decimal int
public static Boolean numberValidate(String text) {
String expression = "[a-zA-Z]";
CharSequence inputStr = text;
Pattern pattern = Pattern.compile(expression);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.find()) {
MatchResult mResult = matcher.toMatchResult();
String result = mResult.group();
return true;
}
return false;
}

Categories