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;
}
Related
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;
}
}
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;
}
}
//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
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;
}
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;
}
}
}