String anagram in Java - java

i am trying to create a program for string anagram that follows these conditions:
method should allow only letters, white space, commas and dots in an anagram. If there are any other characters, then the string cannot contain an anagram.
The method should ignore all white space, commas and dots when it checks the text.
If there are no letters in the text, then the text cannot be an anagram.
import java.util.Arrays;
import java.util.Scanner;
public class StringAnagram {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter first string: ");
String first = in.nextLine().toUpperCase();
System.out.print("Enter second string: ");
String second = in.nextLine().toUpperCase();
String result = isAnagram(first, second);
System.out.println(result);
}
private static String isAnagram(String first, String second) {
String answer = "";
if (first.matches("[A-Z\\.\\,\\s]")) {
String st = first.replaceAll("\\.\\,\\s", "");
String nd = second.replaceAll("\\.\\,\\s", "");
char[] arraySt = st.toCharArray();
char[] arrayNd = nd.toCharArray();
Arrays.sort(arraySt);
Arrays.sort(arrayNd);
if(Arrays.equals(arraySt, arrayNd)) {
answer = "Anagram.";
}
else {
answer = "No anagram.";
}
}
else {
answer = "No anagram.";
}
return answer;
}
}
However when the program tests these 2 sentences, they are not anagram but they should be anagram. I have no idea where to look for mistake.
Eleven plus two is thirteen.
Twelve plus one is thirteen.

If you start your method as follows, it will fulfil validations mentioned in the 1st and the 3rd points of your question:
if (first == null || second == null || first.equals("") || second.equals("") || !first.matches("[A-Za-z,. ]+")
|| !second.matches("[A-Za-z,. ]+")) {
return "No anagram.";
}
The next thing you should do is to replace all white space, commas and dots with "" in order to ignore them:
String st = first.replaceAll("[,. ]+", "");
String nd = second.replaceAll("[,. ]+", "");
The complete code is as follows:
private static String isAnagram(String first, String second) {
if (first == null || second == null || first.equals("") || second.equals("") || !first.matches("[A-Za-z,. ]+")
|| !second.matches("[A-Za-z,. ]+")) {
return "No anagram.";
}
String answer = "";
String st = first.replaceAll("[,. ]+", "");
String nd = second.replaceAll("[,. ]+", "");
if (st.equals("") || nd.equals("")) {
return "No anagram.";
}
char[] arraySt = st.toCharArray();
char[] arrayNd = nd.toCharArray();
Arrays.sort(arraySt);
Arrays.sort(arrayNd);
if (Arrays.equals(arraySt, arrayNd)) {
answer = "Anagram.";
} else {
answer = "No anagram.";
}
return answer;
}
A test run:
Enter first string: london
Enter second string: britain
No anagram.
Another test run:
Enter first string: ram
Enter second string: mar
Anagram.
Another test run:
Enter first string: .
Enter second string: .
No anagram.
Another test run:
Enter first string: ,
Enter second string: .
No anagram.
Another test run:
Enter first string: ra.m
Enter second string: a.m.r
Anagram.

This: first.matches("[A-Z\\.\\,\\s]") tests if the first value is a single character that is either 1 capital letter, or a dot, or a comma, or any whitespace character.
Completely not what you want.
You can add System.out.println statements all over the place to print where your code is and the value of relevant variables. Follow the code along like you're the computer. There where what you think should happen does not match with what the sysout statements tell you – there is a bug there (there can be many, especially if you write this much stuff without testing anything first).
Better yet, use a debugger.
NB: Something as trivial as replacing one of your No anagram. strings with anything else just so you know which of the two got triggered would already have helped a lot.
NB: first.replaceAll("\\.\\,\\s", ""); is also broken; you've written way too much code here; test each individual moving piece. It's like a bike that doesn't do anything after you put it together: Take it apart piece by piece, test each piece individually.

