Java check if parameter contains vowels - java

I am kind of new to Java coming from a JavaScript background. I am trying to check if a given parameter contains vowels and if so, return true. This is what I have so far:
public class StringUtils {
public static boolean isVowel(String s) {
String x = s.toLowerCase();
if(x.indexOf('a' || 'e' || 'i' || 'o' || 'u')) {
return true;
} else {
return false;
}
}
}
How should this be done in Java?

You can try this method to check for vowels:
public static boolean isVowel(char c) {
return "AEIOUaeiou".indexOf(c) != -1;
}
You can try regex also:
yourString.matches("[AEIOUaeiou]")
smth like that

Related

How to check if a string is only number values

I am trying to run a recursion function where i check each character in the string to see if the character is a numeric number, however im a little stuck as the function runs and only checks the first character of the string
public static boolean isNumeric(String str) {
if(str == null)
{
return false;
}
if(str=="") {
return true;
}
char first = str.charAt(0);
if(Character.isDigit(first))
{
return true;
}
if(Character.isDigit(first) == false)
{
return false;
}
String reduced = str.substring(1);
return isNumeric((reduced)); }
Not 100% sure if I understood you correctly. If you want to check, if the string contains numeric values just see my other examples further down.
Otherwise, if you want to check, if the string contains exclusively numerical signs and digits you could do something like:
public static boolean isInteger(String numericValue) {
if (numericValue == null) return false;
try {
Integer.parseInt(numericValue);
return true;
} catch (NumberFormatException e) {
return false;
}
}
Please note, that this example does only work for Integers. If you
want to use bigger numbers, we can use Long or even BigDecimal
instead. But the main idea stays the same - check, if it can be parsed.
Or probably more appealing:
public static void main(String args[]) {
System.out.println(MyClass.isNumeric(""));
System.out.println(MyClass.isNumeric(null));
System.out.println(MyClass.isNumeric("abc"));
System.out.println(MyClass.isNumeric("a2b"));
System.out.println(MyClass.isNumeric("1a2b3"));
System.out.println(MyClass.isNumeric("42"));
System.out.println(MyClass.isNumeric("-100"));
}
public static boolean isNumeric(String str) {
if (str == null) return false; // handle null-pointer
if (str.length() == 0) return false; // handle empty strings
// to make sure that the input is numeric, we have to go through the characters
for (char c : str.toCharArray()) {
if (!Character.isDigit(c)) return false; // we found a non-digit character so we can early return
}
return true;
}
This will only print true for 42. The other examples contain other characters, too.
There are multiple issues with your code:
if(str=="") {
return true;
}
For string comparison you should use the String.equals() method - there are alternatives to that for example for your use-case you could use the convenience method String.isEmpty() or you could also just check the length of the string.
if(Character.isDigit(first))
{
return true;
}
if(Character.isDigit(first) == false)
{
return false;
}
This is some kind of if-else structure here. No need to check the same condition twice. Besides, it won't work with your recursive approach, because for what you want to achieve you need the current state which is "have I already found a digit". You could solve that with a memoized recursive function where you pass the current state along as a second argument to each subsequent call.
In your case it will return the result of the latest iteration / the
latest character.
You could do something like the following instead of using recursion. Recursion is fine, but it also comes with some costs. For example is it arguably harder to read and maintain.
public static void main() { ... } // same as above
public static boolean isNumeric(String str) {
if (str == null) return false; // handle null-pointer
if (str.length() == 0) return false; // handle empty strings
boolean atLeastOneDigit = false;
// to make sure that the input is numeric, we have to go through the characters
// until we find the first one then we can early return
for (char c : str.toCharArray()) {
if (Character.isDigit(c)) {
atLeastOneDigit = true; // we found a digit, therefore it must be numeric
break; // early return to save some iterations
}
}
return atLeastOneDigit;
}
The output of the program is:
false
false
false
true
true
true
true
Another alternative is to use Regex:
private static final Pattern digitRegex = Pattern.compile("\\d+");
public static main() { ... } // same as above
public static boolean isNumeric(String str) {
if (str == null) return false;
Matcher matcher = MyClass.digitRegex.matcher(str);
return matcher.find();
}
I am trying to explain you to solve this problem by two string methods that is isDigit(character) and charAt(i). In this case we will try to solve this problem by for loop. we will apply for loop in order to check every character of a string whether it is digit or not. If it is digit we will return true otherwise false.
Code is looks like this :
import java.lang.*;
import java.util.Scanner;
class Main {
public boolean containsDigit(String str) {
byte flag = 0;
for (int i = 0; i < str.length(); i++) {
if (Character.isDigit(str.charAt(i))) {
flag = 1;
}
}
if (flag == 1) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string : ");
String str = sc.nextLine();
Main test = new Main();
boolean chkDigit = test.containsDigit(str);
if (chkDigit == true) {
System.out.println("String contains digit.");
} else {
System.out.println("String doesn't contain any digit.");
}
}
}

