help with making a password checker in java - java

I am trying to make a program in Java that checks for three specific inputs. It has to have pass these tests:
At least 7 characters.
Contain both upper and lower case alphabetic characters.
Contain at least 1 digit.
So far I have been able to make it check if there is 7 characters, but I am having trouble with the last two. What should I put in my loop as an if statement to check for digits and make it upper and lower case. Any help would be greatly appreciated.
Here is what I have so far.
import java.awt.*;
import java.io.*;
import java.util.StringTokenizer;
public class passCheck
{
private static String getStrSys ()
{
String myInput = null; //Store the String that is read in from the command line
BufferedReader mySystem; //Buffer to store the input
mySystem = new BufferedReader (new InputStreamReader (System.in)); //creates a connection to system input
try
{
myInput = mySystem.readLine (); //reads in data from the console
myInput = myInput.trim ();
}
catch (IOException e) //check
{
System.out.println ("IOException: " + e);
return "";
}
return myInput; //return the integer to the main program
}
//****************************************
//main instructions go here
//****************************************
static public void main (String[] args)
{
String pass; //the words the user inputs
String temp = ""; //holds temp info
int stringLength; //length of string
boolean goodPass = false;
System.out.print ("Please enter a password: "); //ask for words
pass = getStrSys (); //get words from system
temp = pass.toLowerCase ();
stringLength = pass.length (); //find length of eveyrthing
while (goodPass == false)
{
if (stringLength < 7)
{
System.out.println ("Your password must consist of at least 7 characters");
System.out.print ("Please enter a password: "); //ask for words
pass = getStrSys ();
stringLength = pass.length ();
goodPass = false;
}
else if (/* something to check for digits */)
{
}
}

Sure you can come up with a convoluted—almost unreadable—regex for doing this but I wouldn't suggest it. Apart from the readability aspect, if the password fails it doesn't tell you why. This solves both of these problems:
while (true) {
pass = getStrSys();
if (pass.length() < 7) {
System.out.println("must be at least 7 characters long");
} else {
boolean upper = false;
boolean lower = false;
boolean number = false;
for (char c : pass.toCharArray()) {
if (Character.isUpperCase(c)) {
upper = true;
} else if (Character.isLowerCase(c)) {
lower = true;
} else if (Character.isDigit(c)) {
number = true;
}
}
if (!upper) {
System.out.println("must contain at least one uppercase character");
} else if (!lower) {
System.out.println("must contain at least one lowercase character");
} else if (!number) {
System.out.println("must contain at least one number");
} else {
break;
}
}
}

A regular expression is more appropriate for what you are trying to accomplish. For instance, using lookahead assertions, you'd use something like this:
Pattern p = Pattern.compile("^.*(?=.{7,})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).*$");
String pass = getStrSys();
Matcher m = p.matcher(pass);
if (m.matches()) {
System.out.println("Valid password.");
} else {
System.out.println("Invalid password.");
}

Don't use StringTokenizer. Use String.split.
Use the functions in the Character class to check for upper case, lower case, or numeric.
Since you've forced lower case, you can't check. You need to get rid of that.

In your situation. There should be two condition true for validation. I think following will be the best approach to achieve it.
private static final char[] SPECIAL = "$!+\-#?_%&/".toCharArray();
private static final char[] NUMBER = "0123456789".toCharArray();
public static boolean checkValidation(String password)
{
int points = 0;
String lowerPass = password.toLowerCase();
String upperPass = password.toUpperCase();
if(!password.equals(lowerPass) && !password.equals(upperPass))
{
// if contains upper or lower letter
points++;
}
if(contains(password, SPECIAL))
{
// if it contains special character
points++;
}
if(contains(password, NUMBER))
{
// if it contains Number
points++;
}
return points >= 2;
}
public static boolean contains(String pwd, char[] value)
{
int i = 0;
boolean success = false;
while(i < value.length && !success)
{
if(pwd.indexOf(""+value[i]) != -1)
{
success = true;
}
i++;
}
return success;
}

Related

palindrome program not working as expected

I know it's very puny thing for experts here but I want to check why my palindrome program is not working as expected, it shows as palindrome to every number or string i enter, can you please look into it where the issue is, please.
actually i'm trying to create this program on my own and not checking any ready made method for it so asking here. please help.
here's my program
import java.util.*;
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter the number");
String k = sc.next();
int s = k.length()/2;
boolean b = true;
while(s>0){
for (int i = 0; i<=s; i++) {
if(k.charAt(i)==k.charAt(s)){
b = true;
}
}
if (b)
s--;
else
System.out.println("exit");
}
if(b)
System.out.println("palindrome");
}
}
s is the midpoint, and you are modifying it in your loop. Also, you never set b to false in any condition. Fixing those two bugs, should give you something like
Scanner sc = new Scanner(System.in);
System.out.println("enter the number");
String k = sc.next();
int s = k.length() / 2;
boolean b = true; // <-- Default to true
for (int i = 0; i <= s; i++) { // <-- Only need one loop.
if (k.charAt(i) != k.charAt(k.length() - i - 1)) {
b = false; // <-- Only need to update when it isn't a palindrome.
break; // <-- terminate the loop.
}
}
if (b) { // <-- Use braces. Even when optional.
System.out.println("palindrome");
}
You might be better off writing a simple method to do the check and call that method with your input.
Scanner sc = new Scanner(System.in);
System.out.println("enter the number");
String str = sc.next();
System.out.printf("'%s' %s%n", str, (isPalindrome(str) ? "is " : "is not ") + "a palindrome.");
For inputs of radar and abcdcbc prints
'radar' is a palindrome.
'abcdcbc' is not a palindrome.
The method
public static boolean isPalindrome(String str) {
int len = str.length();
for (int i = 0; i < len / 2; i++) {
if (str.charAt(i) != str.charAt(len - i - 1)) {
return false; // return as soon as characters don't match
}
}
// if the program gets this far, the string must be a palindrome
return true;
}

