I need to check if two strings are anagrams but I cant use arrays.sort ... I know that I have to use for loop but I do not know how to start so that the chararray would be sorted alphabetically. Please, help me.
import java.util.Scanner;
public class Assignement3{
public static void main (String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println( "Please, type the first word: ");
String word1=sc.nextLine();
System.out.println( "Please, type the second word: ");
String word2=sc.nextLine();
String word1lower=word1.toLowerCase().replace(" ","");
String word2lower=word2.toLowerCase().replace(" ","");
System.out.println("Your First word is: " + word1lower);
System.out.println("Your Second word is: " + word2lower);
char[] firstword=word1lower.toCharArray();
char[] secondword=word2lower.toCharArray();
}
}`
I think that providing code which determines whether two strings are meaningful or actual anagrams of each other would require doing a lookup in a dictionary. But if we define an anagram of a word as being some permutation of the existing characters in the original word, then we can check for this fairly easily.
In the code snippet below, I read the characters from the first word into a map, keeping counts of the occurrences of each letter. This map of characters represents everything which is available to form a potential anagram. By iterating over the second word and keeping track of each character consumed, we can tell if the second word be an anagram. The marker for failure would be trying to use a character which does not appear or which has been exhausted already. Otherwise, the second word is a potential anagram.
String word1lower = "hala babel";
String word2lower = "baha label";
char[] firstword = word1lower.toCharArray();
char[] secondword = word2lower.toCharArray();
Map<Character, Integer> m1 = new HashMap<>();
int count = 0;
for (char c : firstword) {
Integer cnt = m1.get(c);
m1.put(c, cnt == null ? 1 : cnt.intValue() + 1);
++count;
}
boolean isAnagram = true;
for (char c : secondword) {
Integer cnt = m1.get(c);
if (cnt == null || cnt.intValue() == 0) {
isAnagram = false;
break;
}
m1.put(c, cnt.intValue() - 1);
--count;
}
if (isAnagram && count == 0) {
System.out.println("Second word is a full anagram of the first word.");
}
else if (isAnagram) {
System.out.println("Second word is a partial anagram of the first word.");
}
else {
System.out.println("Second word is not an anagram of the first word.");
}
Again, I say potential anagram here because to check whether a random combination of characters corresponds to an actual English (or other language) word would require a dictionary. This is way past the scope of a single Stack Overflow question, but hopefully my answer gets you thinking in the right direction.
Demo here:
Rextester
Related
I want to print a letter instead of the index position using the indexOf(); method.
The requirement is that: Inputs a second string from the user. Outputs the character after the first instance of the string in the phrase. If the string is not in the phrase, outputs a statement to that effect. For example, the input is 3, upside down, d. The output should be "e", I got part of it working where it inputs an integer rather than a string of that particular position. How would I output a string?
else if (option == 3){
int first = 0;
String letter = keyboard.next();
first = phrase.indexOf(letter,1);
if (first == -1){
System.out.print("'"+letter+"' is not in '"+phrase+"'");
}
else {
System.out.print(first + 1);
}
}
String.charAt(index)
You can access a single character, or a letter, by caling método charAt() from String class
Example
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String phrase = keyboard.nextLine();
char firstLetter = phrase.charAt(0);
System.out.println("First Letter : " + firstLetter);
}
So, running this code, assuming the input is StackOverFlow, the output will be S
In your code I think doing the follow will work:
Your Code
String letter = keyboard.next();
first = letter.charAt(0);
That might help!
Based on those comments
So, what you want is print the first letter based on a letter the user
has input? For example, for the word Keyboard, and user inputs letter
'a' the first letter might be 'R'. Is that it? – Guerino Rodella
Yes, I have to combine both the indexOf(): method and the charAt():
method – Hussain123
The idea is get next letter based on user input letter.
I'm not sure I wunderstood it, but this is my shot
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String phrase = "keyboard";
String userInput = keyboard.nextLine();
boolean notContainsInputValue = !phrase.contains(userInput);
if (notContainsInputValue) {
System.out.println("The input value doesn't exists");
return;
}
char firstLetter = userInput.charAt(0);
int desiredIndex = 0;
for (int i = 0; i < phrase.length(); i++) {
if (phrase.charAt(i) == firstLetter) {
desiredIndex = i;
break;
}
}
System.out.println("The index for your input letter is: " + desiredIndex);
System.out.println("Next letter based on input value is: " + phrase.charAt(desiredIndex + 1));
}
The Output
The index for your input letter is: 5
Next letter based on input value is: r
Hope that helps you.
I'm just starting out with Java so I'm pretty new to this programming language. I've been looking at similar problems for hours now but nothing specific enough to follow that seems to help me.
How do I check to see if the last letter of the first word is the same as the next word's first letter? For example, the user inputs: Chocolate Elephant Toronto. Chocolate's last letter is 'e', which is the first letter of elephant, and then the last letter of elephant is 't', which is the first letter of Toronto.
I want to make it so if all the words correctly follow one another, it will print something like "They all match" and if not, then "second word does not follow first word".
I'm just looking for tips on how to do this if the user decides to enter a different amount of words each time to check. I'm guessing I'll need a String Array, but can I still solve this using charAt?
You can use a method like the following:
private static boolean wordCheck(String[] words) {
if(words.length < 2) {
return true; //check what to return if only 1 word is passed
}
for(int i = 1; i < words.length; i++) {
String currentWord = words[i].toLowerCase();
String previousWord = words[i - 1].toLowerCase();
if(!currentWord.startsWith(previousWord.substring(
previousWord.length() - 1))) {
return false;
}
}
return true;
}
It just checks each word's beginning against its preceding word's ending.
wordCheck("Chocolate Elephant Toronto".split(" ")) //returns true
wordCheck("Chocolate Elephant oronto".split(" ")) //returns false
Remember to validate the words that you send to the method. The above doesn't ensure indexes are valid, nulls and 0-length strings can cause exceptions.
Try something like this:
public String checkWords(String phrase){
if(phrase == null){
return "Phrase must not be null";
}
String[] words = phrase.toLowerCase().split(" ");
if(words.length < 2){
return "At least 2 words!";
}
for (int i = 0; i < (words.length - 1); i++) {
String firstWord = words[i].trim();
char firstWordlastLetter = firstWord.charAt(firstWord.length()-1);
String secondWord = words[i+1].trim();
char secondWordFirstLetter = secondWord.charAt(0);
if(firstWordlastLetter!=secondWordFirstLetter){
return String.format("Word %d does not follow word %d", i+1, i);
}
}
return "They all match";
}
In Java, I am supposed to make a word game where one is supposed to make letters with a given set of random letters. I have already wrote the code to find the letters (Variable is String Letters ), but I am having trouble checking if the word chosen by the player (String word), is actually created using the given letters? I have a txt file of all the English words in the English language, and this is what I am basing it off if it is a word. How do I do this? I am pretty sure it has something to do with checking the index, or using the built in command contains at.
I have already tried to search for this. However other questions used C-Language or Python. I have found 1 Java explanation, however I am new to coding and do not understand the code and variables they used.
This is an example of where I need help
if (Words.contains(letters) == true) {
System.out.println("That is a word");
for (int i = 0; i < word.length(); i++) {
int index = letters.indexOf(word.charAt(i));
}
Full method.
public static void getWord(String letters) {
int trys = 0;
int trysLeft = 5;
System.out.println("Input a word that you can make with those letters");
while (trys < 5) {
String word = getString(); //getString is a method where user can input a desired string
if (Words.contains(letters) == true) {
System.out.println("That is a word");
for (int i = 0; i < word.length(); i++) {
int index = letters.indexOf(word.charAt(i));
}
}
else if (Words.contains(word) == false) {
System.out.println("That is not a real word! Please enter a word that you can make with these letters.");
trys++;
trysLeft=trysLeft-trys;
System.out.println("You have " + trysLeft + " trys Left. Keep at it!");
}
else if (Words.contains(letters) == false) {
System.out.println("You can not make a word with these letters.");
trys++;
trysLeft=trysLeft-trys;
System.out.println("You have " + trysLeft + " trys Left. Keep at it!");
}
}
}
You need to check the cointains for each letter. If you send a charSeq, example { 'a' , 'b', 'd' }, java will try to find if your string contains completely "abd"
One way to do it is to sort the letters in your letter list and your word and see if your word is contains in the available letters, like this:
public static void main(String args[]) {
String letters = sort("haat");
System.out.println("Is a word: " + letters.contains(sort("hat")));
}
public static String sort(String s)
{
char[] chars = s.toCharArray();
Arrays.sort(chars);
return new String(chars);
}
There are many techniques that you could use to implement this class project.
Here is one:
Build a Map from the input letters. The key of the map should be a Character and the Value of the map should be the count of letters.
Build a Map from the word guess. Again, the key of the map should be a Character and the Value of the map should be the count of letters.
Compare the maps. If they are equal, then the word is constructed from exactly the letters in the input letters string.
Recently, I've been trying to build a program that does 4 things:
1) Enter a word from the keyboard.
2) Check the context of this word with the context of a string that contains the letters of the alphabet.
3) Compare the letters of the given word with the letters of the alphabet string and whenever there is match, it will return the position of that letter in the alphabet string +1. (ex. word='a' position=1 since 'a' is the first letter)
4) Get the total of all of these positions.(ex. word='abc' total=6)
Now let me show you what I've written in terms of code.
//Part 1 Entering word from keyboard
package IntroductionJava;
import java.util.Scanner;
public class Numerology
{
public static void main(String[] args)
{
int m=0,n=0,sum=0;
int j,k;
Scanner user_input=new Scanner(System.in);
String word;
System.out.print("Give a word: ");
word=user_input.next();
String word1 = "\u03b1\u03b2\u03b3\u03b4\u03b5\u03b6\u03b7\u03b8\u03b9\u03ba\u03bb\u03bc\u03bd\u03be\u03bf\u03c0\u03c1\u03c3\u03c2\u03c4\u03c5\u03c6\u03c7\u03c8\u03c9";
//Part 2 check word
for(int i=0; i<word.length(); i++)
{
if(word.charAt(i)>=word1.charAt(0) && word.charAt(i)<=word1.charAt(word1.length()-1))
{
System.out.println("Your word '"+word+"' is valid.");
break;
}
else
{
System.out.println("Your word '"+word+"' is invalid.");
}
break;
//show System.out.print(word.charAt(i));
}
//Part 3 Compare letters
for(j=0; j<word.length(); j++)
{
for(k=0; k<word1.length(); k++)
{
if(word.charAt(j)==word1.charAt(k))//???
{
m=k+1;
}
}
}
}
Now, Part 1 and 2 are working fine.
My problem lies when I try to compare the letters of the word that I'm entering with the String of letters in unicode format(the letters in unicode format are from the Greek alphabet). I've tried many variations, I've also consulted some of the articles here but I couldn't find a solution.
To make things a bit more clear let's say that I'm entering the word: "hello". I want to check whether 'h' is inside the alphabet string, and if it is I want to get it's position as an integer which in our case it's the number '8' (position in the string +1) and so on.
And the last part of my program is to get all those numbers from the given word and get it's total ('hello'=8+5+12+12+20=57).
Thank you very much in advance.
How about this:
String alphabet = "abcdefgh";
String input = "abc";
int value = input.chars()
.map(alphabet::indexOf)
.map(i -> i + 1)
.sum()
System.out.println(value);
I made a program that lets a user enter in a word or a phrase or a sentence and reverse it and display the result.
My issue is that when I run it it does reverse it but it reverses the words when all I want to do is keep the words as they were inputted and just reverse them.
Here is what I have currently
//import statements
import java.util.*; //for scanner class
// class beginning
class WordReverser {
public static void main(String[] args ) {
//Declare variables area
String original, reverse = "";
Scanner in = new Scanner(System.in);
boolean blankString = false;
public StringBuilder reverse();
// beginning message to user to explain the program
System.out.println("Welcome to my reverse word program!");
System.out.println("Please enter in a word or a phrase and see it reversed: ");
//main code and calculations to do
while (!blankString){
System.out.println("Enter a string to reverse");//Collect inputs from user.
original = in.nextLine();
if (original.equals(""))
{
blankString = true ;
}
else {
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
System.out.println("Reverse of entered string is: "+reverse);//Output results here
}
}
//End program message
System.out.println();
System.out.println("Hope you enjoyed using this program!");
}// end main method
}// end class
Clearly a homework question, so I'll give you a shove in the right direction, but I won't give the full answer. You need to reverse one word at a time and not the whole string.
You need something that implements this pseudo code:
original = getStringFromUser();
words[] = breakIntoWords(original);
foreach word in words {
reversed = reverse(word);
print reversed;
}
reverse(string word)
{
return reversed version of the input
}
breakIntoWords(sting sentence)
{
return array with each word as a sep.element
}
If you read the docs, you may find reverse and breakIntoWords are already there for you, so you just need to call the right methods.
The key to solving problems is learning how to break them down into smaller pieces that are easier to solve. This is a good problem solving technique and is at the heart of programming.
You know how to reverse the letters in a sentence. You want to reverse the letters in each word, but leave the words in their original order. Or, to say it another way, you want to:
Split the sentence into separate words.
Reverse each word one by one.
Combine the words back together into a sentence.
Hopefully each of these steps is more manageable. If not, think about how you can break them into even smaller steps. For instance, for #2 maybe you need a loop and then something inside that loop.
Do you want to reverse the word order? In this case you'll have to split the input string at " ".
To do this, your else-block should be
String[] words = original.split(" ");
for(int i = words.length-1; i>=0; i--)
reverse += words[i] + " ";
System.out.println("Reverse of entered string is: "+reverse);
I see 2 ways of dealing with this quickly if not too elegantly
easiest thing to do would be to create a 3rd variable called something like String originalWords that gets appended to from stdin in the loop.
Reuse the existing 'original' String to do the same as above and then loop it in reverse in a second loop.
You can split the input string into separate array of words and then reverse each word in the array separately.
Refer this for code.
I have refactored your code a little bit to solve your issue. First I put your reverse logic in a separate method
public static String reverse(String strToReverse) {
String original = strToReverse, reverse = "";
boolean blankString = false;
if (original.equals(""))
{
blankString = true ;
}
else {
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
}
return reverse;
}
Second I splitted your string into words (assuming the words are separated by simple spaces)
public static void main(String[] args ) {
//Declare variables area
String original, reverse = "";
Scanner in = new Scanner(System.in);
boolean blankString = false;
//public StringBuilder reverse();
// beginning message to user to explain the program
System.out.println("Welcome to my reverse word program!");
System.out.println("Please enter in a word or a phrase and see it reversed: ");
//main code and calculations to do
while (!blankString){
System.out.println("Enter a string to reverse");//Collect inputs from user.
original = in.nextLine();
if (original.equals(""))
{
blankString = true ;
}
else {
String[] words = original.split(" ");
String[] reversedWords = new String[words.length];
StringBuilder reverseBuilder = new StringBuilder();
for (int index = 0; index < words.length; index++) {
reversedWords[index] = reverse(words[index]);
reverseBuilder.append(reversedWords[index] + " ");
}
System.out.println("Reverse of entered string is: "+reverseBuilder.toString());//Output results here
}
}
//End program message
System.out.println();
System.out.println("Hope you enjoyed using this program!");
}// end main method
Here is an execution example: