check password for digits and letters - java

I have problem with two of my methods for password validation.
The method hasDigitsAndLetters is supposed to check whether all the characters of the String are digits and letters and the second method hasTwoDigits is supposed to check whether there are at least two digits in the pass, but the problem is that for expected result true they are ruturning false. If someone can help. here is the code.
//check if the whole string consists of digits and letters
public static boolean hasDigitsAndLetters(String pass)
{
for(int i=0; i<pass.length(); i++)
{
if(!Character.isLetterOrDigit((i)))
{
return false;
}
}
return true;
}
// check whether the password has at least 2 digits
public static boolean hasTwoDigits(String pass)
{
int counter = 0;
for(int i=0; i<pass.length(); i++)
{
if(Character.isDigit(i))
{
counter ++;
}
}
System.out.println("Number of digits: " + counter);
if(counter >= 2)
{
return true;
}
return false;
}

You need to pass character at position i for that String.
Character.isLetterOrDigit((pass.charAt(i)))
same for digit also
Character.isDigit((pass.charAt(i)))

You want to check the character in the string at index i, not the index variable itself:
Character.isLetterOrDigit(pass.charAt(i))

You aren't checking against characters in your pass, you need to change your checks to:
if(!Character.isLetterOrDigit((pass.charAt(i)))
and
if(Character.isDigit(pass.charAt(i)))

Right now you are checking if i is a digit or letter and i is an int. You need to check the character at position i.
if(Character.isDigit(pass.charAt(i)))

The error is that you're comparing the position into the string rather than the character at that position in the string. I'd probably not use charAt, however... there's no point in keeping explicit management of the position here. I suggest you use String.toCharArray instead.
public static boolean isAlphanumeric(final String str) {
for (char c : str.toCharArray()) {
if (!Character.isLetterOrDigit(c)) {
return false;
}
}
return true;
}
public static boolean isBidigital(final String str) {
int n = 0;
for (char c : str.toCharArray()) {
if (Character.isDigit(c)) {
++n;
}
}
return n >= 2;
}

Related

Find the amount of occurances of a character in a string recursively (java)

I am trying to write a method which returns the number of times the first character of a string appears throughout the string. This is what I have so far,
public int numberOfFirstChar0(String str) {
char ch = str.charAt(0);
if (str.equals("")) {
return 0;
}
if ((str.substring(0, 1).equals(ch))) {
return 1 + numberOfFirstChar0(str.substring(1));
}
return numberOfFirstChar0(str);
}
however, it does not seem to work (does not return the correct result of how many occurrences there are in the string). Is there anything wrong with the code? Any help is appreciated.
This uses 2 functions, one which is recursive. We obtain the character at the first index and the character array from the String once instead of doing it over and over and concatenating the String. We then use recursion to continue going through the indices of the character array.
Why you would do this I have no idea. A simple for-loop would achieve this in a much easier fashion.
private static int numberOfFirstChar0(String str) {
if (str.isEmpty()) {
return 0;
}
char[] characters = str.toCharArray();
char character = characters[0];
return occurrences(characters, character, 0, 0);
}
private static int occurrences(char[] characters, char character, int index, int occurrences) {
if (index >= characters.length - 1) {
return occurrences;
}
if (characters[index] == character) {
occurrences++;
}
return occurrences(characters, character, ++index, occurrences);
}
Java 8 Solution
private static long occurrencesOfFirst(String input) {
if (input.isEmpty()) {
return 0;
}
char characterAtIndexZero = input.charAt(0);
return input.chars()
.filter(character -> character == characterAtIndexZero)
.count();
}
Here is a simple example of what you are looking for.
Code
public static void main(String args[]) {
//the string we will use to count the occurence of the first character
String countMe = "abcaabbbdc";
//the counter used
int charCount=0;
for(int i = 0;i<countMe.length();i++) {
if(countMe.charAt(i)==countMe.charAt(0)) {
//add to counter
charCount++;
}
}
//print results
System.out.println("The character '"+countMe.charAt(0)+"' appears "+ charCount+ " times");
}
Output
The character 'a' appears 3 times

How to check that one String can be spelled using characters from another String?

Example: String a = "ACAHBBA" and String b = "ABAB" should return true, since both strings can spell ABAB.
I have tried with contains(), but that only works for equal sequences.
// The code should look like this.
public class task10 {
public static boolean contains(String a, String b) {
// check if b can be spelled using characters from a.
// if it can. return true.
// else
return false;
}
}
Posible solution?
public static boolean contains(String a, String b) {
for (int i = 0; i < b.length(); i++) {
if (a.indexOf(b.charAt(i)) == -1) {
return false;
}
}
return true;
}
Simply iterate thru one string and get the index of the character. If >= 0, replace character with non-alphabetic character and repeat. This algorithm presumes the need to match the correct number of characters. For example, hello would return false if the character set was helo.
public static boolean spelledFrom(String word, String chars) {
StringBuilder sb = new StringBuilder(chars);
for (String c : word.split("")) {
int i;
if ((i = sb.indexOf(c)) < 0) {
return false;
}
sb.setCharAt(i, '#');
}
return true;
}
You can try this:
public static boolean canSpell(String a, String b)
{
String shorter = (a.length() <= b.length()) ? a : b;
String longer = (shorter.equals(a)) ? b : a;
for(int i = 0; i < shorter.length(); i++)
{
if(!longer.contains("" + shorter.charAt(i)))
return false;
}
return true;
}
Once you've identified the shorter string, you just need to verify that each of its chars are contained in the longer string. This solution doesn't verify if a char "has already been used", which means inserting "AB" and "ABBA" will return true. If you need to do this, you just need to delete the verified char from the longer string in every loop.

Question >> print "True" or "False" if the string contains two or more characters

I have to make a method named 'contains' that accepts a string and a character as parameters and returns true if that character occurs two or more times in the string.
example: Input contains("Apple", 'p') should return "True"
private boolean contains(String a,char b) {
if(a.contains(b)) {
print("true");
}
else {
print("");
}
//boolean c = a.contains('l');
return false;
}
I know this code is wrong ... I want to know what I have to do and what I have to fix .
I would appreciate your advice
Thank you.
There are a few ways to do this but the simplest would just be to loop through the String looking for the char, if count reaches two then return true.
For this consider using
for (char c : input) {
if (c == myChar) count++;
if (count >= 2) return true;
}
return false;
Another way would be to use String.replace and replace the wanted char with ""
then compare the size of the before and after String
Your method may return a boolean based on the size difference between the original string, and the string without the given character :
return (a.length() - (a.replace(b, '')).length()) >= 2 ;
In theoretical terms:
First: you need to iterate over the input string characters using a for loop and then in each iteration compare the current character in the string with the other character argument which is given as method argument. If they match, then you can increase a counter (a variable). Then compare if the counter value is 2 and return true immediately it is so. At the method end you can return false just like you have done already.
Second : you are printing true , not returning true. Should use return true; when the value of variable becomes 2
countMatches(a,b) returns the count of b in String a. and it is from org.apache.commons.lang3
private boolean contains(String a,char b) {
return StringUtils.countMatches(a, b)>=2 ;
}
or in simple java you can use
private boolean contains(String a,char b) {
return (a.length() - a.replaceAll(String.valueOf(b),"").length())>=2 ;
}
This is one of simple ways to do this. Here the string is put into char array. This way it is easier to examine the elements of the char array and find out same characters.
private boolean contains(String a, char b) {
char[] c_array = a.toCharArray();
int count = 0;
for (int i = 0; i < c_array.length; i++) {
if (b == c_array[i]) {
count++;
continue;
} else {
continue;
}
}
if (count >= 2) {
return true;
} else {
return false;
}
}
public class Demo {
public static boolean contains(String str,char c){
//todo:check str for NullPointExecption
int flag=0;
for(int i=0;i<str.length();i++){
if(c==str.charAt(i)){
flag++; //if str contains char c,flag=flag+1
}
if(flag>=2){
return true; //if flag>=2,return true
}
}
return false;
}
public static void main(String[] args) {
System.out.println(contains("appple", 'p'));//result is true
}
}

Surrounded Character Method Java

I'm working on a java method that checks whether a character in an array of characters is surrounded by a character. Ex: abcdc, d is surrounded by c. Ex: abccc, has no letters that are surrounded. Here is what I have so far.
public static boolean surroundedCharacter(char[] letters){
boolean result = false;
for(char letter : letters)
if(letters[letter-1] == letters[letter+1]){
result = true;
}
return result;
} }
So I basically have a for each loop going through letter in letters and checks whether the letter before the position is equal to letter after the position. If it is, it means that the letter is surrounded and it should change result to true. The junit test says that the if statement is wrong, but I don't know how to fix it. Any help is appreciated.
You have to use an Integer for the index:
public static boolean surroundedCharacter(char[] letters){
boolean result = false;
for(int i = 1; i < letters.length - 1; i++) {
// You said that if the string is "abccc", should return false.
// So, we check if the previous or the next letter is different to
//the actual value of i
if((letters[i-1] == letters[i+1]) && (letters[i-1] != letters[i])) {
result = true;
}
}
return result;
}
Try this one:
public static boolean surroundedCharacter(char[] letters){
boolean result = false;
for( int i=1;i<letters.length-1;i++)
if(letters[i-1] == letters[i+1]){
result = true;
}
}
return result;}
You must use for loop instead of short for. Try this for loop:
for(int i = 1; i< letters.length-1; i++){
if(letters[i-1] == letters[i+1]){
result = true;
}
}
A Java foreach is designed to iterate element after element.
In case of need to get two distinct element at each iteration, you should use a classic for using a int value.
Besides, you don't need to have intermediary variable. When the condition is matched you can return true. Otherwise you return false after the loop.
At last, according to your needs :
Ex: abccc, has no letters that are surrounded.
you should accept the match only if the surrounded char differs from the chars that surround it.
public static boolean surroundedCharacter(char[] letters){
for(int i=1; i<letters.length-1; i++){
var beforeLetter = letters[i-1];
var afterLetter = letters[i+1];
if(beforeLetter == afterLetter && beforeLetter != letters[i]){
return true;
}
}
return false;
}

