Surrounded Character Method Java - java

I'm working on a java method that checks whether a character in an array of characters is surrounded by a character. Ex: abcdc, d is surrounded by c. Ex: abccc, has no letters that are surrounded. Here is what I have so far.
public static boolean surroundedCharacter(char[] letters){
boolean result = false;
for(char letter : letters)
if(letters[letter-1] == letters[letter+1]){
result = true;
}
return result;
} }
So I basically have a for each loop going through letter in letters and checks whether the letter before the position is equal to letter after the position. If it is, it means that the letter is surrounded and it should change result to true. The junit test says that the if statement is wrong, but I don't know how to fix it. Any help is appreciated.

You have to use an Integer for the index:
public static boolean surroundedCharacter(char[] letters){
boolean result = false;
for(int i = 1; i < letters.length - 1; i++) {
// You said that if the string is "abccc", should return false.
// So, we check if the previous or the next letter is different to
//the actual value of i
if((letters[i-1] == letters[i+1]) && (letters[i-1] != letters[i])) {
result = true;
}
}
return result;
}

Try this one:
public static boolean surroundedCharacter(char[] letters){
boolean result = false;
for( int i=1;i<letters.length-1;i++)
if(letters[i-1] == letters[i+1]){
result = true;
}
}
return result;}

You must use for loop instead of short for. Try this for loop:
for(int i = 1; i< letters.length-1; i++){
if(letters[i-1] == letters[i+1]){
result = true;
}
}

A Java foreach is designed to iterate element after element.
In case of need to get two distinct element at each iteration, you should use a classic for using a int value.
Besides, you don't need to have intermediary variable. When the condition is matched you can return true. Otherwise you return false after the loop.
At last, according to your needs :
Ex: abccc, has no letters that are surrounded.
you should accept the match only if the surrounded char differs from the chars that surround it.
public static boolean surroundedCharacter(char[] letters){
for(int i=1; i<letters.length-1; i++){
var beforeLetter = letters[i-1];
var afterLetter = letters[i+1];
if(beforeLetter == afterLetter && beforeLetter != letters[i]){
return true;
}
}
return false;
}

Related

'for' does not loop in boolean method

I have this boolean method that is supposed to compare all the characters between the "word" and "inputPlay", and update the int array to value 1 if they match as well as return true.
However, it does not loop and instead stops if it finds a match. What should I do differently?
public static boolean updateArray(String word, int[] guesses, String inputPlay) {
for (int i = 0; i < word.length(); i++) {
if (inputPlay.charAt(0) == word.charAt(i)) {
guesses[i] = 1;
}
return true;
}
return false;
}
Going off of the assumption that you should return true if any of the letters match, you'll need to use a temporary boolean that you declare outside the loop:
public static boolean updateArray(String word, int[] guesses, String inputPlay) {
boolean match = false;
for (int i = 0; i < word.length(); i++) {
if (inputPlay.charAt(0) == word.charAt(i)) {
guesses[i] = 1;
match = true;
}
}
return match;
}
Because we set match to true inside the if-statement, it will still continue iterating and return true after the for-loop terminates, assuming any of the letters match. Otherwise, it will return false.

Question >> print "True" or "False" if the string contains two or more characters

I have to make a method named 'contains' that accepts a string and a character as parameters and returns true if that character occurs two or more times in the string.
example: Input contains("Apple", 'p') should return "True"
private boolean contains(String a,char b) {
if(a.contains(b)) {
print("true");
}
else {
print("");
}
//boolean c = a.contains('l');
return false;
}
I know this code is wrong ... I want to know what I have to do and what I have to fix .
I would appreciate your advice
Thank you.
There are a few ways to do this but the simplest would just be to loop through the String looking for the char, if count reaches two then return true.
For this consider using
for (char c : input) {
if (c == myChar) count++;
if (count >= 2) return true;
}
return false;
Another way would be to use String.replace and replace the wanted char with ""
then compare the size of the before and after String
Your method may return a boolean based on the size difference between the original string, and the string without the given character :
return (a.length() - (a.replace(b, '')).length()) >= 2 ;
In theoretical terms:
First: you need to iterate over the input string characters using a for loop and then in each iteration compare the current character in the string with the other character argument which is given as method argument. If they match, then you can increase a counter (a variable). Then compare if the counter value is 2 and return true immediately it is so. At the method end you can return false just like you have done already.
Second : you are printing true , not returning true. Should use return true; when the value of variable becomes 2
countMatches(a,b) returns the count of b in String a. and it is from org.apache.commons.lang3
private boolean contains(String a,char b) {
return StringUtils.countMatches(a, b)>=2 ;
}
or in simple java you can use
private boolean contains(String a,char b) {
return (a.length() - a.replaceAll(String.valueOf(b),"").length())>=2 ;
}
This is one of simple ways to do this. Here the string is put into char array. This way it is easier to examine the elements of the char array and find out same characters.
private boolean contains(String a, char b) {
char[] c_array = a.toCharArray();
int count = 0;
for (int i = 0; i < c_array.length; i++) {
if (b == c_array[i]) {
count++;
continue;
} else {
continue;
}
}
if (count >= 2) {
return true;
} else {
return false;
}
}
public class Demo {
public static boolean contains(String str,char c){
//todo:check str for NullPointExecption
int flag=0;
for(int i=0;i<str.length();i++){
if(c==str.charAt(i)){
flag++; //if str contains char c,flag=flag+1
}
if(flag>=2){
return true; //if flag>=2,return true
}
}
return false;
}
public static void main(String[] args) {
System.out.println(contains("appple", 'p'));//result is true
}
}

