How to use IndexOf to see if a string contain numbers - java

I need to use indexOf to find numbers inside a string, and it gives me the error:
Type mismatch: cannot convert from int to boolean.
public static boolean validPassword(String password) {
if(password.length() >= 8 ){
return true;
}
else if (password.indexOf("0")) {
return true;
}
return false;
}

Don't use index. You can use String.matches().
String str = "ksksks8ksksksksksks";
System.out.println(str.matches(".*\\d.*"));
Honestly though, if you can do it anyway you want, I would simply write a method as follows. Regular expressions are great for complicated patterns but they are also expensive in terms of processing.
public static boolean containsNumber(String str) {
boolean found = false;
for (char c : str.toCharArray()) {
if (Character.isDigit(c)) {
found = true;
break;
}
}
return found;
}
You could also modify the above and call it indexOf and iterate thru the characters using a regular for loop. Then returning either the location of the first digit or -1 just like the String version of indexOf().
And finally, for fun, you could use the Streams capability of Java 8+.
public static boolean containsNumber(String str) {
return str.chars().filter(Character::isDigit).count() > 0;
}

Related

Can this While loop be simplified?

Consider the following code. It is for check if the String has valid parenthesis but without using stack.
public boolean isValid(String input) {
while(input.length() != (input = input.replaceAll("\\(\\)|\\[\\]|\\{\\}", "")).length());
return input.isEmpty();
}
But Kinda difficult to understand. Can this be simplified? Without adding more number of new lines?
It helps if you first format and indent it properly:
public boolean isValid_2(String input) {
while(input.length() != (input = input.replaceAll("\\(\\)|\\[\\]|\\{\\}", "")).length())
;
return input.isEmpty();
}
Next, notice that the method doesn't depend on instances of its class, so can be static. Also, remove redundant escapes from the regex:
public static boolean isValid_3(String input) {
while(input.length() != (input = input.replaceAll("\\(\\)|\\[]|\\{}", "")).length())
;
return input.isEmpty();
}
Finally, break up the complicated statement into easy-to-understand parts, and introduce some variables with meaningful names, and then change the type of loop to something more useful, and you have your final version:
public static boolean isValid_4(String input) {
int oldLength, newLength;
do {
oldLength = input.length();
input = input.replaceAll("\\(\\)|\\[]|\\{}", "");
newLength = input.length();
} while (oldLength != newLength);
return input.isEmpty();
}
My simplification is this:
static boolean isValid(String input) {
String t = input, s;
do {
s = t;
t = s.replaceAll("\\(\\)|\\[\\]|\\{\\}", "");
} while (s.length() != t.length());
return t.isEmpty();
}
which, though longer, makes it easier IMO to see what's going on. I like brevity, but it's not always best.
This differs from other simplification answers in that it focuses more on the remaining strings than on the lengths, which to my mind is more to the point. But at some point, this is a matter of aesthetics.
(Also, you can conveniently stick a "print" after the assignments in the loop, to see what is really happening - I did this to debug my incorrect comment)
Note: The question has been updated after I've answered the question. So, if doesn't fulfill the questions answer's each and every aspect, then please just ignore it.
let's see:
public boolean isValid(String input) {
int prevLength = input.length();
input = input.replaceAll("\\(\\)|\\[\\]|\\{\\}", "");
while(prevLength != input.length()) {
prevLength = input.length();
input = input.replaceAll("\\(\\)|\\[\\]|\\{\\}", "");
}
return input.isEmpty();
}
I guess its enough simplified...

+ compareTo(wordtoCompare : Word) : Integer Java