Detecting last character

Im trying to detect whether the last character of a string contains an operator using an array checker that was previously used for integers. For some reason the code will always display "Not In" Even if the last character is an operator
class Main {
public static boolean useLoopString(String[] arr, String targetValue)
{
for (String s : arr) {
if (s == targetValue)
return true;
}
return false;
}
public static void main(String[] args) {
String[] op={"+","-","×","÷"};
String eq = "43+4+";
String eqLast=eq.substring(eq.length()-1);
System.out.println(eqLast);
boolean in=useLoopString(op,eqLast);
if(in){
System.out.println("In");
}
else{
System.out.println("Not In");
}
}
}
You can use char to compare, like this:
public static boolean useLoopString(char[] arr, char targetValue) {
for (char ch : arr) {
if (ch == targetValue)
return true;
}
return false;
}
public static void main(String[] args) {
char[] op = { '+', '-', '×', '÷' };
String eq = "43+4+";
char eqLast = eq.charAt(eq.length() - 1);
boolean in = useLoopString(op, eqLast);
if (in) {
System.out.println("In");
} else {
System.out.println("Not In");
}
}
Using == on class objects checks whether the two objects are the exact same instance, rather than whether the objects are equivalent, as you are intending. Instead, you should use .equals as Strings are classes:
public static boolean useLoopString(String[] arr, String targetValue) {
for (String s : arr) {
if (s.equals(targetValue))
return true;
}
return false;
}
String equality should be checked using the equals method. One should not use the object reference comparison.
In your case s and targetValue might be logically equal but may or may not point to the same String object.
Therefore, replace
if (s == targetValue)
with
if (s.equals(targetValue))
Also, null check should be made before making method calls on any object.
typically in production world, Edge cases if array has null element, you end up with null pointer exception.
always safe to use if(s!=null && s.equals(targetValue))
or
use apache's StringUtils.equals(String a, Strin b)

Check a string for consonants