program to find if two characters in String in a row are digits does not work in java

I have the code below, which I want to take input from the keyboard and show me if the input contains 2 digits in a row. If so, I want to get false printed out in the console, otherwise true. It works fine, except when the first 2 characters of the input are digits. In that case, I still get true in the console. Can anyone understand why? Thanks in advance
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System. in );
System.out.println("Enter:");
String s = sc.nextLine();
if (checkDigit(s)) {
System.out.println("false");
} else {
System.out.println("true");
}
}
public static boolean checkDigit(String s) {
boolean b = true;
char[] c = s.toCharArray();
for (int i = 0; i < c.length - 1; i++) {
if (Character.isDigit(c[i]) && Character.isDigit(c[i + 1])) {
b = true;
} else {
b = false;
}
}
return b;
}
}
You continue to check the input string even when you already found the result. As noted by #Stultuske, you overwrite the value of the variable b, so your code will only return true, if the last two chars are digits.
You would need to return from the loop if there are two digits in a row:
public static boolean checkDigit(String s) {
char[] c = s.toCharArray();
for(int i=0; i < c.length-1; i++) {
if(Character.isDigit(c[i]) && Character.isDigit(c[i+1])) {
return true;
}
}
return false;
}
UPDATE: in fact there was an error in the snippet, as it was returning too early from the loop. Fixed now.
The problem is that you overwrite the value on each loop iteration, so you only get true if the last pair of characters match. But Krypt1 already said this.
An alternative implementation using streams (because all the kids want to use Streams these days):
return IntStream.range(0, str.length()-1)
.anyMatch(i -> Character.isDigit(str.charAt(i)) && Character.isDigit(str.charAt(i+1)));
use Character.isDigit(char) method in your if condition and return true; rather than store b=true as that may get overwritten in next iteration.
you can also use regular expression. String's matches(pattern) method for this purpose.
Try using the following regex
Pattern pattern = Pattern.compile("[0-9]{2}");
Matcher matcher = pattern.matcher("your input string");

Check if the dictionary contains a certain word

I've come up with the following problem: suppose the words are being added into the dictionary that is based on some data strucure. For example, the following words are added:
"bob", "dad", "bad"
And suppose I want to check if a certain word is in the dictionary by implementing the method:
public boolean checkWord(String word)
However, the character '.' also represents some letter so if, for example:
checkWord(".ob")
then the result is true (as '.' can be substituted or represented by b and would be bob). Or another example is:
checkWord("..d")
which also return true (because of "dad").
I need help only with how to check if the words match. Suppose the data structure is ArrayList and dictionary is represented as myList. My code is giving always true for whatever String I pass. Please could smb please help me out? I just want to know how to return true if a dictionary contains "bob" and a passing check word is ".ob", then how can I omit the character '.' and check other characters? Thanks in advance!
public boolean checkWord(String word){
boolean result = false;
if(myList.contains(word)){
return true;
}
else{
for(int i = 0; i < myList.size(); i++){
if(myList.get(i).length() == word.length()){
for(int j = 0; j < word.length(); j++){
if(word.charAt(j) == myList.get(i).charAt(j)){
result = true;
}
}
}
}
}
return result;
}
If I understand correctly, you should be able to use regex.
public boolean checkWord(String word){
boolean result = false;
if(myList.contains(word)){
return true;
}
else{
word += "$";
Pattern p = Pattern.compile(word);
for(int i = 0; i < myList.size(); i++){
Matcher m = p.matcher(myList.get(i));
if(m.find()){
result = true;
break;
}else{
result = false;
}
}
}
return result;
}

check password for digits and letters

I have problem with two of my methods for password validation.
The method hasDigitsAndLetters is supposed to check whether all the characters of the String are digits and letters and the second method hasTwoDigits is supposed to check whether there are at least two digits in the pass, but the problem is that for expected result true they are ruturning false. If someone can help. here is the code.
//check if the whole string consists of digits and letters
public static boolean hasDigitsAndLetters(String pass)
{
for(int i=0; i<pass.length(); i++)
{
if(!Character.isLetterOrDigit((i)))
{
return false;
}
}
return true;
}
// check whether the password has at least 2 digits
public static boolean hasTwoDigits(String pass)
{
int counter = 0;
for(int i=0; i<pass.length(); i++)
{
if(Character.isDigit(i))
{
counter ++;
}
}
System.out.println("Number of digits: " + counter);
if(counter >= 2)
{
return true;
}
return false;
}
You need to pass character at position i for that String.
Character.isLetterOrDigit((pass.charAt(i)))
same for digit also
Character.isDigit((pass.charAt(i)))
You want to check the character in the string at index i, not the index variable itself:
Character.isLetterOrDigit(pass.charAt(i))
You aren't checking against characters in your pass, you need to change your checks to:
if(!Character.isLetterOrDigit((pass.charAt(i)))
and
if(Character.isDigit(pass.charAt(i)))
Right now you are checking if i is a digit or letter and i is an int. You need to check the character at position i.
if(Character.isDigit(pass.charAt(i)))
The error is that you're comparing the position into the string rather than the character at that position in the string. I'd probably not use charAt, however... there's no point in keeping explicit management of the position here. I suggest you use String.toCharArray instead.
public static boolean isAlphanumeric(final String str) {
for (char c : str.toCharArray()) {
if (!Character.isLetterOrDigit(c)) {
return false;
}
}
return true;
}
public static boolean isBidigital(final String str) {
int n = 0;
for (char c : str.toCharArray()) {
if (Character.isDigit(c)) {
++n;
}
}
return n >= 2;
}

Categories