Currently I am working on a project in which I have to use this UML diagram to create and additional class I understand everything but I am baffled by the last line.
compareTo(wordToCompare : Word) : Integer
Since Word is the name of the class how would I insert an argument? I tried inputting an Object as an argument but it says:
Object is an incompatible type with Word.
I researched if Word was a non primitive data-type but could not find any information. I am rather inexperienced and quite confused if anyone could lend some assistance I would be greatly appreciative.
Word class UML
-wordCharacters : String
-count : integer
+ CONSTRUCTOR (word : String)
+ getWord() : String
+ getCount() : Integer
+ incrementCount() : void
+ toString() : String
+ equals(wordtoCompare : Object) : Boolean
+ compareTo(wordtoCompare : Word) : Integer
#Override
public boolean equals(Object wordtoCompare) {
boolean flag = false;
String currentWord = wordtoCompare.getClass().getName();
this.compareTo(wordtoCompare);
return flag;
}
public Integer compareTo(Word wordtoCompare) {
return 0;
}
you are overriding the equals method and it should look a bit like this.
You need to check if the Object wordtoCompare is of the type Word or if it´s the current object. After you did check if it´s a type or subtype of Word you can cast the wordtoCompare to an actuall Word object and do your stuff with it.
#Override
public boolean equals(Object wordtoCompare) {
boolean flag = false;
if(wordtoCompare == this) return true;
if(!(wordtoCompare instanceof Word)) return false;
Word word = (Word)wordtoCompare;
this.compareTo(word);
// Whatever you do with your flag
return flag;
}
Something like this I guess
class Word{
String wordCharacters;
int count;
public Word(String word){
...
}
.. other stuff
public int compareTo(Word other){
return wordCharacters.compareTo(other.wordCaracters)
}
}
You can just create the compareTo Method having a Word parameter. (Word is the class you're currently creating)
public class Word{
....
public int compareTo(Word wordToCompare){
int result = 0;
//do your compare stuff
return result;
}
}
If this isn't your problem, I may did not understand the problem properly
Edit:
Your equals Method looks the following:
public boolean equals(Object wordtoCompare) {
boolean flag = false;
String currentWord = wordtoCompare.getClass().getName();
this.compareTo(wordtoCompare);
return flag;
}
But you have to make sure, that the Object you're working with is really a Word.
#Override
public boolean equals(Object wordtoCompare) {
boolean flag = false;
if(wordtoCompare == this) return true;
if(!(wordtoCompare instanceof Word)) return false;
Word word = (Word)wordtoCompare;
int compareResult = this.compareTo(wordtoCompare);
// Whatever you do with your flag
return flag;
}
This method is taken from Kevin Esche, as he implemented this method properly. Thank you.
And then you have to implement compareTo properly.

All combinations of alphanumeric string, better way?

The input to the "alphaNumeric" function is a String which consists of alphanumeric characters that are all lower case, for example "hello123hello". I want to be able to check all upper/lower case letter combinations for this string through a check( ) function. (Eg. HeLlO123hELlo is one of the combinations to be checked). I have written code in Java to do this where I store the matching String into an ArrayList, but would like to know if there a better way to do this without the ArrayList. Also, am I correct in saying the worst case runtime of this is O(2^n)? Note: Check is a function that returns either true or false, depending on whether the correct String is passed to the function.
public static String alphaNumeric(String input) {
ArrayList<String> list = new ArrayList<String>();
alphaHelper(input, "", list);
return list.get(0);
}
private static void alphaHelper(String in, String current, ArrayList<String> list) {
if (in.length() == 0) {
if (check(current)) {
list.add(current);
}
} else if (Character.isLetter(in.charAt(0))) {
alphaHelper(in.substring(1),current+in.substring(0,1).toLowerCase(),list);
alphaHelper(in.substring(1),current+in.substring(0,1).toUpperCase(),list);
} else if (Character.isDigit(in.charAt(0))) {
alphaHelper(in.substring(1),current+in.substring(0,1),list);
} else {
return;
}
}
If you just want to remove the ArrayList without changing your basic algorithm, you can do this:
public static String alphaNumeric(String input) {
return alphaHelper(input, "");
}
private static String alphaHelper(String in, String current) {
String result = null;
if (check(current)) {
result = current;
} else if (Character.isLetter(in.charAt(0))) {
result = alphaHelper(in.substring(1),current+in.substring(0,1).toLowerCase());
if (result == null) result = alphaHelper(in.substring(1),current+in.substring(0,1).toUpperCase());
} else if (Character.isDigit(in.charAt(0))) {
result = alphaHelper(in.substring(1),current+in.substring(0,1));
}
return result;
}
Yes it is O(2^n), and I can't see offhand how you would improve on that if you can't get the original string directly.
If you don't need to check substrings (i.e. you only care about case variations of the entire string) you could improve the algorithm by not testing the substrings, but it would still be O(2^n).
You could temporarily set both the check and input to lowercase and compare them then.
public static boolean alphaNumeric(String input, String check) {
return input.toLowerCase().equals(check.toLowerCase());
}
-Sean

how to know if a string is inside an array on Android?

Hi everybody im programming an application in Android and I don`t know what to do to get this that I am trying. I now that it is very simple but please help me!
Lets say that I have an array:
String coco[] = { "hi", "everybody", "superman", "batman" };
And also I have a:
String heroe = "superman";
Now I need to make a loop, method or whatever, that takes "heroe" and search if that value ("superman") its inside the array and then so if that value exist TRUE and if don`t exist FALSE.
Thank you guys.
The most comfortable way is to convert the array to a list and search then.
It is clean, short and expressive.
boolean isThere = Arrays.asList(yourArray).contains("needle");
for(int i=0;i<coco.length;i++)
{
if(coco[i].equals(heroe))
return true;
}
Here is a simple solution. It would be easier to use an ArrayList that can use .contains ()method.
for(int i = 0; i < coco.length; i++)
{
if(coco[i].equals(heroe))
{
// a match!
return true;
}
}
// no match
return false;
Simply iterate over the values in the array and compare them to the value you're looking for
public boolean arraySearch(String[] strArray, String key) {
for (String s : strArray) {
if (s.equals(key)) {
return true;
}
}
return false;
}
You can use this by calling arraySearch(coco, heroe); in your code.
Alternatively you could use the Arrays class and use:
boolean keyPresent = Arrays.asList(coco).contains(heroe);
you could do some thing like this:
for (String testcoco : coco)
{
if (testcoco.contains("superman"))
{
return true;
}
}
return false;
You can do like this.
Just take a variable which you want to search and iterate the array and use equals method.
String heroe = "superman";
boolean flag = false;
for(int index = 0; index < coco.length; index++)
{
Strin value = coco[index];
if(heroe.equals(value))
{
flag = true;
}
}
if(flag) {
//Exist
}
else {
//Not Exist
}
public boolean checkPresence(String desired)
for(String s:coco){
if(s.equals(desired)){
return true
}
}
return false;

How do I check for nulls and empty string for a needle in a haystack?

Situation: I am coming across a lot of checks in my code. And I would like to know of a way in which I can reduce them.
if(needle!=null && haystack!=null)
{
if(needle.length()==0)
return true;
else
{
if(haystack.length()==0)
return false;
else
{
// Do 2 for loops to check character by character comparison in a substring
}
}
}
else
return false;
Perhaps a different code style would increase the readability of your code and reduce the amount of nested if statements for all of your checks.:
if (needle == null || haystack == null || haystack.isEmpty())
return false;
if (needle.isEmpty())
return true;
// compare strings here and return result.
You could consolidate that logic into a single method on a singleton 'StringFunctions' class and update the usages to use the common method as you encounter them.
You can create a wrapper class for the strings, then add a function like isValid() to them that checks if the length == 0. Use a Null Object that always returns false on isValid() to eliminate the null checks.
If you can create classes that you tell what to do, rather than passing strings that have to be null checked throughout your code, you will get more resuseable results:
class Haystack {
private static final Haystack NULL_HAYSTACK = new Haystack("");
private final String value;
public Haystack(String value) {
this.value = value;
}
public boolean containsNeedle(String needle) {
return needle != null && value.contains(needle);
}
}

Categories