So I have the following String: dog "and" cat
I split it up into an array named: array1 with,
{'d','o','g',' ','"','c','a',t','"'}
boolean works = false;
for (int i=0; i < array1.length;i++){
if (array1[i].equals("d"){
if (array1[i+1].equals("o"){
if(array1[i+2].equals("g"){
if (array1[i+3].equals(" "){
if (array1[i+4].equals("""){ //does work here
if (array1[i+5].equals("c"){
if (array1[i+6].equals("a"){
if (array1[i+7].equals("t"){
works = true;
}
}
}
}
}
}
}
}
}
System.out.println(works);
It doesnt work at the equals with quotations. Does anyone have any ideas?
I would try to simplify your code, for example you could write
String s = "dog \"and\" cat";
boolean works = s.contains("dog \"cat");
This makes it much more obvious that works will always be false.
You have ambiguous data types.
I assume that your array1 is of type char[]. If it is, then you should have == comparators in your code (note the single quotes 'x' where x is the char you are testing):
if (array1[i] == 'd'){
....
}
if the arrays are of type String[], then you need to escape the " character using a backslash in the comparison:
if (array1[i+4].equals("\""){ //does work here
....
}
{'d','o','g',' ','"','c','a',t','"'} this is a char array
you need below code
You can no equal Char with String.
boolean works = false;
for (int i=0; i < array1.length;i++){
if (array1[i]=='d'){
if (array1[i+1]=='o'){
if(array1[i+2]=='g'){
if (array1[i+3]==' '){
if (array1[i+4]=='"'){ //does work here
if (array1[i+5]=='c'){
if (array1[i+6]=='a'){
if (array1[i+7]=='t'){
works = true;`
}
}
}
}
}
}
}
}
boolean works = false;
String[] pattern = { "d","o","g"," ","\"","c","a","t","\"" };
for (int i = 0; i < array1.length; i++) {
// Loop over the items in the pattern array, and check if they match array1
boolean inner = true;
for (int j = 0; j < pattern.length; j++) {
if (i + j >= array1.length) {
// Don't go beyond the end of array1
break;
}
if (!pattern[j].equals(array1[i+j])) {
// We found an item that doesn't match.
inner = false;
break;
}
}
if (inner) {
// All items matched
works = true;
break;
}
}
System.out.println(works);
You need to escape the " character inside the "". Like this:
(array1[i+4].equals("\"")
Related
I have a char array of a length n, which I don't know the value. I need to write a condition to check if all elements of my array are one by one equal to a given char 'a'.
For example, with n = 4, I convert the array to a string by doing :
String str = new String(myArray);
and then I do my condition like :
if (str.equals("aaaa")) {}
but my problem is that the value of n is unknown.
I tried to do :
for (int i = 0; i < n; i++) {
if (myArray[i].equals('a')) {
??
}
}
But i don't know to do in '??' after the if, as I need to wait the for loop to be finished, because i want that all the elements of my array to be equal to 'a'.
A process of checking all items usually goes as follows:
Check an individual item
If it matches the condition, continue
Otherwise, declare the match unsuccessful, and end the loop
If the loop ends without declaring the match unsuccessful, you have a successful match
In terms of Java, declaring the match unsuccessful could mean setting a boolean variable to false:
boolean successfulMatch = true;
for (int i = 0; i < myArray.length ; i++) {
// ^^^^^^^^^^^^^^
// Note how we check array length
if (myArray[i] != 'a') {
// ^^
// Note != here
successfulMatch = false;
break;
}
}
if (successfulMatch) {
...
}
In Java-8 you can do it using Stream#allMatch. It will reduce ceremonial code. You don't need to worry about the Array Length and setting the flag and breaking the loop.
String[] strs = {"a","a","a"};
boolean isAllEqual = Arrays.stream(strs).allMatch(e->e.equals("a"));
System.out.println(isAllEqual);
You can simply use regular expression. For example:
String s = "aaaaaaaa";
if(s.matches("[a]*"))
System.out.println("s only contains a");
else if(s.matches("[A]*"))
System.out.println("s only contains A");
else if(s.matches("[aA]*"))
System.out.println("s only contains A and a");
else
System.out.println("s not match a*");
try this
private static void n(){
char[] n = {'a', 'b'};
String[] myArray = {"a", "a", "a"};
for(char c : n){
int i = 0;
int j = 0;
for(String s : myArray){
if((s.equals(String.valueOf(c)))){
i++;
}
if(++j == n.length){
System.out.println(i + "->" + n.length);
if(n.length == i){
System.out.println("All the elemntes in your array are the same to char array");
}else{
System.out.println("Not the same");
}
}
}
}
}
What about:
boolean matched = true;
for(int i = 0, n=myArray.length; i<n; i++){
if(!myArray[i].equals("a")){
matched = false;
}
}
Then all you have to do is check matched boolean.
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;
}
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;
}
I am having difficulties with my method returning true. It is a boolean method that takes two words and tries to see if one can be turned into the other by transposing two neighboring letters. I have had no troubles getting the false boolean. When the code gets to the for loop with an if statement in it it runs fine but does not return true when the if statement is satisfied. For some reason it continues through the for loop. For example, when comparing "teh" and "the" when the loop hits 1 the if statement is satisfied but does not return true, the for lo
public static boolean transposable(String word1, String word2)
{
ArrayList<Character> word1char = new ArrayList<Character>();
ArrayList<Character> word2char = new ArrayList<Character>();
int word1length = word1.length();
int word2length = word2.length();
int count = 0;
String w1 = word1.toUpperCase();
String w2 = word2.toUpperCase();
if(word1length != word2length)
{
return false;
}
for(int i = 0; i < word1length; i++)
{
char letter1 = w1.charAt(i);
word1char.add(letter1);
char letter2 = w2.charAt(i);
word2char.add(letter2);
}
for(int i = 0; i < word1length; i++)
{
char w1c = word1char.get(i);
char w2c = word2char.get(i);
if(w1c == w2c)
{
count++;
}
}
if(count < word1length - 2)
{
return false;
}
for(int i = 0; i < word1length; i++)
{
char w1c = word1char.get(i);
char w2c = word2char.get(i+1);
if(w1c == w2c)
{
return true;
}
}
return false;
}
op just keeps running. What am I doing wrong?
As pointed out in the comments this doesn't seem to be the easiest way around this problem. Here is a solution which tries to follow your logic and includes the use of toUpperCase() and ArrayLists.
Going over your code it looks like you were getting a bit lost in your logic. This is because you had one method trying to do everything. Break things down into smaller methods and you also will benefit by not having to repeat code and it keeps things much cleaner. The code below is tested with Java8 (although there is no reason why this should not work with Java 7).
public static void main(String args[]) {
String word1 = "Hello";
String word2 = "Hlelo";
transposable(word1, word2);
}
private static boolean transposable(String word1, String word2) {
// Get an ArrayList of characters for both words.
ArrayList<Character> word1CharacterList = listOfCharacters(word1);
ArrayList<Character> word2CharacterList = listOfCharacters(word2);
boolean areWordsEqual;
// Check that the size of the CharacterLists is the same
if (word1CharacterList.size() != word2CharacterList.size()) {
return false;
}
// check to see if words are equal to start with
areWordsEqual = checkIfTwoWordsAreTheSame(word1CharacterList, word2CharacterList);
System.out.print("\n" + "Words are equal to be begin with = " + areWordsEqual);
if (!areWordsEqual) {
/*
This loop i must start at 1 because you can't shift an ArrayList index of 0 to the left!
Loops through all the possible combinations and checks if there is a match.
*/
for (int i = 1; i < word1CharacterList.size(); i++) {
ArrayList<Character> adjustedArrayList = shiftNeighbouringCharacter(word2CharacterList, i);
areWordsEqual = checkIfTwoWordsAreTheSame(word1CharacterList, adjustedArrayList);
System.out.print("\n" + "Loop count " + i + " words are equal " + areWordsEqual + word1CharacterList + adjustedArrayList.toString());
if (areWordsEqual) {
break;
}
}
}
return areWordsEqual;
}
// takes in a String as a parameter and returns an ArrayList of Characters in the order of the String parameter.
private static ArrayList<Character> listOfCharacters(String word) {
ArrayList<Character> wordCharacters = new ArrayList<Character>();
String tempWord = word.toUpperCase();
for (int wordLength = 0; wordLength < tempWord.length(); wordLength++) {
Character currentCharacter = tempWord.charAt(wordLength);
wordCharacters.add(currentCharacter);
}
return wordCharacters;
}
// takes in two character arrayLists, and compares each index character.
private static boolean checkIfTwoWordsAreTheSame(ArrayList<Character> characterList1, ArrayList<Character> characterList2) {
// compare list1 against list two
for (int i = 0; i < characterList1.size(); i++) {
Character currentCharacterList1 = characterList1.get(i);
Character currentCharacterList2 = characterList2.get(i);
if (!currentCharacterList1.equals(currentCharacterList2)) {
return false;
}
}
return true;
}
// this method takes in an ArrayList of characters and the initial index that we want to shift one place to the left.
private static ArrayList<Character> shiftNeighbouringCharacter(ArrayList<Character> characterListToShift, int indexToShiftLeft) {
ArrayList<Character> tempCharacterList = new ArrayList<Character>();
int indexAtLeft = indexToShiftLeft - 1;
// fill the new arrayList full of nulls. We will have to remove these nulls later before we can add proper values in their place.
for (int i = 0; i < characterListToShift.size(); i++) {
tempCharacterList.add(null);
}
//get the current index of indexToShift
Character characterOfIndexToShift = characterListToShift.get(indexToShiftLeft);
Character currentCharacterInThePositionToShiftTo = characterListToShift.get(indexAtLeft);
tempCharacterList.remove(indexAtLeft);
tempCharacterList.add(indexAtLeft, characterOfIndexToShift);
tempCharacterList.remove(indexToShiftLeft);
tempCharacterList.add(indexToShiftLeft, currentCharacterInThePositionToShiftTo);
for (int i = 0; i < characterListToShift.size(); i++) {
if (tempCharacterList.get(i) == null) {
Character character = characterListToShift.get(i);
tempCharacterList.remove(i);
tempCharacterList.add(i, character);
}
}
return tempCharacterList;
}
Hope this helps. If you are still struggling then follow along in your debugger. :)
public static boolean isValidNumber(String a1)
{
String x = ("0123456789");
boolean valid = false;
for (int i = 0; i < 4; i++) {
char c = a1.charAt(i);
for (int j = 0; j < 10; j++) {
if ( c == x.charAt(j)) {
valid = true;
}
else {
valid = false;
}
}
}
return valid;
}
The above method checks to see whether an input of a four character string is composed of the characters 0123456789. However, regardless of what the input is, the method always returns as false.
If I were to change the valid value in the else statement to true, the method would always return as true.
What is the error that I have made in this method?
As soon as you find a non matching character, break the loop otherwise the next matching character will set valid to true.
e.g. "123a456" is considered valid.
for (int j = 0; j < 10; j++) {
if ( c == x.charAt(j)) {
valid = true;
}
else {
valid = false;
break;
}
}
If for some reason you don't want to break the loop, you could keep an "invalid counter" and make sure that is 0 at the end.
Of course for what you are doing here, Integer.parseInt() might be your best bet ;-)
a String.equals method will check these two strings in a single statement if you are permitted to use that.
public static boolean isValidNumber(String a1)
{
String x = ("0123456789");
return x.equals(a1);
}
I would rewrite your function as given below,
String x = ("0123456789");
boolean valid = false;
for (int i = 0; i < 4; i++) {
char c = a1.charAt(i);
boolean isCharOK = false;
for (int j = 0; j < 10; j++) {
if ( c == x.charAt(j)) {
isCharOK = true;
break;
}
}
if (!isCharOK) {
valid = false;
break;
}
}
return valid;
John3136 is quite correct, but I would like to propose even better solution to your whole task:
final static String x = "0123456789";
public static boolean isValidNumber(String a1) {
for (int i = 0; i < a1.length(); ++i) {
if (x.indexOf(a1.charAt(i)) == -1) return false;
}
return true;
}
In short: the above code "looks up" every character in your parameter string a1 in the string composed of digits. If it can find it, continues. If it can't, it means a1 consist not only digits and returns false. If it passes through all a1 characters then it returns true :)
And as asked and described in the comments - handling of duplicate characters in argument string:
final static String x = "0123456789";
public static boolean isValidNumber(String a1) {
for (int i = 0; i < a1.length(); ++i) {
final char currentChar = a1.charAt(i);
if (x.indexOf(currentChar) == -1 || a1.indexOf(currentChar, i+1) != -1)
return false;
}
return true;
}
The function call a1.indexOf(currentChar, i+1) essentially checks if there is any duplicate character in the rest of the string (from position i+1 and farther). Which means if it will be able to find duplicate char, the method return false :) Hope this helps, here is more info on String.indexOf(int, int) function if you want:
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(int, int)
You can use this one liner function to check for validity of a String as Number using Regular Expression
public static boolean isValidNumber(String a1)
{
return a1.matches("[\\d]+");
}
Hope this helps.