This solution accepts strings from console input. That portion is omitted since that is working for you.
The idea is to selectively reduce the essence of what you are comparing to the bare minimum. Comments are provide to explain the logic. In the examples, all but the third one report as an anagram.
System.out.println(isAnagram("radar", "darar"));
System.out.println(isAnagram("ra.,. dar", "d.,a rar"));
System.out.println(isAnagram("r+a.,. dar", "d.,a + rar"));
System.out.println(isAnagram("Eleven plus two is thirteen.", "Twelve plus one is thirteen."));
// This method accepts mixed case strings. The conversion to upper case is
// done within the method.
public static String isAnagram(String first, String second) {
// get rid of allowed characters and convert to upper case
String st = first.replaceAll("[., ]","").toUpperCase();
String nd = second.replaceAll("[., ]","").toUpperCase();
// Now get rid of all alpha characters and compare to the empty string.
// Only if both are equal are the strings potential anagrams.
// Otherwise, the illegal characters would be present.
if (st.replaceAll("[A-Z]","").equals("") &&
nd.replaceAll("[A-Z]","").equals("")) {
// this is your original code
char[] arraySt = st.toCharArray();
char[] arrayNd = nd.toCharArray();
Arrays.sort(arraySt);
Arrays.sort(arrayNd);
// don't set a value just return it's an
// anagram
if (Arrays.equals(arraySt, arrayNd)) {
return "Anagram.";
}
}
// Otherwise, it's not
return "No Anagram.";
}

Related

How can I prevent the user from entering the same letter in Hangman JAVA?

I am writing a hangman program and one of the requirements to a hangman game is preventing the user from entering the same letter twice.
I have written the code for that, but the problem is every time I enter a letter it says it is already entered. I need to only say it when it is entered the second time. You guys have any suggestions? I've been trying to fix this for the past few hours, I figured I could ask on here to find some help. I already looked at another Stackoverflow question regarding something similar to this but all those solutions have the same result.
In Java, how can I determine if a char array contains a particular character?
I've tried something like this but it won't work either:
boolean contains = false;
for (char c : store) {
if (c == character) {
System.out.println("Already Entered");
contains = true;
break;
}
}
if (contains) {
// loop to top
continue;
}
SECOND CLASS-
public void hangman(String word, int life) {
KeyboardReader reader = new KeyboardReader();
char[] letter = new char[word.length()];
char[] store = new char[word.length()];
String guess;
int i = 0, tries = 0, incorrect = 0, count = 1, v = 0;
while (i < word.length()) {
letter[i] = '-';
I would just use the String.contains() method:
String aString = "abc";
char aChar = 'a';
return aString.contains(aChar + "");
To keep track of guessed letters you can use a StringBuffer, appending them using a StringBuffer.append() to append new letters (maintaining state) and use the StringBuffer.toString() method to get the String representation when you need to do the comparison above.
Since Java 1.5 the class String contains the method contains(). My idea is to collect all entered letters into a string variable and using above method:
// My code line
String letterAlreadyEntered = "";
// Your code line
char character = reader.readLine().charAt(0);
// My code line
if (letterAlreadyEntered.contains("" + character) == true) {
//Put code here what ever you want to do with existing letter
} else {
letterAlreadyEntered += character;
}
In my opinion, this is an easier way to check for occurrences than in arrays, where you have to write your own check method.

How to Test if Input String is Null in Java

So I created some code to check if the first letter of the word that the user enters (stored in the variable word) is a consonant or vowel. If it is neither it outputs saying it is neither. However, I am using nextLine() instead of next() to get input. I understand that next() will not take input until they enter a valid character besides a space, and I know that nextLine() will go to the else statement if they enter just spaces. However, in nextLine when the user just puts enter and does not enter any character, no spaces, the program crashes. I tried checking if the string was equal to null and then making it print out "test" if it was proven true, however for some reason whenever I press enter I still get an error. Below is my code:
import java.util.Scanner;
public class WordStart {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.printf("Please enter a word: ");
String word = in.nextLine();
String lowerWord = word.toLowerCase();
String x = lowerWord.substring(0,1);
String test = null;
String empty = new String();
boolean vowel = x.equals("a")||x.equals("e")||x.equals("i")||
x.equals("o")||x.equals("u");
boolean conc = x.equals("b")||x.equals("c")||x.equals("d")||x.equals("f")||
x.equals("g")||x.equals("h")||x.equals("j")||x.equals("k")||
x.equals("l")||x.equals("m")||x.equals("n")||x.equals("p")||
x.equals("q")||x.equals("r")||x.equals("s")||x.equals("t")||
x.equals("v")||x.equals("w")||x.equals("x")||x.equals("y")||
x.equals("z");
if(vowel){
System.out.printf("%s starts with a vowel.\n", word);
}
else if(conc){
System.out.printf("%s starts with a consonant.\n", word);
}
else if(word.equals("")){
System.out.println("testEmpty");
}
else if(word.isEmpty()){
System.out.println("testNull");
}
else{
System.out.printf("%s starts with neither a vowel nor a consonant.\n", word);
}
}
}
Basically, I am trying to check if the user just pressed enter without entering anything and call them out on it. What method, line of code would help me do that. I tried using word.equals(null), but the IDE said that it was never true. Thanks in advance.
The error code I get when I just press enter is as follows
run:
Please enter a word:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.substring(String.java:1963)
at WordStart.main(WordStart.java:8)
C:\Users\Jordan\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 3 seconds)
I think the problem lies with this line:
String x = lowerWord.substring(0,1);
If the string is empty (nextLine will never return a null string) it is impossible to take a substring. You should probably check that the string is > 0 characters long.
if(x.length > 0)
String x = lowerWord.substring(0,1);
Firstly note that word.equals("") and word.isEmpty() checks the same condition. So there is no need to use them both. To check whether is String null use if (word == null). Checking the null and the emptyness of the String should be the first one you do.
Secondly in case you skip the input (get the empty String ""), you get IndexOutOfBoundsException, because lowerWord.substring(0,1); has no chance to find that index.
So:
if (word != null && !word.isEmpty()) {
// ...
}
Just check if it is null
if(variable==null)
should suffice

