I´m a bloody beginner trying to write a lil programm to check if 2 words are anagrams. So far all the whitespaces within the words get deleted but apparently there's an error with my Arrays.sort() but I can´t see it. Why and where´s the error in my Arrays.sort() line and how could I solve it?
Edit: If I leave the Arrays.sort() out like this it compiles and works so apparently there's only a problem with that line. If I leave them in it points to array and says error: can not find symbol
public static void isAnagramm(String wordOne, String wordTwo)
{
String w1= wordOne.replaceAll("\\s", "");
int word1 = w1.length();
String w2 = wordTwo.replaceAll("\\s", "");
int word2 = w2.length();
boolean anagrammStatus = false;
if(word1 == word2)
{
anagrammStatus = true;
}
else
{
char [] charArrayWordOne = w1.toLowerCase().toCharArray();
char [] charArrayWordTwo = w2.toLowerCase().toCharArray();
//Arrays.sort(charArrayWordOne);
//Arrays.sort(charArrayWordTwo);
anagrammStatus = charArrayWordOne.equals(charArrayWordTwo);
}
if(anagrammStatus == false)
{
System.out.println("Anagram");
}
else;
{
System.out.println("No Anagram");
}
}
This should do the trick:
public static void isAnagramm(String wordOne, String wordTwo)
{
String w1= wordOne.replaceAll("\\s", "");
String w2 = wordTwo.replaceAll("\\s", "");
// No need to keep the length variables
boolean anagramStatus = false;
// Check if the strings are equal to begin with, use equals and not == operator
if(w1.equals(w2))
{
anagramStatus = true;
}
else
{
char [] charArrayWordOne = w1.toLowerCase().toCharArray();
char [] charArrayWordTwo = w2.toLowerCase().toCharArray();
Arrays.sort(charArrayWordOne);
Arrays.sort(charArrayWordTwo);
// Compare arrays using the Arrays.equals method to avoid comparing the object references
anagramStatus = Arrays.equals(charArrayWordOne, charArrayWordTwo);
}
// Use simple boolean logic in your condition here, or again, always use == instead of =
if (anagramStatus)
{
System.out.println("Anagram");
}
else
{
System.out.println("No Anagram");
}
}
Related
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
}
}
I am currently trying to create a method that turn words into their plural equivalent. In doing this I have some cascaded if's that use the .endsWith() method.
I have a string array of consonants(+y) which I want to use as a parameter for the endsWith() method. But it says that I need to change type consonantandY method to String and not String[]. If I do that, I can't make an array...
How do I get around this?
private String regularPluralForm(String word) {
String s2 = "";
if(word.endsWith("s)")) {
s2 = "es";
} else if(word.endsWith("x)")) {
s2 = "es";
} else if(word.endsWith("z")) {
s2 = "es";
} else if(word.endsWith("ch")) {
s2 = "es";
} else if(word.endsWith("sh")) {
s2 = "es";
} else if(word.endsWith(consonantAndY)) {
}
String correctWord = word+s2;
return correctWord;
}
private static final String[] consonantAndY = {"by","cy","dy","fy",
"gy","hy","jy","ky"
,"ly","my","ny"
,"py","qy","ry","sy"
,"ty","vy","wy","xy"
,"yy","zy"};
}
Rather than looping over consonantAndY, calling endsWith on each element of that array, you can use a regular expression.
} else if (word.matches(".*[bcdfghjklmnpqrstvwxyz]y")) {
Iterate over the array
else {
boolean matches = false;
for(String s : constantAndY) {
if (word.endsWith(s)) {
matches = true;
break;
}
}
but better is apparently the answer above with java 8
With java 8 you can do
if( Arrays.asList(consonantAndY).stream().anyMatch(t -> word.endsWith(t)) ){
// do something
}
Demo
Could make a helper method called endsWith that takes the array as a parameter.
int consonantIndex = -1;
if (...) { ... }
else if((consonantIndex = endsWith(word, consonantAndY)) != -1) {
s2 = consonantAndY[consonantIndex];
}
private int endsWith(String s, String... suffixes) {
for (int i = 0; i < suffixes.length; i++) {
if (s.endsWith(suffixes[i])) {
return i;
}
}
return -1;
}
I am a beginner learning Java and have been asked to check if a given string is a palindrome.
Here is what I have so far:
int namel = name.length();
for (int i =0; i<=namel; i++)
{
char letter = name.charAt(i);
char namerev = name.charAt(namel-i);
String letterS =txtNamePali.getText();
if(letter==namerev)
{
txtNamePali.setText("Palindrone");
}
else
{
txtNamePali.setText( "Not a Palindrone");
}
}
Unfortunately my textbox isn't showing any output. I have searched for how to fix the issue but couldn't find an answer relating to what I have learnt in class.
What did I do wrong, and how can I correct it?
I think the easiest test is to use the StringBuilder.reverse() to construct the reverse of the input. Also, the word is usually spelled palindrome.
StringBuilder sb = new StringBuilder(name);
sb.reverse();
String msg = (sb.toString().equals(name)) ? "Palindrome" : "Not a Palindrome";
txtNamePali.setText(msg);
You can do it using a StringBuilder
Use the reverse function in that.
Example:
public static void main(String args[]){
String str = "1234";
String str1 = "1234321";
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(str);
if(stringBuilder.reverse().toString().equals(str)){
System.out.println("Palindrome");
} else {
System.out.println("Not Palindrome");
}
stringBuilder = new StringBuilder();
stringBuilder.append(str1);
if(stringBuilder.reverse().toString().equals(str1)){
System.out.println("Palindrome");
} else {
System.out.println("Not Palindrome");
}
}
Output:
Not Palindrome
Palindrome
Int short you can just do
new StringBuilder().append(yourString).reverse().toString().equals(yourString)
This return a boolean true if the string is palindrome else false.
Your code is on the right track, but as some people have said, there are a few errors you need to account for, which should appear as compiler issues.
int namel = name.length();
boolean isPalindrome = true;
//add a tracking value, it's a palindrome unless we prove it otherwise
for (int i =0; i< namel/2; i++)
//change from <= to < because arrays are 0-index, we also only have to check halfway so we can use namel/2
{
char letter = name.charAt(i);
char namerev = name.charAt(namel-i);
//String letterS =txtNamePali.getText(); <-- not sure what this was for, possibly a debug statement
if(letter!=namerev)
{
isPalindrome = false; //we have found a non-matching value, it'll stay false, and we'll output correctly
}
}
//then we set the text once. Keeping the text inside would have returned an erroneous "abbc" is a palindrome.
if(isPalindrome) {
txtNamePali.setText("Palindrone");
}
else {
txtNamePali.setText( "Not a Palindrone");
}
1.The result of the method should be given when the whole string got checked. So first put
if(letter==namerev)
{
txtNamePali.setText("Palindrone");
}
else
{
txtNamePali.setText( "Not a Palindrone");
}
outside the loop (and change the condition - like in my proposal below).
you can break the loop when the first mismatch of two chars occured.
2.Instead of char namerev = name.charAt(namel-i); you have reduce the position one more.
So use: char namerev = name.charAt(namel-1-i);
try something like this:
String s = "stringtotest";
boolean result = true;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != s.charAt(s.length()-1-i)) {
result = false;
break;
}
}
if (result)
System.out.println("Palindrom");
else
System.out.println("Not palindrom");
Same general idea as the others, but I think that this is cleaner and easier to read. Just a thought - everyone has their own style. :) If you're a beginner, I highly suggest getting into the habit of moving redundant logic to its own method. It's cleaner and may prove to be much more useful later.
public class Main {
public static void main( String args[] ) {
for ( String string : args ) {
if ( isPalendrome( string ) {
System.out.println("Palindrome");
} else {
System.out.println("Not a Palindrome");
}
}
}
private static boolean isPalindrome( String string ) {
return string.equals( reverse( string ) );
}
private static String reverse( String original ) {
return new StringBuilder(original).reverse().toString();
}
}
String name="pop"; // string to check if it palindrome or not
String revName="";
int namel = name.length();
for (int i =1; i<=namel; i++)
{
char namerev = name.charAt(namel-i);
revName += namerev;
}
if(name.equals(revName))
{
System.out.println("Palindrome");
}
else
{
System.out.println( "Not a Palindrome");
}
I've the below code.
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class Dummy {
public static void main(String args[]) throws Exception {
String word="hi";
String[] one={"a","b","c"};
String[] two={"d","e","f"};
String[] three={"g","h","i"};
String[] four={"j","k","l"};
String[] five={"m","n","o"};
String[] six={"p","q","r","s"};
String[] seven={"t","u","v"};
String[] eight={"w","x","y","z"};
for(int i=0;i<word.length();i++)
{
for(int j=0;j<three.length;j++)
{
if(three[j].equals(word.charAt(i)))
{
System.out.println("Matched");
}
else
{
System.out.println("err");
}
}
}
}
}
Here my concept is to match a letter from the string to the array created and here the output is all err(condition stating not matched). please let me know where am i going wrong.
Thanks
You're comparing a single-character string (from your arrays) to a character. Make your arrays of char, not String. (And use == to compare them.)
The element three[j] in for loop is String whereas word.charAt(i) is char.. so equals() against those will be always false.
You should either change it to
if(three[j].equals(String.valueOf(word.charAt(i))))
so that it compares string's actual context, or define arrays (one, two, three.. ) to be char array instead of string array so that you can simply use == for that.
Please check equals() for String, Object, and the others in JavaDoc, and probably you need to check hashCode() as well to fully understand what's equals() means in Java.
charAt return a char not a string so it can't be "equals" to a String
Why don't you use String.indexOf() ?
for(int j=0;j<three.length;j++)
{
if(word.indexOf(three[j]) == -1)
{
System.out.println("err");
}
else
{
System.out.println("Matched");
}
}
This way you will enter in a single loop..
Try like this:
StringBuffer result = new StringBuffer();
for (int i = 0; i < one.length; i++) {
result.append(one[i]);
}
if (result.toString().equals(word)) {
System.out.println("Matched");
} else {
System.out.println("err");
}
Just saying the obvious....sometimes it is helpful to see the actual code. Following is excerpt from java.lang.String
See bold condition in particular. it returns false if instanceof fails!
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (**anObject instanceof String**) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
Can someone please discuss and explain a way I can modify my code to function with these test cases... I am trying to make my program take a word and make it a palindrome by replacing one letter in a word that prevents the word from being a palindrome
Desired test cases:
Palindromes.isPalindrome2("cat", 'c') => true
Palindromes.isPalindrome2("axaa", 'x') => true
Palindromes.isPalindrome2("12bb", 'b') => true
Palindromes.isPalindrome2("ca", 'c') => true
This is what I have thus far...
public class Palindromes {
public static boolean isPalindrome(String word) {
//Strip out non-alphanumeric characters from string
String cleanWord = word.replaceAll("[^a-zA-Z0-9]","");
//Check for palindrome quality recursively
return checkPalindrome(cleanWord);
}
public static boolean isPalindrome2(String word) {
//Strip out non-alphanumeric characters from string
String cleanWord = word.replaceAll("[^a-zA-Z0-9]","");
//Check for palindrome quality recursively
return checkPalindrome2(cleanWord);
}
public static boolean checkPalindrome(String word) {
if(word.length() < 2) {
return true;
}
char first = word.charAt(0);
char last = word.charAt(word.length()-1);
if(first != last) {
return false;
}
else {
return checkPalindrome(word.substring(1,word.length()-1));
}
}
public void replace(int first, int last) {
if(first != last)
{ first = last;}
else if(last != first)
{ last = first;}
}
public static boolean checkPalindrome2(String word) {
char special = 0;
if(word.length() < 2) {
return true;
}
char first = word.charAt(0);
char last = word.charAt(word.length()-1);
if(first != last) {
return false;
}
if(first != last)
return false;
else {
return checkPalindrome2(word.substring(1,word.length()-1));
}
}
}
replace() was my attempt at handling the wildcard letter, but I cant seem to find the appropriate solution... All help will be greatly appreciated. thanks...
Here's my steps I would do:
Split the received string into 2 substrings. The first string front being the front half of the string, the second string back being the half end of the string.
Example:
char replacement = 'c';
String input = "aabbcc";
StringBuilder front = new StringBuilder(input.substring(0, input.length()/2));
// Do modulus to not include the odd middle (it mirrors itself)
StringBuilder back = new StringBuilder(input.substring((input.length()/2)+(input.length()%2));
Compare the two strings, replacing if one matches but the other doesn't. If neither match each other and is not the given 'replacement' character, return false. If you do more than one replacement, return false (since that is what you said the requirement is)
Example:
int replacements = 0;
for (int i=0; i < front.length(); ++i)
{
int backIndex = back.length() - i;
if (front.charAt(i) != back.charAt(backIndex))
{
// Characters do not match at all to given replacement
if ((front.charAt(i) != replacement) &&
(back.charAt(backIndex) != replacement)
{
// Cannot make it
// (Or if you want to force it, set both to replacement
// by deleting this one if statement)
return false;
}
// Front matches replacement
else if (front.charAt(i) == replacement)
{
// Replace back character with replacement
back.setCharAt(backIndex, replacement);
replacements++;
}
// Back matches replacement
else if (back.charAt(backIndex) == replacement)
{
// Replace front character with replacement
front.setCharAt(i, replacement);
replacements++;
}
if (replacements > 1)
{
// Can only replace one
return false;
}
}
}
String output = front.toString() + back.toString();
Here's my code, it splits the input into two halves, and compares the first half to the reversed second half. If they are equal, the input is already a palindrome. If they are not equal, it iterates through the first half, exchanging letters with the input char to replace with, and comparing with the reversed second half at every step. Then it does the same thing, but using the second half instead of the first half:
public class CanMakePalindrome {
public static void main(String[] args) {
System.out.println("cat using c: " + canMakePalindrome("cat", 'c'));
System.out.println("axaa using x: " + canMakePalindrome("axaa", 'x'));
System.out.println("12bb using b: " + canMakePalindrome("12bb", 'b'));
System.out.println("ca using c: " + canMakePalindrome("ca", 'c'));
}
private static boolean canMakePalindrome(String input, char c) {
int length = input.length();
String start = input.substring(0, length/2);
String end = input.substring(length/2+length%2, length); // need modulus in the case of odd length input
return (replaceLoop(start,end, c) || replaceLoop(end,start, c));
}
private static boolean replaceLoop(String start, String end, char c) {
if (start.equals(reverse(end))) {
System.out.println("Input is already a palindrome.");
return true;
}
for (int i=0; i<start.length(); i++) {
char[] startchars = start.toCharArray();
char[] endchars = end.toCharArray();
endchars = reverse(endchars);
startchars[i] = c;
if ((new String(startchars).equals(new String(endchars)))) return true;
}
return false;
}
private static char[] reverse(char[] input) {
int length = input.length;
char[] reversed = new char[length];
for (int i=0;i<length;i++) {
reversed[length-i-1]=input[i];
}
return reversed;
}
private static String reverse(String input){
String reversed = new String(reverse(input.toCharArray()));
return reversed;
}
}
Output:
cat using c: true
axaa using x: true
12bb using b: false
ca using c: true
Note that 12bb cannot be made into a palindrome using only one character change, so your test case appears to not match your specifications of replacing only one letter. Also my code will return true if given an empty string as input.