Password should consist of minimum 8 characters.
Password should consist both numbers and letter.
No special characters are allowed.
The output of this code is always "Invalid Password"
What should be modified to get the correct output?
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");
} else {
System.out.println("Invalid Password");
}
}
public static boolean isValid(String password) {
if (password.length() < 8) {
return false;
} else {
for(int i = 0; i <= password.length() - 1; i++) {
char c = password.charAt(i);
if (!Character.isLetter(c) | !Character.isDigit(c)) {
return false;
}
}
}
return true;
}
}
| is a bitwise or, || is a logical or. You should know the difference.
Work this way though:
if(!Character.isLetter(c) && !Character.isDigit(c))
return false;
=> If the character is not a letter nor a digit return false
You have only one | in your code when doing the OR in your if statement. It should be || . I was stumped on the same thing for an hour yesterday :l
| is a bitwise operator, || is a logical operator. Also, there is a problem with the logic. A Character can't be a Letter and Digit at the same time, so this condition is always true. Try using &&
if(!Character.isLetter(c) && !Character.isDigit(c))
return false;
I feel that I should mention a few mistakes in your approach, as it might help save you time in the future.
If your method isValid, you have a loop which iterates over all the characters in the string. This is the right way to do this, so you clearly know what you need to do to achive the aim.
However, logically, what this method does next is as follows.
Get the first character in the string
Check if the character is a digit or a char
If that character is not a digit or char, return false
Your method will fall over if the first character is not a char, or not a digit. Rationally, you have the right idea, but a letter is not a number, and vise versa.
Suppose the first letter is 'A' - it's not a number, so return false.
If the first character is '1' - it's not a letter, so return false.
As you have seen, changing the operator to && will stop the program failing if you enter only numbers or letters, but will return false if you add any non alphanumeric value.
If you need to enforce at least one digit and at least one number, you have to store the number of digits and chars you have in the string as you iterate over it.
Have two variables, one to store the total number of digits, and one to store the number of chars, and increment them as you step through the string.
If the total number of digits found is greater than zero, and the total number of letters found is greater than zero, your password is valid.
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");
} else {
System.out.println("Invalid Password");
}
}
public static boolean isValid(String password) {
if(password.length()<8) {
return false;
} else {
int dCount = 0;
int cCount = 0;
for (int i=0; i<=password.length()-1; i++) {
char c=password.charAt(i);
if(Character.isLetter(c) {
cCount++;
}
if(Character.isDigit(c)) {
dCount++;
}
}
return dCount > 0 && cCount > 0;
}
}
Related
The instruction to the program is: Zip codes consist of 5 consecutive digits. Prompt the user for a five digit zip code as a String. Create a Java method called isValid and pass the String as a parameter to the method. In the method determine whether the input is a valid zip code. A valid zip code is as follows:
Must only contain numbers (no non-digits allowed).
Must not contain any spaces.
Must not be greater than 5 digits in length.
If the zip code is valid return true to the main method, else return false.
Everytime I put in a valid zip code it still says false
this is my code:
import java.util.Scanner;
public class Main
{
public static void main (String[]args)
{
Scanner input = new Scanner (System.in);
System.out.println ("Enter a zip code: ");
String zipCode = input.nextLine ();
System.out.println (isValid (zipCode));
}
public static boolean isValid (String zipCode)
{
boolean yes = false;
int i = 0;
for (i = 0; i < zipCode.length (); i++)
{
int digit = zipCode.charAt (i);
//if only contains number
if (digit > 48 && digit < 57)
{
System.out.println (digit);
}
else
{
return false;
}
int len = zipCode.length ();
if (len == 4)
{
System.out.println (len);
}
else
{
return false;
}
}
return yes;
}
}
You should include both 0 and 9 , Hence, please change this line
if (digit > 48 && digit < 57)
to
if (digit >= 48 && digit <= 57)
On the other hand, the length of a zip should be 5 instead of 4, Hence, please change this line:
if (len == 4)
to
if (len == 5)
You can refactor the code and use a matcher in order to reduce the validations.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a zip code: ");
String zipCode = input.nextLine();
System.out.println(isValid(zipCode));
}
public static boolean isValid(String zipCode) {
boolean yes = false;
// Check that only digits are accepted and the length is equals to 4
if (zipCode.matches("[0-9]+") && zipCode.length() == 4) {
yes = true;
}
return yes;
}
}
boolean yes = false;
return yes;
if (len == 4) {
...
} else {
return false;
}
Your two specific mistakes.
More generally, you need to learn how to debug. Eventually you'll get some basic skill in eyeballing errors, but only the most simple errors are eyeballable. (It's surely a word, no?)
Take out pen and paper if you have to, but the name of the game is: You calculate what you think the code should do in your head. Then you let the computer do it and compare notes: What should every variable be, what is the result of every call? Crosscheck with what you think. Where you and computer disagree? Bug.
Then it's just a matter of picking some inputs and off you go. A debugger makes this a lot simpler, but some System.out.println statements and some sweat will take care of it too.
Do that next time instead of asking on SO. It's good exercise, and you'll never be worth a can of beans as a programmer if you can't do this.
I am new to learning java and I'm doing a project for my online class and currently stuck on part of it.
Write a program that checks the properness of a given variable name. More specifically, your program should specify whether a user-entered variable name is:
illegal (no spaces allowed, must begin with a letter)
legal, but uses poor style (should only use letters or digits)
good
You don’t need to check for an uppercase letter for the first letter in the second word, third word, etc.
So my problem is that since having space in a variable name is illegal, I need to check the user's input for space, and if there is one it needs to print that it is illegal. I also need to check for special symbols (like $%#) and if it is anywhere but the first character, have it print that it is legal but improper.
I feel like this is super simple I just can't figure it out.
import java.util.Scanner;
public class IdentiferCheck
{
public static void main (String[] args)
{
Scanner in = new Scanner (System.in);
String variableName = "";
char ch = ' '; //temp holder
//Get User Input
System.out.println("This program checks the properness of a proposed Java variable name.");
System.out.println("Please enter a variable name (q to quit):");
variableName = in.nextLine();
//Check if variable name is proper
do
{
//Check if first char is lowercase
ch = variableName.charAt(0);
if (Character.isLetter(ch) && Character.isLowerCase(ch))
{
System.out.println("Good!");
}
else if (Character.isDigit(ch) && Character.isUpperCase(ch) && variableName.contains(" "))
{
System.out.println("Illegal!");
}
//Allow user to input another name or quit
System.out.println("Enter another name or press q to quit: ");
variableName = in.nextLine();
} while (!variableName.equalsIgnoreCase("q"));
}
}
make sure to read the following documentation for your task. It's worth noting that the requirements don't actually match the real world requirements of Java variable names. However, the most difficult part of this task is the logic rather than the script. I've written an example script for you below:
Subsequent characters may be letters, digits, dollar signs, or underscore characters. https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
import java.util.Scanner;
public class identifierCheck
{
public static void main(String[] args) {
String input = " ";
System.out.printf("type q to exit...\n");
while (input.charAt(0) != 'q' && input.length() == 1) // Note the length so that you can use q for starting variable names
{
input = requestLine();
if (checkValid(input))
{
System.out.printf("%s is legal...\n", input);
}
}
}
public static String requestLine()
{
Scanner cmd = new Scanner(System.in);
System.out.printf("Enter a variable name > ");
return cmd.nextLine();
}
public static boolean startsWithLetter(String input)
{
if (123 > (int)input.toLowerCase().charAt(0) && (int)input.toLowerCase().charAt(0) > 60)
{
return true;
}
else
{
return false;
}
}
public static boolean containsInvalid(String input)
{
if ((input.indexOf('$') != -1 || input.indexOf('_') != -1) && input.indexOf(' ') == -1)
{
System.out.printf("Using $ and/or _ in variable names is poor style...\n");
}
if (input.indexOf(' ') != -1) // Has a space in the string
{
return true;
}
else
{
return false;
}
}
public static boolean checkValid(String input)
{
if (!startsWithLetter(input))
{
System.out.printf("%s is illegal, must start with a letter (note: $ and _ are 'valid' to start variable names)...\n", input);
return false;
}
else if (containsInvalid(input))
{
System.out.printf("%s is illegal, it must not contain spaces...\n", input);
return false;
}
else
{
return true;
}
}
}
Good luck with your course! Java's an excellent language to learn.
Here are the exact words of my project
"Write a class and test program that prompts the user to enter a three-digit number
such that the digits are in order. For example 123, 567. The program will loop until a
correct value is entered. ( 576 is incorrect)"
I have written this program that searches for a specific password but what i need is one that searches for any numerical value where the numbers are in order and im having trouble writing a program that searches for something thats not a specific value, heres what i have so far.
import java.util.Scanner;
public class pass {
public static void main(String[] args) {
int passw;
Scanner sc = new Scanner(System.in);
do {
System.out.print("Enter 3 digits in sequence");
passw = sc.nextInt();
if(passw != 567) {
System.out.println("Access Denied");
}
else {
System.out.println("Access Granted");
}
}
while(passw != 567);
}
}
You could use a method to check for whether the given digits are in order.
private boolean isInOrder(int number){
int digit = -1;
while(number > 0){
if (digit != -1 && digit != (number % 10) + 1)
return false; // Since the number is not in order
digit = number % 10;
number /= 10;
}
return true; // If the number is in order
}
This method can check whether a number (of any length, not only 3), is in the order specified in the question.
Since you know that your "password" will be an integer with only three digits, you can easily accomplish whether the digits are ordered or not with an if statement. Try out the following code and see if it works for you!
public class ThreeDigitPasswordTest {
public static boolean testPassword(int number) {
char[] cArr = String.valueOf(number).toCharArray();
if((cArr[2] == cArr[1] + 1) && cArr[1] == cArr[0] + 1)
return true;
return false;
}
public static void main(String[] args) {
System.out.println(testPassword(567)); //prints "true"
System.out.println(testPassword(576)); //prints "false"
}
}
The user should give a string, where we should check if all characters are numbers.
If all are digits, we will get one message that the password is with digits and move on with the program. If any of them (or all) is not a digit, then the user should enter password again.
(E.g. 465486 is acceptable. hell3429384 or sfdkjsfkj is not acceptable)
Apparently, my code is not working correctly, since whether I give a number or a letter to the password, I get the same result.
Am I looping something wrong, or am I using the isDigit method wrong?
import java.util.*;
public class Password {
public static void main(String[] args) {
Scanner passn = new Scanner(System.in);
System.out.println("Give password: ");
String pass = passn.nextLine(); /* user enters password*/
int length = pass.length();
boolean isadigit;
for(int i = 0; i < length; i++) { /*looping each character one by one*/
char character= pass.charAt(i);
if (Character.isDigit(i)) { /*checking if each character is digit*/
isadigit = true; /* if it is, give the value to isadigit true*/
System.out.println("PASSWORD is w digits");
}
else {
System.out.println("PASSWORD w/out digits");
passn.nextLine();
}
}
}
}
If you can use java-8 there is one-liner:
pass.chars().allMatch(Character::isDigit)
You are not checking each character, but each index value.
Change
if(Character.isDigit(i))
to
if(Character.isDigit(character))
Also: you don't break out of the loop when you encounter a non-digit...
A side note if you are on Android:
You can use TextUtils.isDigitsOnly() directly, e.g.
TextUtils.isDigitsOnly(myString)
And just in case, an empty string is digit only because it doesn't contain any non-digit; also this method is not null-tolerant.
To be honest: You could write code like you did. But it would be better to use a regular expression on that. You want to know, if a certain String only contains digits. Here is the code:
String foo = "My_pwd_is_wrong_123!";
String bar = "123";
boolean foo_ok = foo.matches("^[0-9]*$") // Will be "false"
boolean bar_ok = bar.matches("^[0-9]*$") // Will be "true"
Ok, in that case: Your Problem is, that you continue your loop after identifiyng a non-digit in one Password. You need to BREAK your loop, as soon as you find a non-digit in the pwd:
public class TEST {
public static void main(String[] args) {
Scanner passn = new Scanner(System.in);
System.out.println("Give password: ");
String pass = passn.nextLine(); /* user enters password*/
int length = pass.length();
boolean isadigit = true;
for(int i = 0; i<length; i++) { /*looping each character one by one*/
char character= pass.charAt(i);
if (!Character.isDigit(character)) { /*checking if current character is digit*/
isadigit = false; /* if it is not, give the value to isadigit false*/
break;
}
}
if(isadigit)
System.out.println("PASSWORD is w digits");
else
System.out.println("PASSWORD w/out digits");
}
}
Please see this sample implementation
boolean isDigit = false;
for (int i = 0; i < length; i++) {
char character = pass.charAt(i);
if (Character.isDigit(character)) {
isDigit = true;
} else {
passn.nextLine();
}
}
if (isDigit) {
System.out.println("PASSWORD is w digits");
} else {
System.out.println("PASSWORD w/out digits");
}
In Kotlin, you can use
text.all { it.isDigit() }
try to parse the string to Integer.
catch the exception
Scanner passn = new Scanner(System.in);
System.out.println("Give password: ");
String pass = passn.nextLine(); /* user enters password*/
try
{
Integer.parseInt(pass);
System.out.println("Digital password!");
}
catch(NumberFormatException nfe){
System.out.println("without digit password!");
}
I am working on a password checker and I need some help. If possible I need to make the checker as "realistic" as possible. Meaning it needs to actually register the password and have dialogue. I managed to get some guidelines down: Password needs to be 8-12 Characters, 1 number, 1 special character, and a Capital letter. Im having trouble with storing the password into a database and not allowing two of the same character in consecutive order(Ex. aa)
import java.util.Scanner;
public class passworChk{
public static void main(String[] args) {
// TODO Auto-generated method stub
int min =8;
int max=12;
int digit=0;
int special=0;
int upCount=0;
int loCount=0;
int count=0;
String password;
String decision;
Scanner scan = new Scanner(System.in);
System.out.println("Enter Your Password: ");
password = scan.nextLine();
//Sees if the Password is okay
if(count <= 0){
System.out.println("No password registered. would you like to register a new password? Enter yes or no.");
decision = scan.nextLine();
if(decision.length() == 3){
System.out.println("Enter Your Password: ");
password = scan.nextLine();
count++;
}
else if(decision.length() == 2){
System.out.println("Goodbye");
System.exit(0);
}
}
if(count >= 0){
if(password.length()>=min&&password.length()<=max){
for(int i =0;i<password.length();i++){
char c = password.charAt(i);
//This code goes through the 'password' String and registers it through counts.
if(Character.isUpperCase(c)){
upCount++;
}
if(Character.isLowerCase(c)){
loCount++;
}
if(Character.isDigit(c)){
digit++;
}
if(password.contains("&") || password.contains("!") || password.contains("#") || password.contains("#") || password.contains("$") || password.contains("*") || password.contains("%") || password.contains("?")){
special++;
}
}//If all the counts are in the correct ranges, the password is acceptable.
if(special>=1&&loCount>=1&&upCount>=1&&digit>=1){
System.out.println("Your Password is acceptable.");
}
}
if(password.length()<min){
for(int i =0;i<password.length();i++){
char c = password.charAt(i);
if(Character.isLowerCase(c)){
loCount++;
}
}
if(loCount>0){
System.out.println("Your Password must be at least "+min+" characters.");
System.out.println(" You need at least one upper case chracter,");
System.out.println(" You need at least one digit.");
System.out.println(" You need at least one special chracter.");
}
}
else if(password.length()<min&&upCount>1){
for(int i =0;i<password.length();i++){
char c =password.charAt(i);
if(Character.isLowerCase(c)){
loCount++;
}
if(Character.isUpperCase(c)){
upCount++;
}
}
if(loCount>0&&upCount>0){
System.out.println(" Password must be at least "+min+" chracters:");
System.out.println(" You need at least one digit:");
System.out.println(" You need at least one special chracter:");
}
}
if(password.length()>max||password.length()>=max&&upCount>1&&loCount>1&&digit>1){
System.out.println(" Password is too long. The limit is "+max+" chracters:");
System.out.println(" You need at least one special chracter:");
}
if(password.length()>=min&&password.length()<=max&&loCount>0&&upCount>0&&digit>0&&special==0){
System.out.println(" You need atleast a special chracter");
}
if(password.length()>=min&&password.length()<=max&&loCount>0&&upCount>0&&digit==0&&special==0){
System.out.println(" You need at least one digit:");
System.out.println(" You need at least one special chracter:");
}
}
}
}
In my opinion, instead of having a count of all the special characters, uppercase, and lowercase, you could just have a boolean of each and if at the end all of them are true, you could insert the password into the database. For blocking passwords that have equal characters next to them, you could try something like this within the for loop.
if(i < (password.length() -1) && c == password.charAt( i+1 ) ) {
//throw error message or set boolean of valid to false.
}
This says if i is less than length - 1 (so we can check the next index without array out of bounds exception), then check to see if the next char is equal to the current char.
Next, as some others have said, you should be storing passwords in a database as salted hashes. This is to make sure if your database is compromised, your passwords are hashed.