CodingBat xyzThere - java

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.
I am trying this problem out and cant seem to find why "abc.xyzxyz" is still returning false
public boolean xyzThere(String str) {
if(str.contains("xyz")) {
int xyz = str.indexOf("xyz");
if(xyz!=0 && str.substring(xyz-1,xyz).equals(".")) {
return false;
}
return true;
}
return false;
}

It returns false because this statement, if(xyz!=0 && str.substring(xyz-1,xyz).equals(".")) { is true.
xyz is 4, and str.substring(3, 4) is "."

Related

How to avoid two or more returns in Java method

I have this method which validates a string.
In my assignment I can't have more than 1 return in a method.
How can I make this method in a way to return only one value at the end after the do while loop ?
public final static String CHOIX_MENUS_VALIDES = "1234";
public static String validateMenu() {
String choice;
String choice1 = String.valueOf(CHOIX_MENUS_VALIDES.charAt(0));
String choice2 = String.valueOf(CHOIX_MENUS_VALIDES.charAt(1));
String choice3 = String.valueOf(CHOIX_MENUS_VALIDES.charAt(2));
String choice4 = String.valueOf(CHOIX_MENUS_VALIDES.charAt(3));
do {
choice = validateString(MSG_SOLL_MENU, MSG_ERR_MENU, 1, 4, true);
if (choice.trim().equals(choice1) || choice.trim().equals(choice2) || choice.trim().equals(choice3) || choice.trim().equals(choice4)) {
return choice; //Here I don't want to return the choice
}
if (!choice.equals(choice1) || !choice.equals(choice2) || !choice.equals(choice3) || !choice.equals(choice4)) {
System.out.println(MSG_ERR_MENU);
}
} while(!choice.trim().equals(choice1) || !choice.trim().equals(choice2) || !choice.trim().equals(choice3) || !choice.trim().equals(choice4));
return choice;
}
I would appreciate if someone could help me rebuild that method for returning only one value at the end.
The simples solution is to replace the first return
return choice; //Here I don't want to return the choice
by a break;
Another solution is to use a boolean variable (lets named stay)
do{
boolean stay = true;
choice = validateString(MSG_SOLL_MENU, MSG_ERR_MENU, 1, 4, true);
if (...){
stay = false;
}
else if(...) {...}
while(stay && ...);
return choice;
In every loop iteration you set the variable to true (i.e., boolean stay = true;) so that you only get out of the loop due to that variable being set to false. Because we removed the first return from the first if(..) and added now the variable we had to change the second if to an else if so that it does not get executed if the first if evaluates to true. Finally, you add the new variable as part of your while condition.

Method to check "dutch" postal code in java

I'm trying to create a method in java to validate a dutch postal code.
the dutch postal code consist 6 characters which contain 4 numbers (first 4 chars) and 2 letters (last 2 chars) so for example 1010AB.
I made a boolean to return false if the postcode is not within standard and true if it is.
I'm getting stuck with checking the last 2 letters.
I've created a loop for the first 4 numbers, but I don't know how to go further from here to check the letters aswell.
My java method:
public static boolean checkPostcode(String postCode) {
boolean value = false;
if (postCode.length() == lengthPost) {
for (int i = 0; i < postCode.length(); i++) {
if (i <= 4) {
if (Character.isDigit(postCode.charAt(i)) {
value = true;
else{
if (Character.isLetter(postCode.charAt(i))) {
value = true;
}
}
}
}
}
}
return value;
}
You van ignore the last else, because that is the point where I get stuck....
If someone can help me that would be great!!
Thanks in advance
Solution using regex:
public class Main {
public static void main(String[] args) {
// Tests
System.out.println(checkPostcode("1234AB"));
System.out.println(checkPostcode("5678MN"));
System.out.println(checkPostcode("0123AB"));
System.out.println(checkPostcode("1023AB"));
System.out.println(checkPostcode("1230AB"));
System.out.println(checkPostcode("AB1234"));
System.out.println(checkPostcode("123456"));
System.out.println(checkPostcode("ABCDEF"));
System.out.println(checkPostcode("12345A"));
System.out.println(checkPostcode("A12345"));
System.out.println(checkPostcode("A12345B"));
System.out.println(checkPostcode("1ABCDE6"));
System.out.println(checkPostcode("1ABCD6"));
}
public static boolean checkPostcode(String postCode) {
return postCode.matches("[1-9]{1}[0-9]{3}[a-zA-Z]{2}");
}
}
Output:
true
true
false
true
true
false
false
false
false
false
false
false
false
Non-regex solution:
public static boolean checkPostcode(String postCode) {
if (postCode.length() != lengthPost || postCode.charAt(0) == '0') {
return false;
}
if (postCode.length() == lengthPost) {
for (int i = 0; i < postCode.length(); i++) {
if (i < 4 && Character.isLetter(postCode.charAt(i))) {
return false;
}
if (i > 3 && Character.isDigit(postCode.charAt(i))) {
return false;
}
}
}
return true;
}
If I understand correctly, the first 4 symbols are digits, so the if condition should be
(i < 4)
because otherwise you check the first 5 symbols for a digit
While you could solve this problem with regular expressions, it is also possible to solve it along the lines you have chosen. I would write two helper methods, one to check that all characters within a given subsequence of a String are digits and another to check for letters. Like,
private static boolean allDigits(String s, int start, int end) {
for (int i = start; i < end; i++) {
if (!Character.isDigit(s.charAt(i))) {
return false;
}
}
return true;
}
private static boolean allLetters(String s, int start, int end) {
for (int i = start; i < end; i++) {
if (!Character.isLetter(s.charAt(i))) {
return false;
}
}
return true;
}
Then the checkPostcode can delegate to those two methods. Like,
public static boolean checkPostcode(String postCode) {
if (postCode != null && postCode.length() == 6) {
return allDigits(postCode, 0, 4) && allLetters(postCode, 4, 6);
}
return false;
}
And if you choose to use a regular expression compile it with a Pattern for better performance. Like,
private static Pattern POSTCODEPATTERN = Pattern.compile("\\d{4}[A-Za-z]{2}");
public static boolean checkPostcode(String postCode) {
return postCode != null && POSTCODEPATTERN.matcher(postCode).matches();
}

Recursion to check if a String equals another string

my current code returns the output:
true
Expected: true
false
Expected: true
false
Expected: true
false
Expected: false
false
Expected: false
So there's an issue with my logic that i'm not seeing
public static void main(String[] args)
{
System.out.println(find("",""));
System.out.println("Expected: true\n");
System.out.println(find("Mitten","Mit"));
System.out.println("Expected: true\n");
System.out.println(find("I love my CS courses!"," CS"));
System.out.println("Expected: true\n");
System.out.println(find("","Cookies."));
System.out.println("Expected: false\n");
System.out.println(find("Java","Python"));
System.out.println("Expected: false\n");
}
public static boolean find(String text, String str)
{
boolean found = false;
if(text.length() == 0 && str.length() == 0)
{
found = true;
return found;
}
if(text.length() == 0 || str.length() == 0)
{
return found;
}
if(str.length() > text.length())
{
return found;
}
if(str.equals(text.substring(0,str.length()-1)))
{
found = true;
}
else
{
text = text.substring(1);
find(text, str);
}
return found;
}
please help
I see an issue with this statement
if(str.equals(text.substring(0,str.length()-1)))
Since the second index of substring is exclusive, it should be
if(str.equals(text.substring(0,str.length())))
in order to compare str to the first str.length characters of text.
Of course you can use text.contains(str) or text.startsWith(str) and eliminate some of your code, but perhaps that's not part of the exercise requirements.
Beside that issue, when you make a recursive call, you should usually do something with the value returned by that call :
found = find(text, str);
otherwise, why make the recursive call in the first place? (unless it has side effects of mutating the objects passed as parameters to the recursive call, which it does not in your case)

How to use contains and equalsIgnoreCase in string

Is there a way to check if a string contains something while not being case sensitive?
For example: (this code is invalid it's just for you to get a basic understanding of my question)
String text = "I love ponies";
if(text.contains().equalsIgnoreCase("love") {
// do something
}
EDIT:
-------- Still not working
ooh, turns out it's not working. Here's what I'm using.
(it's a curse filter for a game)
public void onChat(PlayerChatEvent event) {
Player player = event.getPlayer();
if (event.getMessage().contains("douche".toLowerCase()) || /* More words ... */) {
event.setCancelled(true);
player.sendMessage(ChatColor.GOLD + "[Midnight Blue] " + ChatColor.RED + "Please Don't Swear.");
}
}
It works with lowercase but not uppercase.
return text.toLowerCase().contains(s2.toLowerCase());
Or another way would be
Pattern.compile(Pattern.quote(s2), Pattern.CASE_INSENSITIVE).matcher(text).find();
It would be easier if you use StringUtils#containsIgnoreCase from Apache Commons library
If you can't add a third party library, you can still use the code because is free to use. Check the online source code.
Test:
public class QuestionABCD {
public static boolean containsIgnoreCase(String str, String searchStr) {
if (str == null || searchStr == null) {
return false;
}
int len = searchStr.length();
int max = str.length() - len;
for (int i = 0; i <= max; i++) {
if (str.regionMatches(true, i, searchStr, 0, len)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
System.out.println(containsIgnoreCase("abc", "A"));
System.out.println(containsIgnoreCase("abc", "a"));
System.out.println(containsIgnoreCase("abc", "B"));
System.out.println(containsIgnoreCase("abc", "b"));
System.out.println(containsIgnoreCase("abc", "z"));
System.out.println(containsIgnoreCase("abc", "Z"));
}
}
Output:
true
true
true
true
false
false
If case sensitivity is your only issue convert everything into lowercase
String text = "I love ponies";
String test = "LOVE";
if(text.toLowerCase().contains(test.toLowerCase()))
{
//your code
}
update:
for your code use :
event.getMessage().toLowerCase().contains("douche".toLowerCase())
in all the conditions
You can check twice like this
text.contains(s);
text.contains(s.toLowerCase());

Return false; statement doesn't "return"

My return false statement doesn't work as expected. I have a recursive method called "prosegui", it works with most of the words i want to work with, but with a few of them the return false doesn't return the value "false" as it should but continue and end up returning true.
if (contChar < this.parola.length() - 1) {
if (this.parola.charAt(contChar+1)==matrice[i][j])
{
prosegui(proseguiI,proseguiJ,i,j,contChar+1);
}
else
{
System.out.println("FALSE");
return false;
}
}
System.out.println("TRUE");
return true;
I really don't know how to sort it out.
EDIT:
the program print both "FALSE" and then "TRUE"
EDIT:
public boolean prosegui(int i, int j, int proseguiI, int proseguiJ, int contChar)
{
if (contChar < this.parola.length() - 1)
{
int direzioneI=proseguiI-i;
int direzioneJ=proseguiJ-j;
i=proseguiI+direzioneI;
j=proseguiJ+direzioneJ;
int cont;
StringTokenizer st = new StringTokenizer(this.results);
cont=0;
char[][] matrice = new char[this.lung][this.lung];
while (st.hasMoreTokens())
{
matrice[cont]=st.nextElement().toString().toCharArray();
cont++;
}
if(this.parola.charAt(contChar+1)==matrice[i][j]){
prosegui(proseguiI,proseguiJ,i,j,contChar+1);
}
else
{
System.out.println("FALSE");
return false;
}
}
System.out.println("TRUE");
return true;
}
your function cannot return false when entering prosegui(...) recursivly, because you don't check the result of your recursive call, it will always return true.
First time through, this.parola.charAt(contChar+1)==matrice[i][j] is true. This means that prosegui is called again with a different input (prosegui(proseguiI,proseguiJ,i,j,contChar+1)).
This time through this.parola.charAt(contChar+1)==matrice[i][j] is false. This means that "FALSE" will be printed, and false will be returned.
Now we are back at the call to prosegui(proseguiI,proseguiJ,i,j,contChar+1). If we step forward from here, "TRUE" is printed and true is returned.
That's my theory anyway! Hope that helps.
If this code is in the prosegui method, then when it calls itself here:
prosegui(proseguiI,proseguiJ,i,j,contChar+1);
The true/false returned by this call is never used.

Categories