Java Compare single char to char array - java

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
}

Related

The user must enter a string that contains at least one lowercase “a”

The user must do the question above or the question keeps repeating so I need a while loop. I need to do this using a subroutine too. My code below isn't working.
public static boolean isAlpha(String name) {
char[] chars = name.toCharArray();
for (char c : chars) {
if (!Character.isLetter(c)) {
return false;
}
else {
for (int i = 0; i < name.length(); i++) {
if (name.charAt(i) >= 'a') {
return false;
}
else {
return false;
}
}
}
}
return false;
}
This is the second part:
System. out.print ("Please enter a string that contains at least one lowercase a. ");
String name = input.next ();
if (isAlpha(name)) {
System.out.println("That is a valid string onto stage 2.");
}
else {
System.out.println("That is an invalid string. Try again.");
}
You're passing a String to the isAlpha method, which iterates over the String and checks each letter to be 'a' or not. You're returning false for every char that isn't 'a', and returning false if you iterate through the entire String.
An easier way to handle this would be to return true upon finding the first 'a', or returning false after iterating over the entire String. It will make scaling easier as well if you reduce the number of return statements in a single method.
Here are three different ways to check whether a string contains at least one lowercase a. The first way uses a for loop as you have tried to do in the code in your question.
The second way uses regular expressions and the last way uses streams.
The code also contains a main method which contains a while loop as requested in your question.
do the question above or the question keeps repeating
import java.util.Scanner;
public class Solution {
public static boolean isAlpha(String name) {
/* Using a loop. */
char[] chars = name.toCharArray();
for (char ch : chars) {
if (ch == 'a') {
return true;
}
}
return false;
/* Using regular expression. */
// return name.matches("^.*a.*$");
/* Using stream API. */
// return name.chars()
// .filter(c -> c == 'a')
// .findFirst()
// .isPresent();
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter a string that contains at least one lowercase 'a': ");
String str = input.nextLine();
while (!isAlpha(str)) {
System.out.println("That is an invalid string. Try again.");
str = input.nextLine();
}
System.out.println("That is a valid string. On to stage 2.");
}
}
Here is a sample run:
Please enter a string that contains at least one lowercase 'a': 1 is the lonliest number.
That is an invalid string. Try again.
2 can be as bad as 1
That is a valid string. On to stage 2.
A couple of mistakes were made. Firstly, your method only returns false, there is no way in which it could be true. Secondly, your code here loops through the entire array for every single character.
public static Boolean isAlpha(String name) {
char[] chars = name.toCharArray();
for (char c : chars) {
if (!Character.isLetter(c)) {
return false;
}
else {
for (int i = 0; i < name.length(); i++) {
if (name.charAt(i) >= 'a') {
return false;
}
else {
return false;
}
}
}
}
return false;
}
Try this instead.
public static Boolean isAlpha(String name) {
char[] chars = name.toCharArray();
for(char c : chars) {
if(c=='a') {
return true;
}
}
return false;
}

a program which identifies the differences between pairs of strings

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);
}
}

Comparing a string array index to a string

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

Java Hangman code, char array

If any of you can point out the issue in this code, i'll be glad :)
This is just the method im having issue with..
public static char[] checkMethod(char[] checkArray, char letter)
{
boolean flag = false;
for(int i=0; i<checkArray.length; i++)
{
if(checkArray[i] == letter)
{
checkArray[i] = letter;
flag = true;
}
}
if(flag == true)
System.out.println("Good job!");
else
System.out.println("Aww.. Try again");
return checkArray;
}
Currently the checkArray contains " - - - - -" for the length of the word. This method is supposed to replace the _ with the letter, if entered correctly. 'letter' is the input given from keyboard.
Right now i'm not getting the expected output, instead i'm getting blanks. It seems the checkArray[i] = letter part doesn't work. How do i make it work ?
Any help will be much appreciated
(i hope i have worded the question correctly.. )
If I understand correctly, you need an additional argument (holding the word) to your function.
Say String word
if(word.charAt(i) == letter)
{
checkArray[i] = letter;
flag = true;
}
You should have 2 arrays: 1 with the blanks to fill in, and one with the actual word being checked against. Currently you are checking against the blank array, which will never == the letter.
You are comparing checkArray[i] == letter and if true replacing checkArray[i] by letter, but they are already equal. You need to pass the word that you are checking.
public static char[] checkMethod(char[] checkArray, char[] wordArray, char letter)
{
boolean flag = false;
for(int i=0; i<checkArray.length; i++)
{
if(wordArray[i] == letter)
{
checkArray[i] = letter;
flag = true;
}
}
if(flag == true)
System.out.println("Good job!");
else
System.out.println("Aww.. Try again");
return checkArray;
}

Get the first instance of a letter from the string

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.

Categories

Resources