I have the following code that takes 2 strings as inputs and returns Boolean on whether they're anagrams:
import java.util.ArrayList;
import java.util.Scanner;
public class AnagramChecker {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.print ("Enter string 1: ");
String str1 = sc.nextLine();
System.out.print ("Enter string 2: ");
String str2 = sc.nextLine();
boolean check = isAnagram (str1, str2);
System.out.println ("Anagram check for '" + str1 + "' and '" + str2 + "': " + check);
sc.close();
}
public static boolean isAnagram (String s1, String s2) {
if(s1.length() != s2.length())
return false;
s1 = s1.toLowerCase();
s2 = s2.toLowerCase();
ArrayList<String> myList = new ArrayList<String>();
for(int i = 0; i < s2.length() ; i++ ){
myList.add(String.valueOf(s2.charAt(i)));
}
for(int i = 0; i < s1.length();i++){
for(int j = 0; j < myList.size(); j++){
if(myList.get(j).equals(String.valueOf(s1.charAt(i)))){
myList.remove(j);
j = 0;
break;
}
}
}
return myList.isEmpty();
}
}
It is somewhat limited though, I'm trying to expand it to work for the following cases:
- different cases i.e. eager == AGREE
- single word with whitespaces i.e. eager == a g ree
- different amounts of whitespace i.e. " eager" == agree
Is there a nice and clean way to integrate this into already written code above without much pain and re-writing. Any help much appreciated. Thanks.
Yes there is. Regex to the rescue! You can use the String built in .replaceAll(). Passing it the \s value will remove all spaces and characters not printed such as \n. I would suggest that during comparison you use something like the following:
string1.replaceAll("\\s","").equals(string2.replaceAll("\\s",""));
personally I would do the following
use trim() to remove leading and traiing whitespace
use replace to remove whitespaces
use toLowerCase() to make the text lower case
convert the Strings into an array list of characters
sort the arrays
compare the arrays - if they are the same then you have an anagram
Related
This is my code and I need it to return all letters that the user has not entered from the alphabet. For example, if the input is "abcd" the output in result should be the rest of the alphabet. It'd be really nice if someone could help. Right now the output of my code is the whole alphabet no matter what input is given. I tried getting the same letters to be output using "==" instead of "!=" and that worked. So I really don't understand why the opposite won't work.
String s;
System.out.println("input string:");
s = sc.nextLine();
char c;
String alphabet = "abcdefghijklmnopqrstuvwxyz";
Set<String> str = new HashSet<String>();
for(int i=0; i<s.length(); i++) {
c = s.charAt(i);
if( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
for(int j=0; j<alphabet.length(); j++){
if(c!=alphabet.charAt(j)) {
str.add(alphabet.charAt(j)+"");
}
}
}
}
System.out.println("result:");
System.out.println(str);
sc.close();
}
The contains method is appropriate in this case:
String s;
System.out.println("input string:");
s = sc.nextLine();
String alphabet = "abcdefghijklmnopqrstuvwxyz";
Set<String> str = new HashSet<String>();
for(int j=0; j<alphabet.length(); j++){
if(!s.contains(alphabet.charAt(j)+"")){
str.add(alphabet.charAt(j)+"");
}
}
System.out.println("result:");
System.out.println(str);
sc.close();
}
The best way to do this would be to use regular expressions (I don't know if you are allowed to do this)
Here's how to write it:
String s;
System.out.println("input string:");
s = sc.nextLine();
//then turn those letters into a regex character capture group
s = "[" + s + "]";
//then run the regular expression
String ans = alphabet.replaceAll(s,"");
If you're not allowed to use Regex, please update your question, and I'll delete this answer okay?
Your inner for-if actually says "for each input character c, output whole alphabet except c and union all results", which produces whole alphabet for any input of two distinct characters.
Initialize str set with all characters of alphabet and then remove each character from input. LinkedHashSet is important to preserve order (thanks to ControlAltDel).
static List<String> listByChar(String s) {
return s.chars().mapToObj(i -> String.valueOf((char)i)).collect(toList());
}
public static void main(String[] args) {
...
Set<String> str = new LinkedHashSet<>(listByChar(alphabet));
str.removeAll(listByChar(s));
System.out.println(str);
}
What remains in str is result you want.
s = sc.nextLine().toLowerCase();
It would be better to add this code.
So I have this program I need to write. I'm, supposed to get an input string from a user and then print out how many capital letters and how many lowercased letters are in the string. I've looked everywhere in the book that I have and I just can't seem to find anything about how to print out the uppercase and lowercase letters. I've been doing a lot of googling as well and I couldn't find anything useful.
Anyway here's my code:
import java.util.Scanner; //calls out the method to get input from user
public class Verk1 {
public static void main(String args[])
{
Scanner innslattur = new Scanner(System.in); //input gotten from user
System.out.println("Sláðu inn textabrot í há- og lágstöfum.");
System.out.println("Forritið mun þá segja þér hve margir stafir eru af hverri gerð.");
System.out.println("Textabrot: ");
//The printouts before tell the user to enter in a string, the program will then print out //how many upper- and lowercase letters there are.
String strengur = innslattur.nextLine();
String hastafir = "";
for (int i=0; i<hastafir.length();i++);
{
System.out.println("Í textabrotinu eru " + hastafir + " hástafir");
}
}
}
I know the code is faulty/doesn't work, but do any of you know how I get the number of uppercase- lowercase letters to print them out?
Thanks in advance!
Cheers
I haven't tested it but I would look to do something like this.
String text = "This IS My TEXT StrinG";
int upperCaseCounter = 0;
int lowerCaseCounter = 0;
for (int i=0; i<text.length(); i++)
{
if (Character.isUpperCase(text.charAt(i)))
{
upperCaseCounter++;
}
else if(Character.isLowerCase(text.charAt(i)))
{
lowerCaseCounter++;
}
}
System.out.println("Total Uppercase Characters: " + upperCaseCounter);
System.out.println("Total Lowercase Characters: " + lowerCaseCounter);
You can do their fairly easily if you convert the string to a char[] first. You can then use the isUpperCase(char c) for each character in the string. http://www.tutorialspoint.com/java/character_isuppercase.htm
For some strange reason your for loop is referring to an empty string you've just declared, rather than the string you just read in from the user. However, if you change that, inside your loop you can get at the individual characters in the string with strengur.charAt(i) and you can test whether a letter is capital with Character.isUpperCase(ch) and you can check for a lower case letter with Character.isLowerCase(ch).
public void printCapsAndLowercaseCounts(String s) {
int uppercase = 0;
int lowercase = 0;
if (s != null) {
String s1 = s.toUpperCase();
String s2 = s.toLowerCase();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == s1.charAt(i) ^ s.charAt(i) == s2.charAt(i)) {
if (s.charAt(i) == s1.charAt(i)) uppercase++;
else lowercase++;
}
}
}
System.out.println(uppercase + " " + lowercase);
}
Seems like this would do the trick, assuming you're not doing it an excessive amount. Just use a temporary string, and get the difference between the two:
int capLetterCount = originalString.length() - originalString.replaceAll("[A-Z]", "").length();
I have to use methods to test a sentence for palindromes and I have got most of it done but it will only do the first word in the string and won't move on to the next one. I believe its something got to do with the spaces, if anyone could help that'd be great. Also I haven't studied arrays so I'd appreciate if arrays were not used.
class palindromeTesting
{
public static void main(String[] args)
{
String userInput;
String goodWords;
String palindromes;
System.out.println("Please enter a sentance to be tested for palindrome: ");
userInput = EasyIn.getString();
userInput += " " ;
goodWords = charsCheck(userInput); //Calling a method to check if any word contains more than letters.
palindromes = palinCheck(goodWords); //Checking the good words to see if they're palindromes.
System.out.println("The valid palindromes are " + palindromes);
} //Main
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
public static String charsCheck(String userInput)
{
String validWords;
String firstWord;
Boolean goodWord;
int spacePos;
char letter;
spacePos = userInput.indexOf(" ");
validWords = "";
while(spacePos > 0)
{
firstWord = userInput.substring(0 , spacePos);
goodWord = true;
for(int index = 0 ; index < firstWord.length() && goodWord == true ; index++)
{
spacePos = userInput.indexOf(" ");
letter = Character.toUpperCase(firstWord.charAt(index));
if(letter < 'A' || letter > 'Z' )
{
goodWord = false;
}
} //for
if(goodWord == true)
{
firstWord = firstWord + " ";
validWords = validWords + firstWord;
}
userInput = userInput.substring(spacePos + 1);
spacePos = userInput.indexOf(" ");
} //While
return validWords;
} //charsCheck main
//-----------------------------------------------------------------------------------------------------------------------------------------------------------
public static String palinCheck(String goodWords)
{
String firstWord;
String validPalins = "";
String backward = "";
int spacePos;
spacePos = goodWords.indexOf(" ");
while(spacePos > 0)
{
firstWord = goodWords.substring(0 , spacePos);
for(int i = firstWord.length()-1; i >= 0; i--)
{
backward = backward + firstWord.charAt(i);
}
if(firstWord.equals(backward))
{
validPalins = validPalins + firstWord;
}
goodWords = goodWords.substring(spacePos + 1) ;
spacePos = goodWords.indexOf(" ") ;
}//While
return validPalins;
} //palinCheck main
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
} //Class
If you believe the issue are spaces, you could always remove all spaces (and any other unwanted characters) with the replaceAll() method (check out the API). Say you have word1 and word2 you'd like to compare to see if they are palindromes, then do the following:
String word1 = "du mb";
String word2 = "b,mu d";
word1 = word1.replaceAll(" ", "");//replace it with empty string
word1 = word1.replaceAll(",", "");//even if the comma doesn't exist, this method will be fine.
word2 = word2.replaceAll(" ", "");
word2 = word2.replaceAll(",", "");
Once you've gotten ridden of unnecessary characters or spaces, then you should do the check. Also, you could always use Regex expressions for this kind of task, but that may be a bit difficult to learn for a beginner.
Also, I recommend using for loops (can probably be done in one for loop, but nested loops will do) instead of while loop for this task. Check out this example.
Sidenote:
Also I haven't studied arrays so I'd appreciate if arrays were not
used.
Strings are essentially char arrays.
The problem you described is actually not what is happening; your code does indeed move on to the next word. For my test, I used the test input Hi my name is blolb.
The problem is in your palinCheck method. You are using the backward variable to reverse the word and check whether it and firstWord, are equal. However, you aren't resetting the backward variable back to a blank string in the loop. As a result, you're constantly adding to whatever was in there before from the previous loop. At the end of the method, if I examine the content of backward using my test string above, it actually looks like iHymemansiblolb.
To solve this, simply declare String backward inside the while loop, like so:
while(spacePos > 0) {
String backward = "";
// rest of loop
Quick side note:
During the run of the palinCheck method, you're changing the goodWords parameter each iteration when you do this:
goodWords = goodWords.substring(spacePos + 1) ;
While this is technically acceptable (it has no effect outside of the method), I wouldn't consider it good practice to modify the method parameter like this. I would make a new String variable at the top of the method, perhaps call it something like currentGoodWords or something like that, and then change your line to:
currentGoodWords = goodWords.substring(spacePos + 1) ;
Also, I assume this is homework, so if you are allowed to use it, I would definitely take a look at the StringBuilder#reverse() method that Elliot Frisch mentioned (I admit, I never knew about this method before now, so major +1s to Elliot).
I had this code written as a personal project quite a while ago on palindrome using the shortest amount of code. It basically strip every non-word character, put it to lower case just with 13 lines. Hope this help haha! Let's hope other guys would get lucky to find this too.
import java.util.Scanner;
public class Palindrome {
public static void main(String[]args){
if(isReverse()){System.out.println("This is a palindrome.");}
else{System.out.print("This is not a palindrome");}
}
public static boolean isReverse(){
Scanner keyboard = new Scanner(System.in);
System.out.print("Please type something: ");
String line = ((keyboard.nextLine()).toLowerCase()).replaceAll("\\W","");
return (line.equals(new StringBuffer(line).reverse().toString()));
}
}
I have a trouble with the for loop method that only loop 1 times whats is the problem? In the array was no problem at all, it able to print the value I want to.
here is my code:
public static void main(String[] args){
String s = "Apple0, Apple1, Apple2, Apple3, Apple4";
String[] word = s.split(",");
StringBuffer str = new StringBuffer();
Integer total = 0;
for (int y = 0; y < word.length; y++){
if(word[y].toString().equals("Apple2") ){
total++;
//str.append(word[y].toString());
}else if(word[y].toString().equals("Apple3") ){
total++;
//str.append(word[y].toString());
}else if(word[y].toString().equals("Apple4") ){
total++;
//str.append(word[y].toString());
}
else if(word[y].toString().equals("Apple1") ){
total++;
//str.append(word[y].toString());
}
}
System.out.println( word[0] + word[1] + word[2] + word[3] + word[4] + word.length);
System.out.println(str + "hihi" + total);
}
The others have nailed the cause of your problem. However, the fix they suggest is rather too specific ... and fragile. (Splitting with split("\\s*,\\s*") is better but it won't cope with whitespace at the start / end of the entire string.)
I suggest that you continue to use split(","), but trim the words before testing; e.g.
for (int y = 0; y < word.length; y++) {
String trimmed = word[y].trim();
if (trimmed.equals("Apple2")) {
total++;
//str.append(trimmed.toString());
} else if (trimmed.equals("Apple3")) {
// etcetera
or better still:
String[] words = s.split(",");
for (String word : words) {
String trimmed = word.trim();
if (trimmed.equals("Apple2")) {
total++;
//str.append(trimmed.toString());
} else if (trimmed.equals("Apple3")) {
// etcetera
That will make your code work irrespective of the whitespace characters around the commas and at the start and end of the string. Robustness is good, especially if it costs next to nothing to implement.
Finally, you could even replace the if / else if / ... stuff with a Java 7 String switch statement.
Try splitting on ", " (with space)
String[] word = s.split(", ");
without that space in split word[1] would look like " Apple1" instead "Apple1"
Other option would be calling word[y].trim().equals("Apple2") to get rid of that additional space, but I would say including it in split is better. If you aren't sure how many white-spaces can be near comma you can split this way split("\\s*,\\s*") to include all white-spaces around comma.
Also as Matt Ball pointed in his comment you don't need to call toString() on word[y] since it is already String.
you ignore the space during split. String[] word = s.split(", ");
You'are split by "," but your String contains ", ".
You can change the s.split(","); to s.split(", ");
Or trim the split's result like this :
public static void main(String[] args) {
String s = "Apple0, Apple1, Apple2, Apple3, Apple4";
String[] word = s.split(",");
StringBuffer str = new StringBuffer();
Integer total = 0;
for (int y = 0; y < word.length; y++) {
if (word[y].trim().equals("Apple2")) {
total++;
// str.append(word[y].toString());
} else if (word[y].trim().equals("Apple3")) {
total++;
// str.append(word[y].toString());
} else if (word[y].trim().equals("Apple4")) {
total++;
// str.append(word[y].toString());
} else if (word[y].trim().equals("Apple1")) {
total++;
// str.append(word[y].toString());
}
}
System.out.println(word[0] + word[1] + word[2] + word[3] + word[4]
+ word.length);
System.out.println(str + "hihi" + total);
}
There is nothing wrong with your code but the problem lies in the String that you are giving to the variable.
String s = "Apple0, Apple1, Apple2, Apple3, Apple4";
Here the string contains spaces between them after the comma. So that when you split your string it splits like
word[0]= "Apple0"
word[1]= " Apple1"
word[2]= " Apple2"
word[3]= " Apple3"
and so on.
So that when you compare like
word[y].equals("Apple1") it returns false because " Apple1" and "Apple1" are two different strings. So that initialize your string like this
String s = "Apple0,Apple1,Apple2,Apple3,Apple4"; // without white spaces
It will work fine. Or you can use trim method in your existing code without changing String like
word[y].trim().equals("Apple1") //It will trim all the leading and trailing white spaces.
Hope this helps.
The output is always a String, for example H,E,L,L,O,. How could I limit the commas? I want the commas only between letters, for example H,E,L,L,O.
import java.util.Scanner;
import java.lang.String;
public class forLoop
{
public static void main(String[] args)
{
Scanner Scan = new Scanner(System.in);
System.out.print("Enter a string: ");
String Str1 = Scan.next();
String newString="";
String Str2 ="";
for (int i=0; i < Str1.length(); i++)
{
newString = Str1.charAt(i) + ",";
Str2 = Str2 + newString;
}
System.out.print(Str2);
}
}
Since this is homework I'll help you out a little without giving the answer:
If you want the output to only be inbetween letters IE: A,B,C instead of A,B,C, which is what I imagine you are asking about. Then you need to look at your for loop and check the boundary conditions.
The easiest way I see is :
public static void main(String[] args) {
Scanner Scan = new Scanner(System.in);
System.out.print("Enter a string: ");
String Str1 = Scan.nextLine();
String newString="";
String Str2 ="";
for (int i=0; i < Str1.length()-1; i++)
{
newString = Str1.charAt(i) + ",";
Str2 = Str2 + newString;
}
Str2 = Str2 + Str1.charAt(Str1.length()-1);
System.out.println(Str2);
}
The output it will give is :
run:
Enter a string: Hello world
H,e,l,l,o, ,w,o,r,l,d
BUILD SUCCESSFUL (total time: 5 seconds)
Though I will highly recommend learning regular expression as suggested by #Roman. Till then this will do the trick. :)
Try regular expressions:
String input = scanner.next();
String output = input.replaceAll(".", "$0,");
With spaces it would be a bit easier since you don't need to abandon last 'odd' comma:
output = output.substring (0, ouput.length() - 2);
When you've figured out the loop-solution, you could try the following ;)
System.out.println(Arrays.toString("HELLO".toCharArray()).replaceAll("[\\[ \\]]", ""));
Just don't append the comma when the last item of the loop is to be appended. You have the item index by i and the string length by Str2.length(). Just do the primary school math with a lesser-than or a greater-than operator in an if statement.
The following snippet should be instructive. It shows:
How to use StringBuilder for building strings
How to process each char in a String using an explicit index
How to detect if it's the first/last iteration for special processing
String s = "HELLO";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (i == 0) { // first
sb.append("(" + ch + ")");
} else if (i == s.length() - 1) { // last
sb.append("<" + ch + ">");
} else { // everything in between
sb.append(Character.toLowerCase(ch));
}
}
System.out.println(sb.toString());
// prints "(H)ell<O>"