I'm currently coding a program that takes in a string and a single character (if you decide to put a single one in that is) and (is supposed) to check how many times that character is in the string and at the end print out the amount of times it is in there. For some reason it isn't working and I would like some help; thank you!
import java.util.Scanner;
public class HowManyChars {
public HowManyChars() {
Scanner sc = new Scanner (System.in);
String askPhrase;
String askChar;
int charCounter = 0;
System.out.println("Enter a phrase");
askPhrase = sc.nextLine();
System.out.println("Enter a letter");
askChar = sc.nextLine();
for (int i = 0; i < askPhrase.length(); i++) {
if (askPhrase.substring(i, i + 1) == askChar) {
charCounter = charCounter + 1;
}
}
System.out.println("There are " + charCounter + " " + askChar + " in " + askPhrase);
}
}
I give credit for this answer to #Mushif, who correctly figured out the problem. Your current comparison logic is comparing a string against a character:
for (int i=0; i < askPhrase.length(); i++) {
// String char
if (askPhrase.substring(i, i + 1) == askChar) {
charCounter = charCounter + 1;
}
}
Try iterating the character set of the input word and then compare apples to apples:
for (int i=0; i < askPhrase.length(); i++) {
if (askPhrase.charAt(i) == askChar) {
charCounter = charCounter + 1;
}
}
You could also use an enhanced loop directly on the input's character set:
for (char chr : askPhrase.toCharArray()) {
if (chr == askChar) {
charCounter = charCounter + 1;
}
}
import java.util.Scanner;
public class HowManyChars {
public HowManyChars() {
Scanner sc = new Scanner (System.in);
String askPhrase;
char askChar;
char[] askChars;
int charCounter = 0;
System.out.println("Enter a phrase");
askPhrase = sc.nextLine();
askChars = askPhrase.toCharArray();
System.out.println("Enter a letter");
askChar = sc.next().charAt(0);
sc.close();
for (int i = 0; i < askChars.length; i++) {
if (Character.toLowerCase(askChar) == Character.toLowerCase(askChars[i])) {
charCounter ++;
}
}
System.out.println("There are " + charCounter + " " + askChar + " in " + askPhrase);
}
}
I have this hangman program but have an issue with asking the user if they want to play again, it always just ends the program. How can i fix this issue. Thanks for future reply's.
package hangman. I hope editing is okay with this
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Hangman {
static Scanner keyboard = new Scanner(System.in);
static int size, size2;
static boolean play = false;
static String word;
static String[] ARRAY = new String[0];
static String ANSI_RESET = "\u001B[0m";
static String ANSI_BLUE = "\u001B[34m";
static String ANSI_GREEN = "\u001B[32m";
static String ANSI_RED = "\u001B[31m";
static String ANSI_LIGHTBLUE = "\u001B[36m";
//^declarations for variables and colors for display^
public static void main(String[] args) {
randomWordPicking();
//^calls method^
}
public static void setUpGame() {
System.err.printf("Welcome to hangman.\n");
try {
Scanner scFile = new Scanner(new File("H:\\HangMan\\src\\hangman\\HangMan.txt"));
String line;
while (scFile.hasNext()) {
line = scFile.nextLine();
Scanner scLine = new Scanner(line);
size++;
}
ARRAY = new String[size];
Scanner scFile1 = new Scanner(new File("H:\\HangMan\\src\\hangman\\HangMan.txt"));
while (scFile1.hasNext()) {
String getWord;
line = scFile1.nextLine();
Scanner scLine = new Scanner(line);
word = scLine.next();
ARRAY[size2] = word;
size2++;
//calls method for picking word^
}
} catch (FileNotFoundException e) {
System.out.println(e);
}
}
public static void randomWordPicking() {
setUpGame();
int LEFT = 6;
do {
int random = (int) (Math.random() * ARRAY.length);
//^genertates a random number^
String randomWord = ARRAY[random];
String word = randomWord;
//^chosses a random word and asgins it to a variable^
char[] ranWord = randomWord.toCharArray();
char[] dash = word.toCharArray();
//^Creates a char array for the random word chosen and for the dashs which are displayed^
for (int i = 0; i < dash.length; i++) {
dash[i] = '-';
System.out.print(dash[i]);
//^displays dashs to the user^
}
for (int A = 1; A <= dash.length;) {
System.out.print(ANSI_BLUE + "\nGuess a Letter: " + ANSI_RESET);
String userletters = keyboard.next();
//^gets user input^
if (!userletters.equalsIgnoreCase(randomWord)) {
//^allows program to enter loop if user has entered a letter^
for (int i = 0; i < userletters.length(); i++) {
char userLetter = userletters.charAt(i);
String T = Character.toString(userLetter);
for (int B = 0; B < ranWord.length; B++) {
//^converts users input to a char and to a string^
if (userLetter == dash[B]) {
System.err.println("This " + userLetter + "' letter already exist");
B++;
//^tells user if the letter they entered already exists^
if (userLetter == dash[B - 1]) {
break;
}
} else if (userLetter == ranWord[B]) {
dash[B] = userLetter;
A--;
}
}
if (!(new String(ranWord).contains(T))) {
LEFT--;
System.out.println("You did not guess a correct letter, you have " + LEFT + " OF "
+ dash.length + " trys left to guess correctly");
}
//^shows how many trys the user has left to get the word right before game ends^
System.out.println(dash);
if (LEFT == 0) {
System.out.println("The word you had to guess was " + word);
break;
}
//^shows the user the word if they didnt guess correctly^
}
} else {
System.out.println(ANSI_GREEN + "\nYou have guessed the word correctly!" + ANSI_RESET);
break;
}
if (LEFT == 0) {
break;
}
if ((new String(word)).equals(new String(dash))) {
System.out.println(ANSI_GREEN + "\nYou have guessed the word correctly!" + ANSI_RESET);
break;
}
}
//^if user enters the word it will check and then display that they got the word correct^
System.out.println("Play agian? (y/n)");
String name = keyboard.next();
//^asks user if they want to play again^
if (name.equalsIgnoreCase("n")) {
play = true;
return;
}
//^stops program if user enters n to stop game^
} while (play = false);
}
}
If you want to compare two variables, do not use = operator, which means assignment. Use == instead. Additionally, in your case it should be !=:
while (play != false)
You should use
while (!play)
instead of
while (play = false)
When the code runs and you ask for char and type a letter lets say 'e' the output makes it "eeeee" instead of filling in the e's in the partial word method. I'm not sure how to fix it. I think the problem is either in replaceChar method or the updatePartialWord method. Would love some help. Thanks!
P.S i need to keep the method inputs the same even if there is an easier way!
// creates partialWord using string length then creating a new string with the same amount of dashes
public static String createPartialWord(String secretWord)
{
String newsecretWord = "";
int wordLength = secretWord.length();
while (wordLength > 0)
{
newsecretWord = newsecretWord + "-";
//System.out.print("-");
wordLength--;
}
System.out.println();
return newsecretWord;
}
//replaces character at certain ints
public static String replaceChar(String word, char c, int i)
{
//return word.replace(word.charAt(i), c);
String newText = word.replace(word.charAt(i), c);
return newText;
}
public static String updatePartialWord(String partial, String secret, char c)
{
if(c==secret.charAt(0))
{
return replaceChar(partial, c, 0);
}
if(c==secret.charAt(1))
{
return replaceChar(partial, c, 1);
}
if(c==secret.charAt(2))
{
return replaceChar(partial, c, 2);
}
if(c==secret.charAt(3))
{
return replaceChar(partial, c, 3);
}
if(c==secret.charAt(4))
{
return replaceChar(partial, c, 4);
}
return partial;
}
//Prints hangman
public static void printHangman(int guessLeft)
{
String HEAD = " ";
String BODY = " ";
String LEGS = " ";
String LEFTARM = " ";
String RIGHTARM = " ";
System.out.println("_____");
System.out.println("| |");
if (guessLeft < 6) {
HEAD = "()";
}
System.out.println("| " + HEAD);
if (guessLeft < 5) {
BODY = "||";
}
if (guessLeft < 4) {
LEFTARM = "\\";
}
if (guessLeft < 3) {
RIGHTARM = "/";
}
System.out.println("| " + LEFTARM + BODY + RIGHTARM);
if (guessLeft < 2) {
LEGS = "/";
}
if (guessLeft < 1) {
LEGS += "\\";
}
System.out.println("| " + LEGS);
System.out.println("|_____\n\n\n\n");
}
public static String generateSecretWord()
{
String[] names = { "alone", "apple", "anode", "abuse", "angle", "amaze","adobe","amuse",
"avoid","peter","sound","doubt","upper","lower","layer","enter","alter","boxer",
"faced", "alive","adore","names","voice","water","plate","pepsi","pizza","paste",
"hello","sugar","money","paper","while","times", "mouth","other","agile","again",
"acute","arise","argue","ankle","badge","blaze","bride","chase","sense","craze",
"dance","false","exile","drove"};
String name = names[(int) (Math.random() * names.length)];
return name;
}
public static void main(String[] args)
{
Scanner stdin = new Scanner(System.in);
String secretWord = generateSecretWord();
String partialWord = createPartialWord(secretWord);
System.out.println(" Welcome to HangMan");
System.out.println("I picked a secret word");
System.out.println();
//start for statement for main game
System.out.println("The current Partial Word is: " + partialWord);
for(int i = 6;i>0;)
{
System.out.println("The current Hangman picture is");
printHangman(i);
System.out.println("Player 2, you have " + i + " remaining guesses");
System.out.println("Would you like to guess the secret work or guess a character?");
System.out.println("Type \"word\" for word, type \"char\" for character");
String playerInput = stdin.nextLine();
String charInput = "char";
String wordInput = "word";
if(playerInput.equals(charInput))
{
System.out.println("Please type a character");
char input = stdin.nextLine().charAt(0);
if(secretWord.charAt(0)== input || secretWord.charAt(1)== input || secretWord.charAt(2)== input ||
secretWord.charAt(3)== input || secretWord.charAt(4)== input)
{
System.out.println("That character is in the secret word");
System.out.println("The current partial word is: " + updatePartialWord(partialWord, secretWord, input));
}
else
{
System.out.println("Sorry that charcater is not in the secret word");
System.out.println("The current partial word is: " + updatePartialWord(partialWord, secretWord, input));
if(i==1)
{
System.out.println("You've killed the hangman. You've lost the game");
printHangman(0);
break;
}
i--;
}
}
else
{
System.out.println("Please guess the word");
String userGuess = stdin.nextLine();
if(userGuess.equals(secretWord))
{
System.out.print("Congrats that is the secret word! You've won the game!");
System.out.println("Here is the hangman");
printHangman(i);
break;
}
else
{
System.out.println("Sorry thats not the secret word. You've lost.");
break;
}
}
}
}
}
public static String replaceChar(String word, char c, int i) {
String newText = word.replace(word.charAt(i), c);
:
The word in this case is -----, so you are replacing all occurrences of the character at position i (which is -) with the letter.
So all - characters are becoming the character you just entered.
You should instead be changing each character in the partial word, if and only if the equivalent character in your secret word matches the character just entered, something like:
public static String replaceChar(String word, String secret, char c) {
for (int i = 0; i < word.length(); i++) {
if (secret.charAt(i) == c) {
word = word.substring(0, i) + c + word.substring(i+1);
}
}
return word;
}
Of course, since you're now using the secret word and the position of the character is irrelevant, you change what gets passed in. The calling code can be modified to be:
if (c == secret.charAt(0))
return replaceChar(partial, secret, c);
if (c == secret.charAt(1))
return replaceChar(partial, secret, c);
// :
// and so on.
Of course, even with that fix, you still have a problem:
System.out.println("The current partial word is: " + updatePartialWord(partialWord, secretWord, input));
This outputs the new partial word as calculated by the function but it doesn't actually change the partial word. You need something along the lines of:
partialWord = updatePartialWord(partialWord, secretWord, input));
System.out.println("The current partial word is: " + partialWord);
As per the javadocs
Returns a new string resulting from replacing all occurrences of
oldChar in this string with newChar.
I have a program for a hangman game and the indexof is not working for me? its on line 30. I have been trying to figure it out but I cannot.if (guessedWord.indexOf(letter) >= 0). I will keep trying to find out what I did wrong
import java.io.PrintStream;
import java.util.Scanner;
public class Hangman
{
public static void main(String[] args)
{
String[] words = { "write", "program", "that", "receive", "positive" };
Scanner input = new Scanner(System.in);
char anotherGame;
do
{
int index = (int)(Math.random() * words.length);
String hiddenWord = words[index];
StringBuilder guessedWord = new StringBuilder();
for (int i = 0; i < hiddenWord.length(); i++) {
guessedWord.append('*');
}
int numberOfCorrectLettersGuessed = 0; int numberOfMisses = 0;
while (numberOfCorrectLettersGuessed < hiddenWord.length()) {
System.out.print("(Guess) Enter a letter in word " + guessedWord +
" > ");
String s = input.nextLine();
char letter = s.charAt(0);
if (guessedWord.indexOf(letter) >= 0) {
System.out.println("\t" + letter + " is already in the word");
} else if (hiddenWord.indexOf(letter) < 0) {
System.out.println("\t" + letter + " is not in the word");
numberOfMisses++;
} else {
int k = hiddenWord.indexOf(letter);
while (k >= 0) {
guessedWord.setCharAt(k, letter);
numberOfCorrectLettersGuessed++;
k = hiddenWord.indexOf(letter, k + 1);
}
}
}
System.out.println("The word is " + hiddenWord + ". You missed " + numberOfMisses + (numberOfMisses <= 1 ? " time" : " times"));
System.out.print("Do you want to guess for another word? Enter y or n> ");
anotherGame = input.nextLine().charAt(0);
}while (anotherGame == 'y');
}
}
You are passing in a char where String is expected. Try using String.valueOf(letter) like this:
if (guessedWord.indexOf(String.valueOf(letter)) >= 0) {
// Your code
}
StringBuilder#indexOf(char) is undefined. You could do
if (guessedWord.indexOf(Character.toString(letter)) >= 0) {
there's no indexOf(char) method for a StringBuilder.
guessedWord.indexOf(letter)
should be
if (guessedWord.toString().indexOf(letter) >= 0) {
I am trying to create a Palindrome tester in java using a method.. This is what I have so far. It is so close I just can't figure out why it won't say that it IS a palindrome and reverse it.
System.out.println("Fun with Palindromes!!");
Scanner in = new Scanner(System.in);
System.out.println("Enter the potential palindrome (or enter exit to quit): ");
String x = in.nextLine();
while(!x.equals("exit"))
{
String t = x.toLowerCase();
String u = CleanUpString(t);
Boolean wordCheck = checkPalindrome(u);
int wordCount = x.length();
String rev = "";
for(int i = 0; i <x.length(); i++)
{
rev = x.charAt(i)+rev;
}
if(wordCheck == true)
{
System.out.println("The orginal string\"" + u + "\" contains" + wordCount + "characters." );
System.out.println("The converted string\"" + rev + "\"is a palindrome");
}
else if(wordCheck == false)
{
System.out.println("The string \"" + u + "\" contains " + wordCount + " characters");
System.out.println("\"" + rev + "\" is not a palindrome");
}
System.out.println("\nEnter the potential palindrome, or enter exit to quit: ");
x = in.nextLine();
}
}
public static String CleanUpString(String words)
{
words = words.replace(".","");
words = words.replace("," ,"");
words = words.replace(":","");
words = words.replace("!","");
return words;
}
public static boolean checkPalindrome(String baseball)
{
String rev = "";
for(int i = 0; i<baseball.length()-1; i++)
{
rev = baseball.charAt(i) + rev;
}
if(rev.equals(baseball))
return true;
else
return false;
}
}
Here is the code I used to determine whether a string is Palindrome String or not:
private static boolean checkPalindrome(String str){
if (str == null)
return false;
int len = str.length();
for (int i=0;i<len/2 ; i++){
if (str.charAt(i) != str.charAt(len - i - 1)){
return false;
}
}
return true;
}
For reversing strings, you can simply use:
String reverse = new StringBuffer(string).reverse().toString();
Hope these can help you.
Use StringUtils for this
import org.apache.commons.lang.StringUtils;
boolean isPalindrome(String word) {
return StringUtils.reverse(word).equals(word);
}
Here is another option
public class PalindromeTester {
public static void main(String[] args) {
try {
String s = args[0];
int i = args[0].length()-1;
int i2 = args[0].length();
char [] chrs = new char[i2];
for ( int i3 = i; i3 > -1; i3-- ) {
chrs[i2-i3-1] = (s.charAt(i3) );
}
String s2 = String.valueOf(chrs);
if ( s2.equals(s) ) {
System.out.println( s + " is a palindrome!");
} else {
System.out.println( s + " is not a palindrome");
}
} catch ( ArrayIndexOutOfBoundsException e ) {
System.out.println("Please enter at least one letter or digit!");
}
}
}
Here's how I did it:
public class palindromeTWO
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int right = 0;
int left = 1;
System.out.println("Please enter a word: ");
String word = scan.next();
int word_length = word.length();
while(word.charAt(right) == word.charAt(word_length - left) && left < (word_length / 2))
{
left++;
right++;
}
if(word.charAt(right) == word.charAt(word_length - left))
{
System.out.println("'" + word + "'" + " is a palindrome!");
}
else
{
System.out.println("'" + word + "'" + " is NOT a palindrome.");
}
}
}
1st implementation using recursion -
import java.util.ArrayList;
import java.util.stream.Collectors;
public class PalindromeManager {
private static String str = "ehcache";
private static ArrayList<String> list = new ArrayList<>();
public static void main(String[] args) {
test(str);
String output = list.stream().collect(Collectors.joining());
System.out.println(output);
if (output.equals(str)) {
System.out.println("it was palindrome");
} else {
System.out.println("Nope! it wasn't");
}
}
private static void test(String str) {
if (str.length() <= 0) {
return;
}
String lastChar = "" + str.charAt(str.length() - 1);
list.add(lastChar);
test(str.substring(0, str.length() - 1));
}
}
2nd implementation using iteration -
public class PalindromeManager2 {
private static String str = "ehcache";
public static void main(String[] args) {
int startIndex = 0;
int lastIndex = str.length() - 1;
boolean result = true;
while (true) {
if (startIndex >= lastIndex) {
break;
}
char first = str.charAt(startIndex);
char last = str.charAt(lastIndex);
/*if (first == ' ') {
startIndex++;
continue;
}
if (last == ' ') {
lastIndex--;
continue;
}*/
if (first != last) {
result = false;
break;
}
startIndex++;
lastIndex--;
}
if (result) {
System.out.println("Yes! It was");
} else {
System.out.println("Nope! it wasn't");
}
}
}
In checkPalindrome method change the condition of for loop from i<baseball.length()-1 to i<baseball.length().