How to prevent integer input in Java?

I am trying to get my code to prevent a user input from having a number in it.
Essentially I want the code to do as follows:
ask for input
receive input
test whether or not the input contains a number(ex: 5matt vs matt)
if contains a number I want to System.out.println("Error: please do not input a number");
Heres the kicker (and why it's not a duplicate question): I can't use loops or other statements we haven't learned yet. So far the only true statements we've learned are if/else/else if statements. That means I can not use for loops, like some of the answers are suggesting. While they're great answers, and work, I'll lose points for using them.
System.out.println("Please input the first name: ");
String name1 = in.next();
System.out.println("Please input the second name: ");
String name2 = in.next();
System.out.println("Please input the third name: ");
String name3 = in.next();
name1 = name1.substring(0,1).toUpperCase() + name1.substring(1).toLowerCase();
name2 = name2.substring(0,1).toUpperCase() + name2.substring(1).toLowerCase();
name3 = name3.substring(0,1).toUpperCase() + name3.substring(1).toLowerCase();
I have this already but I can't figure out how to test if the input only contains letters.
Okay, there are many ways to deal with this. A good thing would be to use Regex (text matching stuff). But it seems that you should only use very basic comparison methods.
So, let's do something very basic and easy to understand: We iterate over every character of the input and check whether it's a digit or not.
String input = ...
// Iterate over every character
for (int i = 0; i < input.length(); i++) {
char c = s.charAt(i);
// Check whether c is a digit
if (Character.isDigit(c)) {
System.out.println("Do not use digits!");
}
}
This code is very straightforward. But it will continue checking even if a digit was found. You can prevent this using a helper-method and then returning from it:
public boolean containsDigit(String text) {
// Iterate over every character
for (int i = 0; i < input.length(); i++) {
char c = s.charAt(i);
// Check whether c is a digit
if (Character.isDigit(c)) {
return true;
}
}
// Iterated through the text, no digit found
return false;
}
And in your main program you call it this way:
String input = ...
if (containsDigit(input)) {
System.out.println("Do not use digits!");
}
Use a regular expression to filter the input
Eg
str.matches(".*\\d.*")
See this link for more info
There are several ways you could do this, among others:
Iterate over all the chars in the string and check whether any of them is a digit.
Check whether the string contains the number 1, number 2, number 3, etc.
Use a regular expression to check if the string contains a digit.
(Java Regular Expressions)
If you're allowed to define functions, you can essentially use recursion to act as a loop. Probably not what your prof is going for, but you could be just inside the requirements depending on how they're worded.
public static boolean stringHasDigit(String s) {
if (s == null) return false; //null contains no chars
else return stringHasDigit(s, 0);
}
private static boolean stringHasDigit(String s, int index) {
if (index >= s.length()) return false; //reached end of string without finding digit
else if (Character.isDigit(s.charAt(index))) return true; //Found digit
else return stringHasDigit(s, index+1);
}
Only uses if/elseif/else, Character.isDigit, and String.charAt, but recursion might be off limits as well.

I want to know how to find a special character in a string

I am programming in Java in Eclipse, I want to ask users to enter their specific ID, Which starts with an uppercase G and has 8 digit numbers. like G34466567. if the user enters an invalid ID it will be an error. how can i separate a valid ID from others?
You can use regex. This pattern checks if the first character is a capital G and there are 8 digits following:
([G]{1})([0-9]{8})$
As you see there are two expressions which are separated by the (). The first says "only one character and this one has to be a capital G". And the second one says, there have to be 8 digits following and the digits can be from 0 to 9.
Every condition contains two "parts". The first with the [] defines which chars are allowed. The pattern inside the {} show how many times. The $ says that the max length is 9 and that there can't be more chars.
So you can read a condition like that:
([which chars are allowed]{How many chars are allowed})
^------------------------\/---------------------------^
One condition
And in Java you use it like that:
String test= "G12345678";
boolean isValid = Pattern.matches("([G]{1})([0-9]{8})$", test);
As you see that matches method takes two parameters. The first parameter is a regex and the second parameter is the string to check. If the string matches the pattern, it returns true.
Create an ArrayList. Ask the user to input the ID, check if it is already there in the list, ignore, otherwise add that ID to the list.
EDIT: For ensuring that the rest 8 characters of the String ID are digits, you can use the regex "\\d+". \d is for digits and + is for one or more digits.
Scanner sc = new Scanner(System.in);
ArrayList<String> IDS = new ArrayList();
char more = 'y';
String ID;
String regex = "\\d+";
while (more == 'y') {
System.out.println("Pleaes enter you ID.");
ID = sc.next();
if (IDS.contains(ID)) {
System.out.println("This ID is already added.");
} else if (ID.length() == 9 && ID.charAt(0) == 'G' && ID.substring(1).matches(regex)) {
IDS.add(ID);
System.out.println("Added");
} else {
System.out.println("Invalid ID");
}
System.out.println("Do you want to add more? y/n");
more = sc.next().charAt(0);
}
Assuming that you save the id as a string, you can check the first letter and then check if the rest is a number.
Ex.
String example = "G12345678";
String firstLetter = example.substring(0, 1); //this will give you the first letter
String number = example.substring(1, 9); //this will give you the number
To check that number is a number you could do the following instead of checking every character:
try {
foo = Integer.parseInt(number);
} catch (NumberFormatException e) {
//Will Throw exception!
//do something! anything to handle the exception.
// this is not a number
}

return the first word in any string (Java)

I have to be able to input any two words as a string. Invoke a method that takes that string and returns the first word. Lastly display that word.
The method has to be a for loop method. I kind of know how to use substring, and I know how to return the first word by just using .substring(0,x) x being how long the first word is.
How can I make it so that no matter what phrase I use for the string, it will always return the first word? And please explain what you do, because this is my first year in a CS class. Thank you!
I have to be able to input any two words as a string
The zero, one, infinity design rule says there is no such thing as two. Lets design it to work with any number of words.
String words = "One two many lots"; // This will be our input
and then invoke and display the first word returned from the method,
So we need a method that takes a String and returns a String.
// Method that returns the first word
public static String firstWord(String input) {
return input.split(" ")[0]; // Create array of words and return the 0th word
}
static lets us call it from main without needing to create instances of anything. public lets us call it from another class if we want.
.split(" ") creates an array of Strings delimited at every space.
[0] indexes into that array and gives the first word since arrays in java are zero indexed (they start counting at 0).
and the method has to be a for loop method
Ah crap, then we have to do it the hard way.
// Method that returns the first word
public static String firstWord(String input) {
String result = ""; // Return empty string if no space found
for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
result = input.substring(0, i);
break; // because we're done
}
}
return result;
}
I kind of know how to use substring, and I know how to return the first word by just using .substring(0,x) x being how long the first word is.
There it is, using those methods you mentioned and the for loop. What more could you want?
But how can I make it so that no matter what phrase I use for the string, it will always return the first word?
Man you're picky :) OK fine:
// Method that returns the first word
public static String firstWord(String input) {
String result = input; // if no space found later, input is the first word
for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
result = input.substring(0, i);
break;
}
}
return result;
}
Put it all together it looks like this:
public class FirstWord {
public static void main(String[] args) throws Exception
{
String words = "One two many lots"; // This will be our input
System.out.println(firstWord(words));
}
// Method that returns the first word
public static String firstWord(String input) {
for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
return input.substring(0, i);
}
}
return input;
}
}
And it prints this:
One
Hey wait, you changed the firstWord method there.
Yeah I did. This style avoids the need for a result string. Multiple returns are frowned on by old programmers that never got used to garbage collected languages or using finally. They want one place to clean up their resources but this is java so we don't care. Which style you should use depends on your instructor.
And please explain what you do, because this is my first year in a CS class. Thank you!
What do I do? I post awesome! :)
Hope it helps.
String line = "Hello my name is...";
int spaceIndex = line.indexOf(" ");
String firstWord = line.subString(0, spaceIndex);
So, you can think of line as an array of chars. Therefore, line.indexOf(" ") gets the index of the space in the line variable. Then, the substring part uses that information to get all of the characters leading up to spaceIndex. So, if space index is 5, it will the substring method will return the indexes of 0,1,2,3,4. This is therefore going to return your first word.
The first word is probably the substring that comes before the first space. So write:
int x = input.indexOf(" ");
But what if there is no space? x will be equal to -1, so you'll need to adjust it to the very end of the input:
if (x==-1) { x = input.length(); }
Then use that in your substring method, just as you were planning. Now you just have to handle the case where input is the blank string "", since there is no first word in that case.
Since you did not specify the order and what you consider as a word, I'll assume that you want to check in given sentence, until the first space.
Simply do
int indexOfSpace = sentence.indexOf(" ");
firstWord = indexOfSpace == -1 ? sentence : sentence.substring(0, indexOfSpace);
Note that this will give an IndexOutOfBoundException if there is no space in the sentence.
An alternative would be
String sentences[] = sentence.split(" ");
String firstWord = sentence[0];
Of if you really need a loop,
String firstWord = sentence;
for(int i = 0; i < sentence.length(); i++)
{
if(sentence.charAt(i) == ' ')
{
sentence = firstWord.substring(0, i);
break;
}
}
You may get the position of the 'space' character in the input string using String.indexOf(String str) which returns the index of the first occurrence of the string in passed to the method.
E.g.:
int spaceIndex = input.indexOf(" ");
String firstWord = input.substring(0, spaceIndex);
Maybe this can help you figure out the solution to your problem. Most users on this site don't like doing homework for students, before you ask a question, make sure to go over your ISC book examples. They're really helpful.
String Str = new String("Welcome to Stackoverflow");
System.out.print("Return Value :" );
System.out.println(Str.substring(5) );
System.out.print("Return Value :" );
System.out.println(Str.substring(5, 10) );

Categories

Resources