comparison with strings having white space - java

Sorry if it's a silly question. I need to compare with a name which has three words separated by one white space. If the name is null or "This is Android" i would do something, otherwise i do something else. For example, is the following code right to do this comparison?
if((name==null)||(name.equalsIgnoreCase("This is Android")))
{
//start activity 1
}
else
{
//start activity 2
}

"This is Android " is different from "This is Android" and equalsIgnoreCase will return false. You can use trim() to remove spaces and the start or the end of the Strings.
Hope this helps!

You should check if the name is null before you do that, otherwise it looks good. (except for, it should be if instead of If):
//either
if(name != null) {
if(name.equalsIgnoreCase("This is Android") {
}
}
//or
if("This is Android ".equalsIgnoreCase(name)) {
Update:
When you are comparing strings, the whitespaces count. So, basically "Hello world" and "Hello world " are not equal.
You need to use the .trim() method to ignore the surrounding whitespaces.
name = name.trim(); //since strings are immutable you need to assign return value to name
if("This is Android".equalsIgnoreCase(name)) {

Always keep constant String on left hand side in equals, this ensures no NPE:
like this :
if ("This is Android ".equalsIgnoreCase(str1)) {
// start activity 1
} else {
// start activity 2
}
In case you dont want space then add trim():
if ("This is Android ".trim().equalsIgnoreCase(str1)) {
// start activity 1
} else {
// start activity 2
}

if("This is Android".equalsIgnoreCase(name))
// start activity 1
} else {
// start activity 2
}
or the bullet-proof (in case user pasted value with unwanted spaces at the end of string)
if(name != null && "This is Android".equalsIgnoreCase(name.trim()))
// start activity 1
} else {
// start activity 2
}

Related

How to get all required strings in a string array before a break

We were given a task to make a program that takes the input of the user. there two types of input the user can use, 1st is the "Type in the Size" and the second is "Type in the style" either way the user can just input in the 1st field or the 2nd field. when the users clicks ok the two inputs will be use to sortout a arraylist which contains the type of size and style in it.
public void viewResult(String style, String size) {
style = style.toLowerCase();
size = size.toLowerCase();
new_list = new ArrayList<>();
for(Items_container items:current_arrayList)
{
if (items.getStyle().toLowerCase().contains(style) && items.getSize().toLowerCase().contains(size))
{
new_list.add(items);
break;
}
else if (items.getSize().toLowerCase().contains(size)) {
new_list.add(items);
break;
}
else if (items.getStyle().toLowerCase().contains(style)) {
new_list.add(items);
break;
}
}
current_arraylist.clear();
adapter.filterSearch(new_list);
if (new_list.size() == 0) {
results.setText("Search not found");
} else {
results.setText("Results");
}
}
this is the method that I use to sortout out the Items_container now it does work fine (I guess)
but the problem is for example the user inputs "large" in the size input field and "blazzing" in the style input field the program must sort the items_container using the given inputs but it is not working because the program also includes all the items that has the same size or the same style.
I tried adding a break to the loop but now it only shows one data and what if there two or more data that matches the givens inputs, how can I do that?
You should check first if both conditions are set. That way you can separate if either one matches and if both match. Maybe put singular matches in a separate list in case no items match both conditions, but that's up to you.
And as others already said, break stops the loop, continue moves to the next item.
like code below:
for (int i = 0; i <current_arrayList.size() ; i++) {
if(current_arrayList.get(i).getStyle().toLowerCase().contains(style)
&& current_arrayList.get(i).getSize().toLowerCase().contains(size))
{
new_list.add(current_arrayList.get(i));
//if used break ,stop loop
}
else if (current_arrayList.get(i).getSize().toLowerCase().contains(size)) {
new_list.add(current_arrayList.get(i));
}
else if (current_arrayList.get(i).getStyle().toLowerCase().contains(style)) {
new_list.add(current_arrayList.get(i));
}
}
current_arraylist.clear();
adapter.filterSearch(new_list);
adapter.notifyDataSetChanged();

Check whitespaces and isempty

I am looking for a if statement to check if the input String is empty or is only made up of whitespace and if not continue with the next input. Below is my code so far which gives an error when I input a whitespace.
name = name.trim().substring(0,1).toUpperCase() + name.substring(1).toLowerCase();
if(name != null && !name.isEmpty() && name.contains(" ")) {
System.out.println("One");
} else {
System.out.println("Two");
}
The reason it gives you an error is that trim() removes all leading and trailing whitespace [edited], so then your string is empty. At that point, you call substring(0,1), so it will be out of range.
I would write this as the following.
name = name == null ? "" : name.trim();
if(name.isEmpty()) {
System.out.println("Null, empty, or white space only name received");
} else {
System.out.println("Name with at least length one received");
name = name.substring(0,1).toUpperCase() + name.substring(1).toLowerCase();
}
I think, if you want to use just String methods, then you'll need matches(regex), possibly more than one.
I haven't tested this, but it might work...
String emptyOrAllWhiteSpace = "^[ \t]*$";
if (name == null || name.matches(emptyOrAllWhiteSpace)) {
// first thing.
} else {
// second thing.
}
There are alternatives in the Apache Commons Lang library - StringUtils.isEmpty(CharSequence), StringUtils.isWhitespace(CharSequence).
Guava has another helper Strings.isNullOrEmpty() which you can use.

finding which sub string comes first, which comes second and which comes third

String s="CCATGTTGGCCTAGGTGACAC";
I am trying to find an Open reading frame from above DNA sequence. First I have to find whether there is "ATG" present as a sub string. If it is there then I have to find out whether any one of these sub strings is present "TAA", "TAG", "TGA". Among these three sub strings whichever comes first is to be taken into considerartion and then I would print the string from "ATG" to "TAA" or "TAG" or "TGA" whichever comes first.
From above string output should be "ATG TTGGCC TAG".
You can get the index of each substring..
System.out.println(s.indexOf("ax"));
The one whose index is minimum is the one who comes first.
String testString = "ddddeeaxgghnnnbykkkkkklllllczfr";
String[] frags = testString.split("(ax|by|cz)");
if(frags.length >= 1) {
System.out.println("first=" + frags[0]);
if(frags.length >= 2) {
System.out.println("second=" + frags[1]);
if(frags.length >= 3) {
System.out.println("third=" + frags[2]);
}
}
} else {
System.out.println("nothing found");
}
It prints:
first=ddddee
second=gghnnn
third=kkkkkklllll

How to check if there are double letters in a 4 digit code in Java

The above question might seems vague but it's actually a very simple idea which i can't seem to figure out.
It basically is a 4 digit letter code containing letters from A to F for example: ABDF, BAAF, DBAF etc.
Now I'm trying to do some post input-handling where it must become impossible to enter a letter that is already in the code cause it has to be a unique 4 digit code with no repeating letter. I've been trying to make it work but none of my code seems to work so i'm back to scratch asking you guys for help :)
I hope this is somewhat clear otherwise i'll be happy to clear it up.
Thanks in advance.
Kind of a pseudocode but it would work.
String uniquePass="";
while(uniquePass.length<4){
String userInput=getUserInputChar()
if(uniquePass.contains(userInput))
rejectInputAndNotifyUser
else
uniquePass=uniquePass+userInput
}
public static boolean hasDuplicateChars(String string) {
Set<Character> chars = new HashSet<Character>();
for (char c : string.toCharArray()) {
if (!chars.add(c)) return false;
}
return true;
}
Set is a collection that contains no duplicate elements. We will use add method which returns true if this set did not already contain the specified element.
hasDuplicateChars functions iterates over characters in the input string using toCharArray function and for loop; each character is added to the chars set which is initially empty. If add method returns false it means that we have already encountered same character before. So we return false from our function.
Otherwise input is valid and method returns true.
using this function you'll be able to see if the string contains unique characters
public static boolean checkForUnique(String str){
boolean containsUnique = false;
for(char c : str.toCharArray()){
if(str.indexOf(c) == str.lastIndexOf(c)){
containsUnique = true;
} else {
containsUnique = false;
}
}
return containsUnique;
}
Update:
This will be ran everytime a user enters a character and if it fails, this would mean there is a duplicate. You have the choice of discarding that input or showing an error.
If you're validating the complete input, you can lean on the set semantics, and a few tricks
String s = "ABAF";
int count = new HashSet<>(Arrays.asList(s.split(""))).size();
if (count - 1 == 4) {
System.out.println("All ok");
} else {
System.out.println("Repeated letters");
}
the split("") will split the string to a an array like {"","A", "B", "A", "F"}.
The new HashSet<>(Arrays.asList(s.split(""))) will create a Set with String elements, and as the Set will bounce back the elements already contained, the size of the set for e.g. "AAAF" will be 3 (it'll contain the "", "A" and "F"). This way you can use the size of the set to figure out if all letters of a String are unique
If its while typing you'll than the solution depends on the input method, but you can have something like (pseudo stuff)
if (pass.contains(letter)) {
breakAndNotifyUser();
} else {
pass+=letter;
}

Java - validating a subject Code

I have a subject code e.g: ABC123 that is a string
I need to ensure that it is of length 6, the first 3 characters are letters and the last 3 are numbers.
I would like to try and do it all in an if statement? I can work the length but cannot figure out the numeric and letter part of things. e.g:
public void isValidCode(String subjectCode2){
str = subjectCode2;
if (str.length() == 6 && """"NEED TO TEST OTHERS HERE??""" ) {
System.out.println("The code is valid");
}
else {
System.out.println("The code is not valid");
}
You can always use Regular Expressions, and the matches() method of the String class.
if (str.matches("[a-zA-Z]{3}[0-9]{3}")) {
// Validation succeeded
}
else {
// Validation failed
}
To test that the first three letters are letters, you could use a loop. Similarly, use a loop for testing that the last three digits are numbers. You might find the functions in the Character class helpful.
I would change the method signature so that it is not a void method but rather declared to return a boolean. Then you could have several if statements that if false returns false. At the bottom, return true if it passes all tests.
public boolean isValidCode(String code) {
if (code.length() != 6) {
return false;
}
// here check if first 3 chars are letters
// here check if last 3 chars are numbers
return true;
}
Then the calling code can do a println if desired.
String test = "ABC123";
if (isValidCode(test)) {
System.out.println("The code is valid");
} else {
System.out.println("The code is not valid");
}
If by "letter", you mean to include letters in alphabets other than English, you'll need this.
if (str.matches("\\p{L}{3}\\d{3}")) {
Here, \p{L} matches any character that Unicode considers to be a letter, in any language.

Categories

Resources