I want to write a method to check a string for consonants using either .contains or .indexOf.
I guess I could do it the long way and check for every consonant in the alphabet but I know there is a better way. This is what I have so far but like I said this is sort of the long way, I think.
public boolean containsConsonant(String searchString) {
if(searchString.contains("b") || searchString.contains("c")){
return true;
}
I think a simple for loop is most readable here, you can test that a character is within the desired range with a boolean and. And you can use an or test to skip vowels. Something like,
public boolean containsConsonant(String searchString) {
if (searchString == null) {
return false;
}
for (char ch : searchString.toCharArray()) {
char lower = Character.toLowerCase(ch);
if (lower >= 'a' && lower <= 'z') {
if (lower == 'a' || lower == 'e' || lower == 'i' ||
lower == 'o' || lower == 'u') continue;
return true;
}
}
return false;
}
Optimization
You could then optimize the above (and directly to your question) by using contains on an extracted constant String of vowels. Something like,
private static final String vowels = "aeiou";
public static boolean containsConsonant(final String searchString) {
if (searchString == null) {
return false;
}
for (char ch : searchString.toCharArray()) {
char lower = Character.toLowerCase(ch);
if (lower >= 'a' && lower <= 'z' && !vowels.contains(String.valueOf(lower))) {
return true;
}
}
return false;
}
I see that you explicitly ask using contains or indexOf
in case - if you can use matches - it would be very easy to implement.
public boolean containsConsonant(String searchString){
String consonants = ".*[bcdfghj].*"; //list the characters to be checked
return searchString.matches(consonants);
}
you can create say an array containing all consonants and then run it using a loop
e.g.
String[] consonants{"b", "c",....}
boolean containsConsonants(String searchString, String[]arr){
for (String consonant: arr){
if(searchString.contains(str)){ return true} return False

Password Validator

I'm currently trying to make a password validator work with boolean method, since the teacher asked us to do so. This is driving me nuts. To be correct, the password need to have one uppercase, one lower case letter, at least 10 characters and one number. I'm aware that right now, my method returns entirely with the value false, but I'm wondering how I can break the code once I have one uppercase, or one lowercase.
Thanks a lot for your help!
public class AtLeast1UppercaseLowercaseNumber {
public static void main(String[] args){
String password = "H";
System.out.println(password);
if(isSecurePassword(password)){
System.out.println("Yay it works");}
else {
System.out.println("you suck");}
}
public static isSecurePassword(String password) {
int uppercase = 0, lowercase = 0, number = 0;
for(int i=0; i<password.length(); i++) {
for(char c ='A'; c <='Z'; c++) {
if(password.charAt(i) == c) {
uppercase++;
if( uppercase >= 1) {
for(char t = 'a'; t <='z'; t++) {
if(password.charAt(i) == t) {
lowercase++;
if(lowercase >= 1) {
}
}
}
for(int j = '0'; j <='9'; j++) {
if(password.charAt(i) == j) {
number++;
if( number >= 1) {
}
}
}
}
return false;
}
}
I suggest you start by creating multiple private and static test methods, and then delegate to them in your public isSecurePassword(String) method. Implement test methods like boolean oneUpper(String), boolean oneLower(String), boolean oneDigit(String) and boolean tenCharacters(String) as an example
private static boolean tenCharacters(String str) {
return str.length() > 9;
}
and a second example
private static boolean oneUpper(String str) {
for (char ch : str.toCharArray()) {
if (Character.isUpperCase(ch)) {
return true;
}
}
return false;
}
Then your isSecurePassword(String) is just
public static boolean isSecurePassword(String str) {
return tenCharacters(str) && oneUpper(str) && oneLower(str)
&& oneDigit(str);
}
Since there is only one return in this method, which explicitly returns false, this method will always return false.
Method 1:
Define a boolean, which will be returned in the last statement of the method. This boolean is true by default and will be set false if one condition is wrong.
Method 2:
The last statement is an implicit return true statement, and whenever a condition is not fullfilled return false. This will prevent the method from executing more tests.
Method 3:
Make the method look like this
if (containsUpperCase(string) && contains...)
return true;
return false;

Checking JSP Input for "Empty"

In my testing, the following seems to cover everything I can think of in terms of ensuring that a field is populated. Can anyone think of a case I might have missed?
public static boolean isEmpty(final String string) {
return string != null && !string.isEmpty() && !string.trim().isEmpty();
}
The name is a bit misleading as the method is labeled "isEmpty" but will return true when it's not empty... but that's up to you.
I would change your AND statements to ORs and remove the middle term as it is superfluous e.g.
public static boolean isEmpty(final String string) {
return string == null || string.trim().isEmpty();
}
EXAMPLE:
if(isEmpty(null)){
System.out.println("Empty");
}else{
System.out.println("Not Empty");
}
if(isEmpty("")){
System.out.println("Empty");
}else{
System.out.println("Not Empty");
}
if(isEmpty(" ")){
System.out.println("Empty");
}else{
System.out.println("Not Empty");
}
if(isEmpty("Test")){
System.out.println("Empty");
}else{
System.out.println("Not Empty");
}
OUTPUT:
Empty
Empty
Empty
Not Empty
Why don't you just use a library?
One example is Apache's Common Utils:
StringUtils.isBlank()
StringUtils.isNotBlank()
Apache Commons StringUtils uses the following techniques:
isEmpty:
public static boolean isEmpty(String str) {
return str == null || str.length() == 0;
}
isBlank:
public static boolean isBlank(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
}
You can just do:
public static boolean isEmpty(String string) { //don't make it final going in or you cant trim it.
string = string.trim();
return string != null || string.length() == 0;
}

Categories

Resources