Check if String contains only letters

The idea is to have a String read and to verify that it does not contain any numeric characters. So something like "smith23" would not be acceptable.
What do you want? Speed or simplicity? For speed, go for a loop based approach. For simplicity, go for a one liner RegEx based approach.
Speed
public boolean isAlpha(String name) {
char[] chars = name.toCharArray();
for (char c : chars) {
if(!Character.isLetter(c)) {
return false;
}
}
return true;
}
Simplicity
public boolean isAlpha(String name) {
return name.matches("[a-zA-Z]+");
}
Java 8 lambda expressions. Both fast and simple.
boolean allLetters = someString.chars().allMatch(Character::isLetter);
Or if you are using Apache Commons, [StringUtils.isAlpha()].
First import Pattern :
import java.util.regex.Pattern;
Then use this simple code:
String s = "smith23";
if (Pattern.matches("[a-zA-Z]+",s)) {
// Do something
System.out.println("Yes, string contains letters only");
}else{
System.out.println("Nope, Other characters detected");
}
This will output:
Nope, Other characters detected
I used this regex expression (".*[a-zA-Z]+.*"). With if not statement it will avoid all expressions that have a letter before, at the end or between any type of other character.
String strWithLetters = "123AZ456";
if(! Pattern.matches(".*[a-zA-Z]+.*", str1))
return true;
else return false
A quick way to do it is by:
public boolean isStringAlpha(String aString) {
int charCount = 0;
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (aString.length() == 0) {
return false; //zero length string ain't alpha
}
for (int i = 0; i < aString.length(); i++) {
for (int j = 0; j < alphabet.length(); j++) {
if (aString.substring(i, i + 1).equals(alphabet.substring(j, j + 1))
|| aString.substring(i, i + 1).equals(alphabet.substring(j, j + 1).toLowerCase())) {
charCount++;
}
}
if (charCount != (i + 1)) {
System.out.println("\n**Invalid input! Enter alpha values**\n");
return false;
}
}
return true;
}
Because you don't have to run the whole aString to check if it isn't an alpha String.
private boolean isOnlyLetters(String s){
char c=' ';
boolean isGood=false, safe=isGood;
int failCount=0;
for(int i=0;i<s.length();i++){
c = s.charAt(i);
if(Character.isLetter(c))
isGood=true;
else{
isGood=false;
failCount+=1;
}
}
if(failCount==0 && s.length()>0)
safe=true;
else
safe=false;
return safe;
}
I know it's a bit crowded. I was using it with my program and felt the desire to share it with people. It can tell if any character in a string is not a letter or not. Use it if you want something easy to clarify and look back on.
Faster way is below. Considering letters are only a-z,A-Z.
public static void main( String[] args ){
System.out.println(bestWay("azAZpratiyushkumarsinghjdnfkjsaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
System.out.println(isAlpha("azAZpratiyushkumarsinghjdnfkjsaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
System.out.println(bestWay("azAZpratiyushkumarsinghjdnfkjsaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
System.out.println(isAlpha("azAZpratiyushkumarsinghjdnfkjsaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
}
public static boolean bettertWay(String name) {
char[] chars = name.toCharArray();
long startTimeOne = System.nanoTime();
for(char c : chars){
if(!(c>=65 && c<=90)&&!(c>=97 && c<=122) ){
System.out.println(System.nanoTime() - startTimeOne);
return false;
}
}
System.out.println(System.nanoTime() - startTimeOne);
return true;
}
public static boolean isAlpha(String name) {
char[] chars = name.toCharArray();
long startTimeOne = System.nanoTime();
for (char c : chars) {
if(!Character.isLetter(c)) {
System.out.println(System.nanoTime() - startTimeOne);
return false;
}
}
System.out.println(System.nanoTime() - startTimeOne);
return true;
}
Runtime is calculated in nano seconds. It may vary system to system.
5748//bettertWay without numbers
true
89493 //isAlpha without numbers
true
3284 //bettertWay with numbers
false
22989 //isAlpha with numbers
false
Check this,i guess this is help you because it's work in my project so once you check this code
if(! Pattern.matches(".*[a-zA-Z]+.*[a-zA-Z]", str1))
{
String not contain only character;
}
else
{
String contain only character;
}
String expression = "^[a-zA-Z]*$";
CharSequence inputStr = str;
Pattern pattern = Pattern.compile(expression);
Matcher matcher = pattern.matcher(inputStr);
if(matcher.matches())
{
//if pattern matches
}
else
{
//if pattern does not matches
}
Try using regular expressions: String.matches
public boolean isAlpha(String name)
{
String s=name.toLowerCase();
for(int i=0; i<s.length();i++)
{
if((s.charAt(i)>='a' && s.charAt(i)<='z'))
{
continue;
}
else
{
return false;
}
}
return true;
}
Feels as if our need is to find whether the character are only alphabets.
Here's how you can solve it-
Character.isAlphabetic(c)
helps to check if the characters of the string are alphabets or not.
where c is
char c = s.charAt(elementIndex);
While there are many ways to skin this cat, I prefer to wrap such code into reusable extension methods that make it trivial to do going forward. When using extension methods, you can also avoid RegEx as it is slower than a direct character check. I like using the extensions in the Extensions.cs NuGet package. It makes this check as simple as:
Add the https://www.nuget.org/packages/Extensions.cs package to your project.
Add "using Extensions;" to the top of your code.
"smith23".IsAlphabetic() will return False whereas "john smith".IsAlphabetic() will return True. By default the .IsAlphabetic() method ignores spaces, but it can also be overridden such that "john smith".IsAlphabetic(false) will return False since the space is not considered part of the alphabet.
Every other check in the rest of the code is simply MyString.IsAlphabetic().
To allow only ASCII letters, the character class \p{Alpha} can be used. (This is equivalent to [\p{Lower}\p{Upper}] or [a-zA-Z].)
boolean allLettersASCII = str.matches("\\p{Alpha}*");
For allowing all Unicode letters, use the character class \p{L} (or equivalently, \p{IsL}).
boolean allLettersUnicode = str.matches("\\p{L}*");
See the Pattern documentation.
I found an easy of way of checking a string whether all its digit is letter or not.
public static boolean isStringLetter(String input) {
boolean b = false;
for (int id = 0; id < input.length(); id++) {
if ('a' <= input.charAt(id) && input.charAt(id) <= 'z') {
b = true;
} else if ('A' <= input.charAt(id) && input.charAt(id) <= 'Z') {
b = true;
} else {
b = false;
}
}
return b;
}
I hope it could help anyone who is looking for such method.
Use StringUtils.isAlpha() method and it will make your life simple.

Categories