I'm having trouble comparing an array that holds a word that's broken up into letters. Here is my code: (it's part of a hangman game)
public static void isGuessCorrect( String guess, String wordInPlay, String[] hangmanScores){
String[] letterGuessedAgainst = wordInPlay.split("");
for (int i = 0;i < letterGuessedAgainst.length; i ++)
System.out.print(letterGuessedAgainst[i]);
System.out.println("Letter guessed against is: "+letterGuessedAgainst[1]);//testing purposes
System.out.println("My guess is: "+guess.charAt(0));//testing purposes
for (int i = 0;i < letterGuessedAgainst.length; i++){
if (letterGuessedAgainst.equals(guess.charAt(0))){//this line isn't working
System.out.println("they're equal");//want it to return this
}//end if
else
System.out.println("they're not");//returns this instead
}//end for
}//end method
guess is a String
holds a letter
wordInPlay is the word that is in play
letterGuessedAgainst is the letter of the word that is being played
hangmanScores is an array that only holds "_", corresponding to the number of letters in the word
Any help would be immensely appreciated! Thanks!
The problem is that letterGuessedAgainst is an array and you are trying to compare a String[] vs char
if (letterGuessedAgainst.equals(guess.charAt(0))){//this line isn't working
First of all, you have to use the index i in the loop
letterGuessedAgainst[i]
Secondly, you need to compare against guess and not guess.charAt(0) since you will not be able to do equals() when comparing String and char
Since you already defined that guess is a String the contains only 1 character then you could do:
if (letterGuessedAgainst[i].equals(guess)) {
Updated your code to start working:
public static void isGuessCorrect(String guess, String wordInPlay, String[] hangmanScores) {
char[] letterGuessedAgainst = wordInPlay.toCharArray(); //Changed to Char Array
for (int i = 0; i < letterGuessedAgainst.length; i++) {
System.out.print(letterGuessedAgainst[i]);
}
System.out.println("Letter guessed against is: " + letterGuessedAgainst[1]);//testing purposes
System.out.println("My guess is: " + guess.charAt(0));//testing purposes
for (int i = 0; i < letterGuessedAgainst.length; i++) {
if (letterGuessedAgainst[i] == guess.charAt(0)) {//Made == since they are all Chars now
//System.out.println("Nice guess! Here are all the "+guess+"'s in the word.");
//System.out.println(hangmanScores);
System.out.println("they're equal");//want it to return this
}//end if
else {
System.out.println("they're not");//returns this instead
}
}//end for
}//end method
There is likely other places that can be improved but this fixes your direct problem.
Rather then splitting into a number of single character String(s), I suggest you use wordInPlay.toCharArray(); then you could iterate that char[] with a For-Each loop (and I believe you wanted to either search the entire String and say the character was found or not; not whether each individual character matches) and your code might look something like
public static void isGuessCorrect(String guess, String wordInPlay,
String[] hangmanScores) {
char[] letterGuessedAgainst = wordInPlay.toCharArray();
char ch = guess.charAt(0);
System.out.println("My guess is: " + ch);
boolean found = false;
for (char letter : letterGuessedAgainst) {
if (letter == ch) {
found = true;
break;
}
}
if (found) {
System.out.printf("%s contains guess %c%n", wordInPlay, ch);
} else {
System.out.printf("%s does not contain guess %c%n", wordInPlay, ch);
}
}
You're comparing a char (which charAt() returns) to a string, which they are not equal. I would suggest using either character arrays, or also using charAt() on letterGuessedAgainst.
Source:
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
if (guess.length==0) return null; // some kind of error handling
char quessedChar = guess.charAt(0);
for (int i = 0;i < letterGuessedAgainst.length; i++){
if (letterGuessedAgainst.charAt(i) == quessedChar ){
//System.out.println("Nice guess! Here are all the "+guess+"'s in the word.");
//System.out.println(hangmanScores);
System.out.println("they're equal");//want it to return this
}//end if
else
System.out.println("they're not");//returns this instead
}//end for
I would suggest at first place some code to validate your input data. You will fail if you will pass an empty string for guess.
Secondly you are comparing String with a character. Use above code.
Wouldn't you need to do
if (letterGuessedAgainst[i].charAt(0).equals(guess.charAt(0))){
instead of comparing an array to a char
Related
I'm a programming newbie and I am doing a coderbyte exercise that says "
Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a)"
i'm thinking of the following methods:
declare a string called "abcdefghijklmnopqrstuvxyz" and compare each string's char index position with the alphabet's index position, and then just bring the alphabet char that is located at the i+1 index location. But I don't know how it would work from z to a.
I've seen some techniques using ASCII values for every char but I've never done that before and not sure how it works
convert the given string into a char[] array, but then I'm not sure how I would tell the system to get me the next alphabet char
What would be the easiest way to do this?
EDIT
this is my code so far, but it doesn't work.
import java.util.*;
import java.io.*;
class Main {
public static String LetterChanges(String str) {
// code goes here
String alphabet = "abcdefghijklmnopqrstuvwxyz";
String newWord = "";
for (int i = 0; i < str.length(); i++){
for (int j = 0; j < alphabet.length(); i++){
if (str[i] == alphabet[i]){
if (alphabet[i+1].isVowel()){
newWord = newWord + toUpperCase(alphabet[i+1]);
}
else{
newWord = newWord + alphabet[i+1];
}
}
}
}
return str;
}
public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
System.out.print(LetterChanges(s.nextLine()));
}
}
Can't I ask for the index position of a Char that is a part of a String? in C I could do that.
Other than that not sure why it doesn't work.
I would definitely go with method 1.
I believe what you're looking for is the indexOf method on a String.
First of, I would create a method that given a character finds the next letter in the alphabet and return that. This could be done by finding the letter in your alphabet string and then fetch the letter at index+1. As you also pointed out you would need to take care of the edge case to turn 'z' into 'a', could by done with an if-statement or by having an extra letter 'a' at the end of your alphabet string.
Now all that remains to do is create a loop that runs over all characters in the message and calls the previously made method on that character and constuct a new string with the output.
Hope this helps you figure out a solution.
Assuming that there would be only lower case English letters in the given String the most performant way would be to add +1 to every character, and use either if-statement checking whethe the initial character was z or use the modulo operator % as #sp00m has pointed out in the comment.
Performing a search in the alphabetic string (option 1 in your list) is redundant, as well extracting array char[] from the given string (option 3).
Checking the edge case:
public static String shiftLetters(String str) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char next = str.charAt(i);
if (next == 'z') result.append('a'); // checking the edge case
else result.append((char) (next + 1));
}
return result.toString();
}
Applying modulo operator:
public static String shiftLetters(String str) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char next = (char) ((str.charAt(i) - 'a' + 1) % 26 + 'a');
result.append(next);
}
return result.toString();
}
main()
public static void main(String[] args) {
System.out.println(shiftLetters("abc"));
System.out.println(shiftLetters("wxyz"));
}
Output:
bcd // "abc"
xyza // "wxyz"
My problem is that I need to identify characters which differ between the two given strings in a visually striking way. Output the two input strings on two lines, and then identify the differences on the line below using periods (for identical characters) and asterisks (for differing characters). For example:
ATCCGCTTAGAGGGATT
GTCCGTTTAGAAGGTTT
*....*.....*..*..
I have tried to write two string with each other but I dont know how to make the program check for every character in the string and see if those match
This is what I have done so far :/
System.out.println("String 1: ");
String var1 = Scanner.nextLine();
System.out.println("String 2: ");
String var2 = Scanner.nextLine();
if (same (var1, var2))
System.out.println(".........");
else
System.out.println("********");
public static boolean same (String var1, String var2){
if (var1.equals(var2))
{
return true;
}
else
{
return false;
}
Can anyone help me with this?
You need to loop through your Strings and compare characters one by one. To run through your list you can make a for-loop. Use an int as counter and use the method length() to obtain your string size.
for(int i=0; i<string1.length(); i++ {
// do stuff
}
Then since you have a counter going through all position of your string, you can obtain the character at a specific position in this string using the method charAt()
char char1 = string1.charAt(i);
Then compare the character to check if they are the same. If they are print a dot . if they're not print an asterisk *
if(char1 == char2) {
System.out.print(".");
} else {
System.out.print("*");
}
In the above part I supposed your two string have the same size. If it's not the case, you can first determine which one is the smallest (and so which is the biggest) :
String smallestString;
String biggestString;
if(string1.size() > string2.sise()) {
smallestString = string2;
biggestString = string1;
else {
smallestString = string1;
biggestString = string2;
}
Then make your for loop go through the smallest String, otherwise you will face IndexOutOfBoundsException.
for(int i=0; i<smallestString.length(); i++ {
// do stuff
}
And the end of this for loop print asterisks for the characters that left in the biggest String
for(int j=smallestString.length(); j<biggestString.length(); j++) {
System.out.print("*");
}
This is what I've come up with.Mind you there are better ways to do this and I've just written it with as much effort as you put in your question.
public class AskBetterQuestion{
public static void main(String[] args) {
// TODO Auto-generated method stub
String w1="ATCCGCTTAGAGGGATT";
String w2="GTCCGTTTAGAAGGTTT";
char[] first = w1.toCharArray();
char[] second = w2.toCharArray();
int minLength = Math.min(first.length, second.length);
char[] out=new char[minLength];
for(int i = 0; i < minLength; i++)
{
if (first[i] != second[i])
{
out[i]='.';
}
else out[i]='*';
}
System.out.println(w1);
System.out.println(w2);
System.out.print(out);
}
}
I have a bug in this block of code. The debugger suggest it´s cause is this line of code char chr = getSecretWord.charAt(i);
What this code does is look for a match between userInput and secretWord. I have the for loop to go through the length of the secretWord letters one by one, and if there is a letter matching return true. If not, return false... but the program crashes when it is suppose to just return false... I guess it is something with this line, but do not know exactly what getSecretWord.charAt(i);
private boolean isMatchingSecretWord(String userInput)
{
String secretWord = "";
String getSecretWord = getSecretWord();
for (int i = 0; i <= getSecretWord.length();i++)
{
char chr = getSecretWord.charAt(i);
secretWord = ""+chr;
if (secretWord.equals(userInput))
{
println("is true");
return true;
}
}
return false;
}
As an side note, is what I´ve done with this code correct, assigning the getSecretWorld() Method to a String so I can use the Strings method length()?
String getSecretWord = getSecretWord();
for (int i = 0; i <= getSecretWord.length();i++)
Debug code:
Exception in thread "Thread-4" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(String.java:686)
at Hangman.isMatchingSecretWord(Hangman.java:49)
at Hangman.userInput(Hangman.java:34)
at Hangman.run(Hangman.java:20)*
for (int i = 0; i <= getSecretWord.length(); i++)
should be:
for (int i = 0; i < getSecretWord.length(); i++)
// ^^^
// see here
The valid indexes for an n-character string (or an n-element array) are 0 through n-1 inclusive.
So, if your secret word is xyyzy, the valid indexes are zero through four. Your original loop iterates with i set to zero through five, hence the problem.
But there seems to be a lot of unnecessary code in there, when you could get away with something simple.
First, I would remove a source of confusion - the function name sounds like the user input and the secret word have to match completely whereas your comment indicates otherwise:
Thanks, this works. But the reason for the loops is that the user enters one letter, I want to see if that letter is within the SecretWord. (it´s a hangman game).
In that case, you simply want to see if the single character exists in the secret word. I would change the function name to suit and, even then, it can be done with a lot less code:
private boolean isInSecretWord (String userInput) {
String secretWord = getSecretWord();
return secretWord.contains(userInput);
}
You were getting out of bounds error as your for loop wasn't looping correctly, I have modified it so that the loop doesn't go out of bounds and also your secretWord variable wasn't populating correctly, the code should now work as intended :)
private boolean isMatchingSecretWord(String userInput)
{
String secretWord = "";
String getSecretWord = getSecretWord();
for (int i = 0; i < getSecretWord.length();i++)
{
char chr = getSecretWord.charAt(i);
secretWord = secretWord + chr;
if (secretWord.equals(userInput))
{
println("is true");
return true;
}
}
return false;
}
I need to compare single char to char array and see if array has that char.
My current code looks like this:
public boolean isThereChar(char[] chaArray, String chr){
boolean bool = false;
for(int i=0; i < chaArray.length; i++)
{
if(chr.equals(chaArray[i])){
bool = true;
}
}
return bool;
}
Edit Notes:
Really sorry for being confusing! I am just a Java Beginner =/
Basically I am writing small Hangman game with GUI.
My program reads off text file and randomly chooses word which player has to guess, then prints it out in hidden manner like this: _ _ _ _ _
In this case I want player to input character or string (person can guess either whole word or just one letter)
Then I want my program to take that letter or string and compare to my hidden word
Following code chooses word and hides it:
public String pickWord(){
String guessWord = (wordsList[new Random().nextInt(wordsList.length)]);
return guessWord.toLowerCase();
}
//Hides picked word
public char[] setWord(){
char[] word = new char[pickWord().length() * 2];
for (int i = 0; i < word.length; i+=2) {
word[i] = '_';
word[i + 1] = ' ';
}
return word;
}
Then person input his character which he guesses to program with following code:
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if (action == "Guess Letter"){
inputChar = JOptionPane.showInputDialog("Please enter letter (a-z)");
if (inputChar.length() > 1){
GuessedLetters glr = new GuessedLetters(inputChar);
glr.setInString(inputChar);
//For testing purposes
System.out.println("This is String: " +glr.getInString());
}else{
GuessedLetters glr = new GuessedLetters(inputChar);
glr.setInChar(inputChar);
//For testing purposes
System.out.println("This is Char: " +glr.getInChar());
}
}
Lastly I want to take that character which was inputted and compare to my array of chars which is my hidden word:
public boolean isThereChar(char[] array, String str){
return isThereChar(array, str.charAt(0));
}
public boolean isThereChar(char[] array, char c){
for(int i=0; i<array.length; i++){
if (array[i] == c) return true;
}
return false;
}
I want to check what does my code returns (true or false), but I keep failing at doing so.
(Right now I am trying to call method in my main class to check it, if you can give me tips how to do it otherwise please let me know.)
I would use: Chars.contains(array, chr); with Guava Chars
The NullPointerException is happening because either chaArray or chr is null when you call the method. (And if not, then the NullPointerException is occurring somewhere else!!)
The other problem with your code is this line:
if (chr.equals(chaArray[i])) {
Since chr is actually a String, what is going to happen here is that the value of chaArray[i] will be auto-boxed as a Character object, and then passed as an argument to String.equals(Object). But the String.equals(Object) will return false unless its argument is a String ... so your code wouldn't find the character anyway.
You need to either compare the character like this:
if (chr.charAt(0) == chaArray[i]) {
or declare chr to be a char and compare it as:
if (chr == chaArray[i]) {
Let's see if I got what you need :
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if (action == "Guess Letter"){
inputChar = JOptionPane.showInputDialog("Please enter letter (a-z)");
if (inputChar.length() > 1){ //User input is a string here, right?
GuessedLetters glr = new GuessedLetters(inputChar);
glr.setInString(inputChar);
System.out.println(wordToGuess.contains(glr.getInString())); //This will print true if wordToGuess is equal to glr.getInString() or if it just contains it
//For testing purposes
System.out.println("This is String: " +glr.getInString());
}else{ //Here the user gave us just a character, so we've got to know if this character is contained in the word, right?
GuessedLetters glr = new GuessedLetters(inputChar);
glr.setInChar(inputChar);
System.out.println(wordToGuess.contains(glr.getInChar()); //This will print true if your char is in the wordToGuess string
//For testing purposes
System.out.println("This is Char: " +glr.getInChar());
}
}
}
Select the character from the parameter passed in, or pass in a char e.g.
chr[0]
or
public String isThereChar(char[] chaArray, char chr){
for(int i=0; i < chaArray.length; i++)
{
if(chr.equals(chaArray[i])){
return chr;
}
}
return "Guess Again";
}
String chr might be null causing NullPointerException.
Use char chr instead of String.
public boolean isThereChar(char[] chaArray, char chr){
boolean bool = false;
for(int i=0; i < chaArray.length; i++) {
if(chr==chaArray[i])){
bool = true;
}
}
return bool;
}
public boolean isThereChar(char[] chaArray, char chr){
for(int i=0; i < chaArray.length; i++)
{
if((chaArray[i]==chr)){
return true; // means Character exist in the Character array
}
}
return false; //// means Character does not exist in the Character array
}
I am working on this very simple method I know I am very close to finish it, but I am missing a detail. I appreciate any help. Thank you.
/**
Gets the first letter in this string.
#return the FIRST LETTER, or "" if there are no letters.
add1=AD3F add2=EF4G result=32SFB (BUT THESE ARE RANDOM ONLY INTS AND CHARS)
*/
public String firstLetter()
{
String line = add1+add2+result;
for(int i=0; i<line.length(); i++){
char ch=new Character(line.charAt(i));
if(Character.isLetter(ch)){
System.out.println("This is the first letter"+ch);
return ch;
}
else
System.out.println("No it is not a character: "+ch);
return "";
}
Your return type is String, but you're only trying to return a single character. Why not make it return a char, with \0 as the "no characters" return value - or possibly throwing an exception...
You also need to think about the ends of blocks - your if statement, your else clause, the loop, and the method itself. I would strongly recommend:
Using braces for all cases, even when there's only a single statement in the block (as per the else clause
Paying attention to indentation. It makes all the difference in clarity for this sort of thing.
You need to move the else code outside the loop so that it is only executed when you have tested all of the characters:
public class FirstLetter
{
public static void main(String[] args)
{
System.out.println(firstLetter());
}
public static String firstLetter()
{
String line = "AD3F" + "EF4G" + "32SFB";
for (int i = 0; i < line.length(); i++)
{
char ch = line.charAt(i);
if (Character.isLetter(ch))
{
System.out.println("This is the first letter: " + ch);
return Character.toString(ch);
}
}
System.out.println("No character found");
return "";
}
}
This kind of problem is more obvious when you format the code clearly.
I have kept the return type as String as per your original, but see also Jon Skeet's comments about changing that to char.
Your logic should look like this:
char ch;
for (int i = 0; i < line.length(); i++) {
ch = new Character(line.charAt(i));
if (Character.isLetter(ch)) {
System.out.println("This is the first letter" + ch);
return String.valueOf(ch);
}
}
System.out.println("No letters, sorry.")
return "";
As soon as a letter is found, it is reported and returned. But if the end of the end of the line is reached (i.e. the for loop completes), then obviously no letter was found, so report that and return an empty string.