Sentence Capitalizer with specific requirement

It's hard to explain but I'm trying to create a program that only capitalizes the letter of every word that ends with a period, question mark, or exclamation point. I have managed to receive a result when inputting any of the marks but only when it is entered the second time. In other words I have to hit enter twice to get a result and I'm not sure why. I am still working on it on my own but I'm stuck at this problem.
import java.util.*;
public class SentenceCapitalizer
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Input a sentence: ");
String line = keyboard.nextLine();
String wrong = keyboard.nextLine();
String[] check = {".!?"};
String upper_case_line="";
Scanner lineScan = new Scanner(line);
for (String sent : check)
{
if (sent.startsWith(wrong))
{
System.out.println("cant use .?!");
}
else
{
/* if (line.startsWith(" "))//if starts with space
System.out.println("good");
else
System.out.println("bad");
*/
//if (int i = 0; i < line.length; i++)
//{char c = line.chartAt(i);
while(lineScan.hasNext())
{
String word = lineScan.next();
upper_case_line += Character.toUpperCase(word.charAt(0)) +
word.substring(1) + " ";
}
System.out.println(upper_case_line.trim());
}
}
}
}
Solution
Hey just a quick solution for your question. Converts the string to character array and then checks the character array for '.!?' if it finds the value then it will make the next letter a capital!
public class SentenceCapitalizer {
public static void main(String[] args) {
//Scanner, Variable to hold ouput
Scanner keyboard = new Scanner(System.in);
System.out.print("Input a sentence: ");
String line = keyboard.nextLine();
//Char array, boolean to check for capital
char [] lineChars = line.toCharArray();
boolean needCapital = false;
//String to hold output
String output = "";
//Check for period in line
for (int i = 0; i < lineChars.length; i++) {
//Make sure first char is upper case
if (i == 0) {
lineChars[i] = Character.toUpperCase(lineChars[i]);
}
//Check for uppercase if char is not space
if (needCapital && Character.isLetter(lineChars[i])) {
lineChars[i] = Character.toUpperCase(lineChars[i]);
needCapital = false;
}
if (lineChars[i] == '.' || lineChars[i] == '?' || lineChars[i] == '!') {
needCapital = true;
}
//Add character to string
output += lineChars[i];
}
//Output string
System.out.println (output);
}
}

Java check String input

