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;
}
Related
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;
}
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
I wrote this program for school and it almost works, but there is one problem. The goal of the program is to take an inputted string and create a new string out of each word in the input beginning with a vowel.
Example:
input: It is a hot and humid day.
output: Itisaand.
Here is the driver:
public class Driver {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Input: ");
String input = console.nextLine();
Class strings = new Class(input);
int beg=0;
for(int j=0;j<input.length();j++)
{
if(strings.isVowel(j)&&(j==0||input.charAt(j-1)==' '))
beg=j;
else if(strings.endWord(j)&&(beg==0||input.charAt(beg-1)==' '))
{
strings.findWord(beg, j);
}
}
System.out.print("Output: ");
strings.printAnswer();
}
}
And here is the class:
public class Class {
String input="",answer="";
public Class(String input1)
{
input = input1;
}
public boolean isVowel(int loc)
{
return (input.charAt(loc)=='U'||input.charAt(loc)=='O'||input.charAt(loc)=='I'||input.charAt(loc)=='E'||input.charAt(loc)=='A'||input.charAt(loc)=='a'||input.charAt(loc)=='e'||input.charAt(loc)=='i'||input.charAt(loc)=='o'||input.charAt(loc)=='u');
}
public boolean endWord(int loc)
{
return (input.charAt(loc)==' '||input.charAt(loc)=='.'||input.charAt(loc)=='?'||input.charAt(loc)=='!');
}
public void findWord(int beg,int end)
{
answer = answer+(input.substring(beg,end));
}
public void printAnswer()
{
System.out.println(answer+".");
}
}
With this code, i get the output:
Itisaa hotandand humidand humid summerand humid summer day.
By removing this piece of code:
&& (j == 0 || input.charAt(j-1) == ' ')
I get the proper output, but it doesn't work if an inputted word has more than one vowel in it.
For example:
input: Apples and bananas.
output: and.
Can someone please explain:
a) why the code is printing out words beginning with consonants as it is and
b) how I could fix it.
Also, the methods in the class I've written can't be changed.
Here's a better algorithm:
split the input into an array of words
iterate over each word
if the word begins with a vowel, append it to the output
The easiest way to split the input would be to use String.split().
Here's a simple implementation:
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
String input = console.nextLine();
String[] words = input.split(" ");
StringBuilder output = new StringBuilder();
for (String s : words) {
if (startsWithVowel(s)) {
output.append(s);
}
else {
output.append(getPunc(s));
}
}
System.out.println(output.toString());
}
public static boolean startsWithVowel(String s) {
char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
char firstChar = s.toLowerCase().charAt(0);
for (char v : vowels) {
if (v == firstChar) {
return true;
}
}
return false;
}
public static String getPunc(String s) {
if (s.matches(".*[.,:;!?]$")) {
int len = s.length();
return s.substring(len - 1, len);
}
return "";
}
The problem with your code was:
It was counting the same word multiple times, due to it finding vowels and starting the word search process over again.
Heres how I went about solving the problem, while still keeping your code looking relatively the same: All I changed was your loop
for(int i=0;i<input.length();i++)
{
if(strings.isVowel(i) &&(i==0 || strings.endWord(i-1))){
beg = i;
for(int j = i; j < input.length();j++) //look for end of word
{
if(strings.endWord(j)) //word has ended
{
i = j; //start from end of last word
strings.findWord(beg, j);
break; //word done, end word search
}
}
}
}
As mentioned above, there are better ways to go about this, and there are some pretty glaring flaws in the setup, but you wanted an answer, so here you go
Normally i would suggest you where to fix your code, but it's seems there is a lot of bad code practice in here.
Mass Concatenation should be apply be StringBuilder.
Never call a class Class
Conditions are too long and can be shorten by a static string of Vowels and apply .contains(Your-Char)
Spaces, Indentations required for readability purposes.
A different way of attacking this problem, may probably accelerate your efficiency.
Another approch will be Split the code by spaces and loop through the resulted array for starting vowels letters and then Append them to the result string.
A better readable and more maintainable version doing what you want:
public static String buildWeirdSentence(String input) {
Pattern vowels = Pattern.compile("A|E|I|O|U|a|e|i|o|u");
Pattern signs = Pattern.compile("!|\\.|,|:|;|\\?");
StringBuilder builder = new StringBuilder();
for (String word : input.split(" ")) {
String firstCharacter = word.substring(0, 1);
Matcher vowelMatcher = vowels.matcher(firstCharacter);
if (vowelMatcher.matches()) {
builder.append(word);
} else {
// we still might want the last character because it might be a sign
int wordLength = word.length();
String lastCharacter = word.substring(wordLength - 1, wordLength);
Matcher signMatcher = signs.matcher(lastCharacter);
if (signMatcher.matches()) {
builder.append(lastCharacter);
}
}
}
return builder.toString();
}
In use:
public static void main(String[] args) {
System.out.println(buildWeirdSentence("It is a hot and humid day.")); // Itisaand.
}
I think best approach is to split input and then check each word if it starts with vowel.
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
System.out.print("Input: ");
String str = console.next();
String[] input = str.split(" ");
StringBuilder s = new StringBuilder();
String test;
for (int i = 0; i < input.length; i++)
{
test = input[i];
if (test.charAt(0) == 'U' || test.charAt(0) == 'O'
|| test.charAt(0) == 'I' || test.charAt(0) == 'E'
|| test.charAt(0) == 'A' || test.charAt(0) == 'a'
|| test.charAt(0) == 'e' || test.charAt(0) == 'i'
|| test.charAt(0) == 'o' || test.charAt(0) == 'u')
{
s.append(input[i]);
}
}
System.out.println(s);
}
The problem with your code is that you override the first beg when a word has more that vowel. for example with Apples beg goes to 0 and before you could call findWord to catch it, it gets overridden with 4 which is the index of e. And this is what screws up your algorithm.
You need to note that you have already found a vowel until you have called finWord, for that you can add a boolean variable haveFirstVowel and set it the first time you have found one to true and only enter the branch for setting that variable to true if you haven't already set it. After you have called findWord set it back to false.
Next you need to detect the start of a word, otherwise for example the o of hot could wrongly signal a first vowel.
Class strings = new Class(input);
int beg = 0;
boolean haveFirstVowel = false;
for (int j = 0; j < input.length(); j++) {
boolean startOfWord = (beg == 0 || input.charAt(j - 1) == ' ');
if (startOfWord && ! haveFirstVowel && strings.isVowel(j)) {
beg = j;
haveFirstVowel = true;
}
else if (strings.endWord(j) && haveFirstVowel) {
strings.findWord(beg, j);
haveFirstVowel = false;
}
}
System.out.print("Output: ");
strings.printAnswer();
I think overall the algorithm is not bad. It's just that the implementation can definitely be better.
Regarding to the problem, you only need to call findWord() when:
You have found a vowel, and
You have reached the end of a word.
Your code forgot the rule (1), therefore the main() can be modified as followed:
Scanner console = new Scanner(System.in);
System.out.print("Input: ");
String input = console.nextLine();
Class strings = new Class(input);
int beg = 0;
boolean foundVowel = false; // added a flag indicating whether a vowel has been found or not
for (int j = 0; j < input.length(); j++) {
if (strings.isVowel(j) && (j == 0 || input.charAt(j - 1) == ' ')) {
beg = j;
foundVowel = true;
} else if (strings.endWord(j) && (beg == 0 || input.charAt(beg - 1) == ' ')) {
if (foundVowel) { // only call findWord() when you have found a vowel and reached the end of a word
strings.findWord(beg, j);
foundVowel = false; // remember to reset the flag
}
}
}
System.out.print("Output: ");
strings.printAnswer();
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.