I am wondering what return str.substring(1,4).equals("bad"); is doing here in the else if(len>=4). I think the if statement is a guard clause but I am not 100%. Can I have an explanation of what exactly is going on here? How is this read to output "false"?
Given a string, return true if "bad" appears starting at index 0 or 1 in the string, such as with "badxxx" or "xbadxx" but not "xxbadxx". The string may be any length, including 0. Note: use .equals() to compare 2 strings.
hasBad("badxx") → true
hasBad("xbadxx") → true
hasBad("xxbadxx") → false
public boolean hasBad(String str)
{
int len = str.length();
if(len == 3 && str.equals("bad"))
return true;
else if(len >= 4)
{
if(str.substring(0, 3).equals("bad"))
return true;
return str.substring(1, 4).equals("bad");
}
else
return false;
}
if(str.substring(0, 3).equals("bad")) is the easy part. "Return true if 'bad' is the beginning of the String.'
return str.substring(1, 4).equals("bad") essentially means, "Return true if 'bad' occurs after the first character, and false otherwise". This is basically a shortcut of
if(str.substring(1, 4).equals("bad")) return true;
else return false;
Because the if already evaluates a boolean (what goes inside of an if results in a boolean value), there's no reason to tell it to return "true if true, else false", you can just return the boolean value directly.
you can try it in other way too, like below one
public static boolean hasBad(String str) {
for (int i = 0; i < str.length() - 1; i++) {
if (str.length()>=3 && str.charAt(0) == 'b' || str.charAt(1) == 'b' ) {
if (str.substring(i).contains("bad")) {
return true;
}
}
}
return false;
}
Related
How check if a String contains only one specific character?
Eg:
On the String square/retrofit and square/retrofit/issues I need to check if the String has more than one / character.
square/retrofit/issues need to be false because have more than one / character and square/retrofit need to be true.
The string can have numbers.
You do not need regex. Simple indexOf and lastIndexOf methods should be enough.
boolean onlyOne = s.indexOf('/') == s.lastIndexOf('/');
EDIT 1
Of course, if / does not appear in given string above will be true. So, to avoid this situation you can also check what is returned index from one of these methods.
EDIT 2
Working solution:
class Strings {
public static boolean availableOnlyOnce(String source, char c) {
if (source == null || source.isEmpty()) {
return false;
}
int indexOf = source.indexOf(c);
return (indexOf == source.lastIndexOf(c)) && indexOf != -1;
}
}
Test cases:
System.out.println(Strings.availableOnlyOnce("path", '/'));
System.out.println(Strings.availableOnlyOnce("path/path1", '/'));
System.out.println(Strings.availableOnlyOnce("path/path1/path2", '/'));
Prints:
false
true
false
Or if you'd like to use a bit more modern approach with streams:
boolean occursOnlyOnce(String stringToCheck, char charToMatch) {
return stringToCheck.chars().filter(ch -> ch == charToMatch).count() == 1;
}
Disclaimer: This is not supposed to be the most optimal approach.
A bit more optimized approach:
boolean occursOnlyOnce(String stringToCheck, char charToMatch) {
boolean isFound = false;
for (char ch : stringToCheck.toCharArray()) {
if (ch == charToMatch) {
if (!isFound) {
isFound = true;
} else {
return false; // More than once, return immediately
}
}
}
return isFound; // Not found
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
Given a string personName, I'm trying to create a boolean condition2 equal to the condition
the first or last letter in personName is 'A' (case-insensitive). e.g., 'aha' or 'A'
Here's what I've tried so far:
boolean condition2;
if (personName.charAt(0) = "a" || personName.charAt(personName.length()-1) = "a") {
condition2 = true;
} else {
condition2 = false;
}
char type in Java is a character so wouldn't you be looking for something like this?
boolean condition2;
if((personName.charAt(0) == 'a' || personName.charAt(0) == 'A') &&
(personName.charAt(personName.length()-1) == 'a' || personName.charAt(personName.length()-1) == 'A'))
{
condition2 = true;
}
else{
condition2 = false;
}
For your first question where first and last character of a String should be 'a'
boolean condition1 = false;
if(personName.charAt(0) == 'a' && personName.charAt(personName.length()-1) == 'a') {
condition1 = true;
}
For your second condition where variable should be true only if age is in the range [18,24]
boolean condition2 = false;
if(personAge >=18 && personAge <=24) {
condition2 = true;
}
You can do it this way except comparison operator is == and you compare characters, not String.
So right way would be:
Character.toLowerCase(personName.charAt(0)) == 'a'
See, double equals and single quote.
use single quote for data type char. and convert it to lower case, so that it allow whether it's upper case or lower case.
Also use == when comparing if it's equal. this = sign, is for assigning value
if(Character.toLowerCase(personName.charAt(0)) == 'a' ||
Character.toLowerCase(personName.charAt(personName.length()-1)) == 'a')
it will look like this
boolean condition2;
if(Character.toLowerCase(personName.charAt(0)) == 'a' || Character.toLowerCase(personName.charAt(personName.length()-1)) == 'a')
{
condition2 = true;
}
else{
condition2 = false;
}
Your problem can be solve in this manner;
public static void main(String[] args) {
String s = "bsdadasd";
boolean condition2;
System.out.println(check(s.toLowerCase().charAt(0),s.toLowerCase().charAt(s.length()-1)));
}
public static boolean check(char a,char b){
return (a == 'a' || b == 'a');
}
You can pass the two characters as parameters for a method where it return true or falsedepending on the condition.
Since both characters are irrelevant of its case first made them to lowercase. toLowerCase() then passed the char at 0 and char at last.
The return statement will return the true or false to you.
And also use == to check if similar = means assigning.
It is circuitous to write
boolean b;
if (some boolean expression)
b = true;
else
b = false;
Much simpler to write
boolean b = some boolean expression;
For reasons I don't understand, there is a widespread reluctance to write a boolean expression (as distinct from the simple literal values true/false) outside an 'if' statement.
And don't get me started on if (b == true)
I am writing a function to fulfill these requirements:
Given a string, return true if it is a nesting of zero or more pairs of parenthesis, like (()) or ((())). Suggestion: check the first and last chars, and then recur on what's inside them.
nestParen("(())") → true
nestParen("((()))") → true
nestParen("(((x))") → false
The correct solution shown on the site is:
public boolean nestParen(String str) {
if (str.equals("")) return true;
if (str.charAt(0) == '(' && str.charAt(str.length()-1) == ')')
return nestParen(str.substring(1,str.length()-1));
else
return false;
}
I don't understand why this works. If the given string has a character other than ( like a ", won't it hit the else case and return false rather than skipping to the next (?
This will definitely not work if the input string contain some thing other than ( and ) to make this work just call another function like below before calling this function:
clean(String str){
String str = "(((X+y)+z))";
String retStr = "";
for(int i = 0 ; i<str.length() ; i++){
if(str.charAt(i) == '(' || str.charAt(i) == ')')
{
retStr += str.charAt(i);
}
}
return retStr
}
and then call your recursive function with input of retStr.
As seems typical with much example code, the suggested correct solution is inadiquate.
Here is an actually correct solution:
public boolean nestParen(final String value)
{
if (value != null)
{
if (value.isEmpty())
{
return true;
}
if (value.charAt(0) == '(' && value.charAt(value.length()-1) == ')')
{
return nestParen(value.substring(1, value.length()-1));
}
else
{
return false;
}
}
else // value is null
{
return true;
}
}
Explanation: (same as with the other answer)
if the parameter is not null, continue. This prevents NullPointerExceptions.
if the parameter is empty, return true. The problem appears to be return true if a string contains zero or more nested pairs of parens and nothing else.
If the first char is '(' and the last char is ')', strip these chars and check again (this is the recursion).
otherwise (first is not '(' and/or last is not ')') return false.
lastly, if the parameter was null, return true (it contains zero pairs and nothing else).
Compare three boolean values and display the first one that is true.
Hey guys, I am trying to write a program that compares three boolean values and displays the first true one. I am comparing three words for their length, and it will display the longest. The error that I am getting is that my else tags aren't working. Take a look at the code.
//Check which word is bigger
if (len1 > len2)
word1bt2 = true;
if (len2 > len3)
word2bt3 = true;
if (len1 > len3)
word1bt3 = true;
//Check which word is the longest
if (word1bt2 == true && word1bt3 == true);
System.out.println(wor1);
else if (word2bt3 == true);
System.out.println(wor2);
else System.out.println(wor3);
I have set boolean values for word1bt2, word2bt3 and word1bt3. In eclipse, I am getting a syntax error under the elses in my code above. Any help would be great!
if (word1bt2 == true && word1bt3 == true);
Is wrong, you need to remove the semicolon:
if (word1bt2 == true && word1bt3 == true)
Same for the elses
else (word2bt3 == true);
Is wrong too, it should be
else if (word2bt3 == true)
Side note: boolean values can be used as condition, so your if statements should be
if (word1bt2 && word1bt3) // The same as if (word1bt2 == true && word1bt3 == true)
How to compare three boolean values?
Dont!
If you find yourself needing to compare three variable you may as well cater for any number of variables immediately - there's no point hanging around - do it properly straight away.
public String longest(Iterator<String> i) {
// Walk the iterator.
String longest = i.hasNext() ? i.next() : null;
while (i.hasNext()) {
String next = i.next();
if (next.length() > longest.length()) {
longest = next;
}
}
return longest;
}
public String longest(Iterable<String> i) {
// Walk the iterator.
return longest(i.iterator());
}
public String longest(String... ss) {
// An array is iterable.
return longest(ss);
}
Remove the ; and change it with brackets {}.
if (word1bt2 && word1bt3) {
System.out.println(wor1);
} else if (word2bt3) {
System.out.println(wor2);
} else {
System.out.println(wor3);
}
Issue with the else blocks: use {} insteaad of () to enclose instructions...
Remove the ; at the first if!!!!! - Quite common mistake, with very puzzling results!
//Check which word is the longest
if (word1bt2 == true && word1bt3 == true) { //leave ; and always add bracket!
System.out.println(wor1);
}
else if(word2bt3 == true)
{
System.out.println(wor2);
}
else {
System.out.println(wor3);
}
if you need a condition in an else branch, you have to use if again - plain else won't have such a feature...
ALWAYS use brackets for bodies of if statements, loops, etc!!!
Be extremely careful NOT to use ; in the lines that don't behave well with it:
if statements
for loops
while() {...} loops' while statement
try this, if lenght are equal then s1 is considered as Bigger. Also i have not added null check
public class Test {
public static void main(String[] args) {
String word1 = "hi";
String word2 = "Hello";
String word3 = "Hell";
String Bigger = null;
if(word1.length() >= word2.length() && word1.length() >= word3.length() ){
Bigger = word1;
}else if(word2.length() >= word1.length() && word2.length() >= word3.length()){
Bigger = word2;
}else if(word3.length() >= word2.length() && word3.length() >= word1.length()){
Bigger = word3;
}
System.out.println(Bigger);
}
}
I'm trying to solve this CodingBat problem:
Return true if the given string contains an appearance of "xyz" where the xyz is not directly preceeded by a period (.). So "xxyz" counts but "x.xyz" does not.
xyzThere("abcxyz") → true
xyzThere("abc.xyz") → false
xyzThere("xyz.abc") → true
My attempt:
public boolean xyzThere(String str) {
boolean res = false;
if(str.contains(".xyz") == false && str.contains("xyz")){
res = true;
}
return res;
}
The problem is that is passes all the tests except the one below because it contains two instances of xyz:
xyzThere("abc.xyzxyz")
How can I make it pass all tests?
public static boolean xyzThere(String str) {
int i = -1;
while ((i = str.indexOf("xyz", i + 1 )) != -1) {
if (i == 0 || (str.charAt(i-1) != '.')) {
return true;
}
}
return false;
}
Alternatively, you could replace all occurrences of ".xyz" in the string with "", then use the .contains method to verify that the modified string still contains "xyz". Like so:
return str.replace(".xyz", "").contains("xyz");
public boolean xyzThere(String str) {
return(!str.contains(".xyz") && str.contains("xyz"));
}
Edit: Given that ".xyzxyz" should return true, the solution should be:
public boolean xyzThere(String str) {
int index = str.indexOf(".xyz");
if(index >= 0) {
return xyzThere(str.substring(0, index)) || xyzThere(str.substring(index + 4));
} else return (str.contains("xyz"));
}
The below code worked fine for me:
if '.xyz' in str:
return xyz_there(str.replace('.xyz',''))
elif 'xyz' in str:
return True
return False
Ok, I know everyone is eager to share their expertise but straight giving the kid the answer does little good.
#EnTHuSiAsTx94
I was able to pass all of the tests with three statements. Here is a hint: Try using the string replace method. Here is the method signature:
String replace(CharSequence target, CharSequence replacement)
On a minor note, the first condition in your if statement can be simplified from:
str.contains(".xyz") == false
to:
!str.contains(".xyz")
The contains method already returns true or false, so there is no need for the explicit equals comparison.
public boolean xyzThere(String str) {
return str.startsWith("xyz") || str.matches(".*[^.]xyz.*");
}
You can use the equivalent java code for the following solution:
def xyz_there(str):
pres = str.count('xyz')
abs = str.count('.xyz')
if pres>abs:
return True
else:
return False
Ok, let's translate your question into a regexp:
^ From the start of the string
(|.*[^\.]) followed by either nothing or any amount of any chars and and any char except .
xyz and then xyz
Java code:
public static boolean xyzThere(String str) {
return str.matches("^(|.*[^\\.])xyz");
}
boolean flag = false;
if(str.length()<=3){
flag = str.contains("xyz");
}
for (int i = 0; i < str.length()-3; i++) {
if (!str.substring(i, i+3).equals("xyz") &&
str.substring(i, i+4).equals(".xyz")) {
flag=false;
}else{
if(str.contains("xyz")) flag=true;
}
}
return flag;
public boolean xyzThere(String str) {
boolean res=false;
if(str.length()<3)res=false;
if(str.length()==3){
if(str.equals("xyz"))res=true;
else res=false;
}
if(str.length()>3){
for(int i=0;i<str.length()-2;i++){
if(str.charAt(i)=='x' && str.charAt(i+1)=='y' && str.charAt(i+2)=='z'){
if(i==0 || str.charAt(i-1)!='.')res=true;
}
}
}
return res;
}
public class XyzThereDemo {
public static void main(String[] args) {
System.out.println(xyzThere("abcxyz"));
System.out.println(xyzThere("abc.xyz"));
System.out.println(xyzThere("xyz.abc"));
}
public static boolean xyzThere(String str) {
int xyz = 0;
for (int i = 0; i < str.length() - 2; i++) {
if (str.charAt(i) == '.') {
i++;
continue;
}
String sub = str.substring(i, i + 3);
if (sub.equals("xyz")) {
xyz++;
}
}
return xyz != 0;
}
}
Another method
public boolean xyzThere(String str) {
if(str.startsWith("xyz")) return true;
for(int i=0;i<str.length()-3;i++) {
if(str.substring(i+1,i+4).equals("xyz") && str.charAt(i)!='.') return true;
}
return false;
}
public boolean xyzThere(String str) {
if (str.startsWith("xyz")){
return true;
}
for (int i = 0; i < str.length()-2; i++) {
if (str.subSequence(i, i + 3).equals("xyz") && !(str.charAt(i-1) == '.')) {
return true;
}
}
return false;
}
This is the best possible and easiest way to solve this question with very simple logic:
def xyz_there(str):
for i in range(len(str)):
if str[i-1]!= '.' and str[i:i+3]=='xyz' :
return True
return False
public boolean xyzThere(String str) {
boolean flag = false;
if (str.startsWith("xyz"))
{
return true;
}
for (int i = 0; i < str.length() - 3; i++)
{
if (str.charAt(i) != '.' && str.charAt(i + 1) == 'x'
&& str.charAt(i + 2) == 'y' && str.charAt(i + 3) == 'z')
{
flag = true;
break;
}
}
return flag;
}
def xyz_there(str1):
for i in range(len(str1)):
if str1[i-1] != '.' and str1[i:i+3] == 'xyz':
return True
else:
return False
def xyz_there(str):
if '.xxyz' in str:
return'.xxyz' in str
if '.' in str:
a=str.replace(".xyz","")
return 'xyz' in a
if '.' not in str:
return 'xyz' in str
'''python
def xyz_there(str):
dot=str.find('.') # if period is present in str if not dot==-1
if dot==-1: # if yes dot will show position of period
return 'xyz' in str
elif dot!=-1: #if period is present at position dot
if 'xyz' in str[:dot]:
return True
while str[dot+1:].find('.')!=-1: #while another period is present
if '.xyz' in str[dot+1:]==False: # .xyz will not be counted
return True
else:
dot=dot+str[dot+1:].find('.')+2 #now dot=previous dot+new dot+2
else:
return 'xyz' in str[dot+2:]
'''
def xyz_there(str):
list = [i for i in range(len(str)) if str.startswith('xyz', i)]
if list == []:
return False
else:
found = 0
for l in list:
if str[l-1:l+3] != ".xyz":
found += 1
if found >=1:
return True
else:
return False
simple solution just by replace and check the "xyz " in a thats it
def xyz_there(str):
a=str.replace('.xyz','')
return 'xyz' in a