I am trying to check an input String:
- length
- type
- special char at the end
The input is a identity card like this 24659213Q.
So what I got for now is:
public void datosUsuario() {
System.out.print("Write ID: ");
input = scanner.nextLine();
}
//ID check
public void comprobacion() {
System.out.println("Checking ID length...");
if (input.length() == 9){
status = true;
System.out.println("Length: OK!");
} else {
System.out.println("Length not OK! Try again!\n");
status = false;
}
}
So I am checking the entire String for having 8+1 length and now I am having problems checking if it has 8 digits and a char at the end of the input.
Any ideas would be apreciated! Thank you!
I'd use a regular expression:
String input = scanner.nextLine();
input.matches("/^[0-9]{8}[A-Za-z]$/);
See String.matches and regular expression documentation.
A simple method would be:
//ID check
public void comprobacion() {
System.out.println("Checking ID length...");
if (input.length() == 9) {
if (Character.isAlphabetic(input.charAt(8)) {
status = true;
System.out.println("OK!");
} else {
status = false;
System.out.println("Length: OK, but last character must be alphabetic");
}
} else {
System.out.println("Length not OK! Try again!\n");
status = false;
}
You can use reg ex,
public static void comprobacion(String input) {
status = false;
if(input.matches("\\d{8}\\w{1}"))
{
status = true;
}
}
Here, \d{8} = eight digits
\w{1} = one alphabetical character
You could use "Character.isDigit()" to determine if a character is a digit or not. In other words, you could create a for loop to interate through each character, checking whether it is a digit or not. Here's an example:
String input = "24659213Q";
for(int c = 0; c < input.length()-1; c++){
//Checks all but the last character
if( !Character.isDigit( input.charAt(c) ) ){
System.out.println("The String does not start with 8 digits");
}
}
if( Character.isDigit( input.charAt(8) ) ){
//Checks only last character
System.out.println("The String does not end with a char");
}
The method of regular expression can also be followed as mentioned above. There is one more way to do it.
1)Split the string into two -one with 8 characters and the other with last one character.
2)Parse the first String
Integer.parseInt(subStringOfFirst8Char) in a try catch block catching NUmberFormatException.
If you don't catch the exception it is alright else it is wrong.

java validate String containing numbers and search to make sure there are no characters

I want to validate a user input phone number, the first thing I need to do is check to make sure that the length of the input string is 10 which isn't an issue as you'll see in my code.
Now is where the problem comes in, I also need to check to make sure no characters have been entered in as well, any ideas on how to do this with out the use of Arrays. I'd like to use Character.isLetter(); but no matter how I implement it it's not coming out right.
import java.util.Scanner;
public class Example
{
public static void main(String[] args)
{
boolean isNumber = false;
String phoneNum = "";
Scanner input = new Scanner(System.in);
while(!isNumber)
{
System.out.print("\nEnter your 10 digit phone number (ex: 2123345657): ");
phoneNum = input.nextLine();
/* Yes I could use nextInt(); etc.. but that would defeat the
purpose of this exercise */
if(phoneNum.length() != 10)
{
System.out.println("\n\nBad input");
}
else
isNumber = true;
}
System.out.println("\n\nPhone number is: " + phoneNum);
}
}
I was looking for some thing like this.
while(!isRight)
{
System.out.print("\n input number: ");
phoneNum = input.nextLine();
while(i < phoneNum.length())
{
if(phoneNum.length() != 10)
{
System.out.println("not enough numbers");
}
else if (Character.isLetter(phoneNum.charAt(i)) == true)
{
System.out.println("Sorry you can't use any thing but numbers");
}
else
isRight = true;
i++;
}
}
You can do it without a regex:
boolean validate(String str) {
if (str.length() != 10) {
return false;
}
for (int i = 0; i < str.length(); ++i) {
if (!Character.isDigit(str.charAt(i)) {
return false;
}
}
return true;
}
use a regex of
"^[0-9]{10}"
or if it has to start with non-zero
"^[1-9][0-9]{9}"
if(!phoneNum.matches("^[0-9]{10}")) {
// ok
}
If you want to use isLetter
then try
boolean allNum = true;
for (char ch : phoneNum.toCharArray ()) {
if (Character.isLetter (ch)) {
allNum = false;
break;
}
}
You can use String regex matching to check whether string is a numeric or not:
boolean numeric = phoneNum.matches("\\d+");
As an alternative solution, if you have apache commons library imported in the project, you can use isNumeric method of StringUtils class, e.g.:
StringUtils.isNumeric(phoneNum);
You can use this:
/* Check is numeric */
StringUtils.isNumeric(yourNumber);
or REGEX to avoid all characters diferente of numbers.
`{\\d+}`
I wanted to post the solution I came up with, for a few reasons but mainly so that if so some one is having issues and they're intentionally avoiding Arrays, regex etc.. they can have a good example!
import java.util.Scanner;
public class Example
{
public static void main(String[] args)
{
boolean isNumber = false;
String phoneNum = "";
Scanner input = new Scanner(System.in);
while(!isNumber)
{
isNumber = true;
System.out.print("\nEnter your 10 digit phone number (ex: 4142317534): ");
phoneNum = input.nextLine();
for(int i = 0; i < phoneNum.length(); i++)
{
if(!Character.isDigit(phoneNum.charAt(i)))
{
isNumber = false;
}
}
if(phoneNum.length() != 10)
{
isNumber = false;
}
if(isNumber == false)
{
System.out.println("\n\nInvalid format - please reenter");
}
}
System.out.println("\n\nPhone Number: " + phoneNum);
}
}
Yes it's a lot of code yes it can be condensed, but it's more important to learn and understand how things work and why they work they way they do before you attempt to be efficient, efficiency comes with learning and working the more you do the better you get and the more waste you cut out!

method declaration

I haven't been programming for long and this is my first time declaring a method within my program and using this method in the program. In its simplicity, the program has the user enter a 5 digit zipcode and the method I created checks that the zipcode is only 5 characters and is all digits. When I use the method in the program no matter what I enter for the zipcode, the while statement runs asking me to input my zipcode again. This should only happen if you enter a string thats not five characters or a string without only digits. However, right now it is happening even when an actual zipcode is entered, leaving me to assume something is wrong with the method. I tried to be as clear as possible in the question but if any further clarification is needed I can try to clear things up, any info you can give would be appreciated. Here is my code:
import java.util.Scanner;
public class BarCode {
public static void main(String[] args) {
String zipcode;
Scanner in = new Scanner(System.in);
System.out.println("Please enter a 5 digit zipcode: ");
zipcode = in.nextLine();
while (checkInput(zipcode) == false) {
System.out.println("You did not enter a 5 digit zipcode: ");
zipcode = in.nextLine();
} // end while
} // ends main
public static boolean checkInput(String zipcode) {
boolean zipcodeLength = true;
boolean zipcodeDigits = true;
if (zipcode.length() != 5) {
zipcodeLength = false;
} // end if statement
for (int i = 0; i <= zipcode.length(); i++) {
if (!Character.isDigit(i)) {
zipcodeDigits = false;
} // end if statement
} // end for statement
if (zipcodeLength == false || zipcodeDigits == false) {
return false;
} // end if statement
else {
return true;
} // end else statement
} // end checkInput
}
This is your problem :
if(!Character.isDigit(i))
should be
if(!Character.isDigit(zipcode.charAt(i)))
import java.util.Scanner;
public class BarCode{ public static void main(String[] args){
String zipcode;
Scanner in = new Scanner(System.in);
System.out.println("Please enter a 5 digit zipcode: ");
zipcode = in.nextLine();
while (checkInput(zipcode)==false){
System.out.println("You did not enter a 5 digit zipcode: ");
zipcode = in.nextLine();
}
}
public static boolean checkInput(String zipcode){
boolean zipcodeLength = true;
boolean zipcodeDigits = true;
if (zipcode.length() != 5){
zipcodeLength = false;
} // end if statement
for (int i=0; i<zipcode.length();i++){
if(!Character.isDigit(zipcode.charAt(i))){
zipcodeDigits = false;
}
}
return zipcodeLength && zipcodeDigits;
} // end checkInput
}
There are two problems.
The first is that you're going <= when you need to be doing <.
The second is that you need to check zipcode.charAt(i) instead of i. Checking i will check the digits 0 - 4 (5 with your code) for a 5 digit zipcode no matter what zipcode you enter.
So those two lines become
for ( int i=0; i<zipcode.length();i++){
if(!Character.isDigit(zipcode.charAt(i))){
Alternatively, I personally would code this method like this:
public static boolean checkInput(String zipcode){
if(zipcode.length() != 5) return false; // bad length
for(int i = 0; i < zipcode.length(); i++) {
if(!Character.isDigit(zipcode.charAt(i)) // bad digit
return false;
}
return true; // if no bad condition, it's good
}
while (zipcode.matches("[0-9]{5}"))==false){
System.out.println("You did not enter a 5 digit zipcode: ");
zipcode = in.nextLine();
}
public static boolean checkInput(String zipcode){
if (zipcode.length() != 5){
return false;
}
for ( int i=0; i<zipcode.length();i++){
char charAt = zipcode.charAt(i);
if(!Character.isDigit(charAt)){
return false;
}
}
return true;
}
You needed to use charAt instead of seeing if i was a digit, because obviously it will be.
!Character.isDigit(i)
That looks like a mistake to me. i is of type int:
for (int i = 0; i <= zipcode.length(); i++) {
// ...
}
So you're not calling Character.isDigit(char), you're calling Character.isDigit(int). The two methods behave differently: one deals with a text characters while the other deals with a numeric unicode value. Try this:
System.out.println("= char '1' =");
System.out.println(Character.isDigit('1')); // true
System.out.println("= int 1 =");
System.out.println(Character.isDigit(1)); // false
System.out.println("= Unicode 31h (49) =");
System.out.println(Character.isDigit('\u0031')); // true
System.out.println("= int 49 =");
System.out.println(Character.isDigit(49)); // true
And you'll get the following output:
= char '1' =
true
= int 1 =
false
= Unicode 31h (49) =
true
= int 49 =
true
You need not store the boolean value false in some boolean variable. Just return the moment you find that the zipcode is invalid.
And you should do : -
!Character.isDigit(zipcode.charAt(i))
in place of: -
!Character.isDigit(i)
So, you can modify your method like this: -
public static boolean checkInput(String zipcode){
if (zipcode.length() != 5){
return false;
}
for ( int i = 0; i < zipcode.length(); i++){
if(!Character.isDigit(zipcode.charAt(i))){
return false;
}
}
return true;
}
Also, you don't need to do :- booleanVar == false. Just do : - !booleanVar thats enough.

Categories