Hangman Code Issue (Java) - java

I am trying to create a simple hangman program in java for a school assignment and I have it working for the most part. The main problem I have with it is that it keeps printing out the hidden word twice. It also only goes through and asks the user to enter an word 8 times when it should be 15 times. Can someone tell me where I went wrong?
// Its in a separate method.
public static void application1() throws Exception {
// Tells the user about the game.
System.out.println("Welcome to Hangman!");
System.out.println("Please try to guess the word within 15 letters.");
String option = "";
// Creates a array of all the phrases.
String answer[] = new String[20];
answer[0] = "computer";
answer[1] = "radio";
answer[2] = "calculator";
answer[3] = "teacher";
answer[4] = "bureau";
answer[5] = "police";
answer[6] = "geometry";
answer[7] = "president";
answer[8] = "subject";
answer[9] = "country";
answer[10] = "environment";
answer[11] = "classroom";
answer[12] = "animals";
answer[13] = "province";
answer[14] = "month";
answer[15] = "politics";
answer[16] = "puzzle";
answer[17] = "instrument";
answer[18] = "kitchen";
answer[19] = "language";
do {
// Creates a random number to choose which word to choose from.
int rand = (int)(Math.random() * 20 + 0);
StringBuffer word = new StringBuffer("");
// This makes the unknown word as long as the actual word.
for (int i = 0; i < answer[rand].length(); i++) {
word.append("_");
}
System.out.println(word);
char input = ' ';
// This is where it checks the input and replaces the letters.
for (int i = 0; i < 15; i++) {
input = (char) System.in.read();
for (int j = 0; j < answer[rand].length(); j++) {
if (input == answer[rand].charAt(j)) {
word.setCharAt(j, input);
}
}
// This is where the hidden word get printed twice.
System.out.println(word);
}
// Asks the user if they want to restart the application.
System.out.println("Would you like to try again? (Y/N)");
option = input();
} while (option.equalsIgnoreCase("y"));
}

Use a Scanner to get your input.
Scanner in = new Scanner(System.in);
String line = in.nextLine();
char input = line.charAt(0);
I think System.in.read(); is returning the entered character and the enter key. (the \n char).
That makes your cycle run twice for each input, printing two times and looking like it only accepts 8 chars.

if (word.equals(answer[rand])) {
System.out.println("Congratulations! You guessed the word!");
// Asks the user if they want to restart the application.
System.out.println("Would you like to try again? (Y/N)");
option = input();
}
else if (i == 14) {
System.out.println("Sorry, you did not guess the word.");
// Asks the user if they want to restart the application.
System.out.println("Would you like to try again? (Y/N)");
option = input();
// Returns to the main menu.
menu();
}
This doesn't recognize the word is correct.

Related

How do i make the loop stop repeating in java

I'm a beginner in Java and I have to write a program that allows the user to enter in words, then the program returns the word backwards until the user writes "stop". Every time the user enters a word, java outputs it backwards plus the previous word which is outputted and I don't want that.
For example, if I put input pots
it outputs, stop
if I print cat
it outputs potstac
How can I just get java to just output the words backwards without adding it on to the prior words
For example, i want to input in pots
it should output, stop
i want to print cat
it should output, tac
import java.util.*;
public class javapdf2413 {
public static void main (String [] args) {
Scanner in = new Scanner (System.in);
String wordEntered = "";
String backWords = "";
do {
System.out.println("Enter in a word");
wordEntered = in.next();
for (int i = wordEntered.length()-1; i>=0; i--) {
backWords = backWords + wordEntered.charAt(i);
}
System.out.println(backWords);
}while(!wordEntered.equals("stop"));
}
}
You'll need to set backWords back to an empty string at the beginning of the do loop. If you don't it will just concatenate onto the end of the previous string - which is what you said is happening. Setting it back to "" at the beginning of the loop body will essentially "reset" it for the next word.
Like this:
do {
backWords = "";
System.out.println("Enter in a word");
wordEntered = in.next();
for (int i = wordEntered.length()-1; i>=0; i--) {
backWords = backWords + wordEntered.charAt(i);
}
System.out.println(backWords);
}while(!wordEntered.equals("stop"));
Try to do this with while loop
import java.util.Scanner;
public class TestRun {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String wordEntered = "";
String backWords = "";
while (true) {
System.out.println("Enter in a word");
wordEntered = in.next();
if (wordEntered.equals("stop")) {
break;
} else {
for (int i = wordEntered.length() - 1; i >= 0; i--) {
backWords = backWords + wordEntered.charAt(i);
}
System.out.println(backWords);
backWords = "" ;
}
}
}
}
Just initialize your variables inside your do loop
String wordEntered;
String backWords;
do {
wordEntered = "";
backWords = "";
System.out.println("Enter in a word");
wordEntered = in.next();
for (int i = wordEntered.length()-1; i>=0; i--) {
backWords = backWords + wordEntered.charAt(i);
}
System.out.println(backWords);
}while(!wordEntered.equals("stop"));
Just beware - Strings are immutable objects. Use it with right use case and approach. Try to use StringBuilder for non concurrent code as much as possible where ever you can.

Java compare user input to char array

First off hello, new here. I'm fairly new to Java and I'm having some issues with comparing user input using the Scanner class to a dynamically created char array. I have a list of 10 words, program randomly choosing one, then converting that to a char array. I've got all that working. I'm having an issue comparing the user input to a char in the array. I'm basically practicing String manipulation and am creating a simple hang man game my daughter can fool with. Any advice would be appreciated, helpful links to some information would be great too. Thanks in advance.
import java.util.Random;
import java.util.Scanner;
public class Hangman {
public static void main(String[] args) {
String[] words = new String[10];
words[0] = "Elsa";
words[1] = "Anna";
words[2] = "Olof";
words[3] = "Sphen";
words[4] = "Christoph";
words[5] = "TinkerBell";
words[6] = "Arial";
words[7] = "SnowWhite";
words[8] = "Cinderella";
words[9] = "SleepingBeauty";
Random selWord = new Random();
int newWord = selWord.nextInt(10);
char[] wordLetters = words[newWord].toCharArray();
Scanner userInput = new Scanner(System.in);
System.out.println("Please make your first guess");
for (int i=0; i < words[newWord].length(); i++) {
System.out.print("_ ");
}
if (!userInput.hasNextLine()) {
do {
System.out.println("Please enter letters only.");
} while (!userInput.hasNext());
}
for (int n=0; n < wordLetters.length; n++) {
String userChoice = userInput.nextLine();
if (wordLetters[n] == userChoice.charAt(n)) {
System.out.println("You've made a match");
} else {
System.out.println("Sorry, try again.");
}
}
userInput.close();
// System.out.println(words[newWord]);
// System.out.println(words[newWord].length());
}
}
The problem is you are expecting the user to input a character at each line, but then you compare it with userChoice.charAt(n). You should compare it with the character which will be at userChoice.charAt(0).
Change this:
if (wordLetters[n] == userChoice.charAt(n))
To:
if (wordLetters[n] == userChoice.charAt(0))
In addition to this, I think your check below should be inside the for loop before you do String userChoice = userInput.nextLine():
if (!userInput.hasNextLine()) {
do {
System.out.println("Please enter letters only.");
} while (!userInput.hasNext());
}
So your for loop should look something like this:
for (int n=0; n < wordLetters.length; n++) {
while (!userInput.hasNextLine()) {
System.out.println("Please enter letters only.");
}
String userChoice = userInput.nextLine();
if (wordLetters[n] == userChoice.charAt(0)) {
System.out.println("You've made a match");
} else {
System.out.println("Sorry, try again.");
}
}
I ran you above code and it works.
I have put a System.out.println(newWord); to know what number has been randomly picked up and from the array if I type the same it says "You've made a match"
I read your code, seems it's totally unplayable.
so I made some change here
String[] words = new String[10];
words[0] = "Elsa";
words[1] = "Anna";
words[2] = "Olof";
words[3] = "Sphen";
words[4] = "Christoph";
words[5] = "TinkerBell";
words[6] = "Arial";
words[7] = "SnowWhite";
words[8] = "Cinderella";
words[9] = "SleepingBeauty";
Random selWord = new Random();
int newWord = selWord.nextInt(10);
char[] wordLetters = words[newWord].toCharArray();
boolean[] CheckBox = new boolean[wordLetters.length];//check each letter is correct
boolean checkRoundbyRound = false;//check the round have make matchs
int correctWords=0;//count how many letter is matched
for(int n=0;n< wordLetters.length; n++) CheckBox[n]=false;//initail
Scanner userInput;
System.out.println("Let's start");
while(true)
{
//initail
checkRoundbyRound=false;
correctWords=0;
//Hanging
for (int n=0; n < words[newWord].length(); n++)
{
if(CheckBox[n])
System.out.print(wordLetters[n]+" ");
else
System.out.print("_ ");
}
System.out.println("\nPlease enter letters only.");
userInput = new Scanner(System.in);
String userChoice = userInput.nextLine();
for (int n=0; n < wordLetters.length; n++)
{
for(int m=0;m<userChoice.length();m++)
{
//remember change the case, just for case :D
if (Character.toLowerCase(wordLetters[n]) == Character.toLowerCase(userChoice.charAt(m)))
{
CheckBox[n] = true;
checkRoundbyRound = true;
}
}
}
//Check have make match this round
if(checkRoundbyRound)
System.out.println("You've made a match");
else
System.out.println("Sorry, try again.");
//count how many letters found
for(int n=0;n<wordLetters.length;n++)
{
if(CheckBox[n])correctWords++;
}
//if all letters are correct, end game
if(correctWords==wordLetters.length)
break;
}
wish your daughter have fun.

Infinite Loop not working

The code works the first time through. But after that, the output doesnt work.
The main goal of this is to create an infinite loop, of asking a user for a phrase, then a letter. Then, to output the number of occurences of the letter in the phrase.
Also - - how would i go about breaking this loop by entering a word?
Scanner in = new Scanner(System.in);
for (;;) {
System.out.println("Enter a word/phrase");
String sentence = in.nextLine();
int times = 0;
System.out.println("Enter a character.");
String letter = in.next();
for (int i = 0; i < sentence.length(); i++) {
char lc = letter.charAt(0);
char sc = sentence.charAt(i);
if (lc == sc) {
times++;
}
}
System.out.print("The character appeared:" + times + " times.");
}
Remove the for loop and replace it with a while.
The while loop should check for a phrase and it will drop out automatically when the phrase is met.
So something like
while (!phraseToCheckFor){
// your code
}
This sounds like homework so I won't post all the code but this should be enough to get you started.
If you need an infinite loop, just do this:
for(;;) { //or while(true) {
//insert code here
}
You can break the loop by using the break statement, for example like this:
for(;;) {
String s = in.nextLine();
if(s.isEmpty()) {
break; //loop terminates here
}
System.out.println(s + " isn't empty.");
}
In order for your program to run correctly, you need to consume the last new line character. You can do this by adding a call to nextLine.
Working example,
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
for (;;) {
System.out.println("Enter a word/phrase");
String sentence = in.nextLine();
if (sentence.trim().equals("quit")) {
break;
}
int times = 0;
System.out.println("Enter a character.");
String letter = in.next();
for (int i = 0; i < sentence.length(); i++) {
char lc = letter.charAt(0);
char sc = sentence.charAt(i);
if (lc == sc) {
times++;
}
}
System.out.println("The character appeared:" + times + " times.");
in.nextLine();//consume the last new line
}
}

I'm having problems writing a code with String Arrays [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
So I have to write a piece of code that manages an event. There are 4 events with limited seats. I'm supposed to write string arrays for each one. The program will then add the name to the pertaining string. My problem is I don't know how to keep adding values to a String array using a loop without deleting the previous values. Any help will be greatly appreciated.
import java.util.Scanner;
public class Assignment_1 {
public static void main(String[] args) {
String [] Hockey_Game;
Hockey_Game = new String[10];
String [] Turner_Concert;
Turner_Concert = new String [5];
String [] Cats_Play;
Cats_Play = new String [3];
String [] StarTrek_Convention;
StarTrek_Convention = new String [3];
System.out.println("Which Event would you like to purchase a ticket for?");
System.out.println("1. Hockey Game 2. Tina Turner Concert \n"
+ "3. Cats Play 4. Star Trek Convention");
Scanner keyboard = new Scanner(System.in);
int input = keyboard.nextInt();
System.out.println("Please enter your first and last name");
Scanner scan = new Scanner(System.in);
String name = scan.nextLine();
for (int i = 0; i < Hockey_Game.length; i++){
Hockey_Game[i] = name;
}
for (String x: Hockey_Game ){
System.out.print(x +",");
}
This should be doing what you're looking for...
import java.util.Scanner;
public class Assignment_1 {
public static void main(String[] args) {
String[] Hockey_Game;
int numHockey = 0;
Hockey_Game = new String[10];
String[] Turner_Concert;
int numConcert = 0;
Turner_Concert = new String[5];
String[] Cats_Play;
int numPlay = 0;
Cats_Play = new String[3];
String[] StarTrek_Convention;
int numCon = 0;
StarTrek_Convention = new String[3];
for (int user = 0; user < 1; user++) {
System.out
.println("Which Event would you like to purchase a ticket for?");
System.out.println("1. Hockey Game 2. Tina Turner Concert \n"
+ "3. Cats Play 4. Star Trek Convention");
Scanner keyboard = new Scanner(System.in);
int input = keyboard.nextInt();
System.out.println("Please enter your first and last name");
Scanner scan = new Scanner(System.in);
String name = scan.nextLine();
switch (input) {
case 1:
if (numHockey < Hockey_Game.length) {
Hockey_Game[numHockey] = name;
}
numHockey++;
for (int j = 0; j < numHockey; j++) {
System.out.print(Hockey_Game[j] + ",");
}
break;
case 2:
if (numConcert < Turner_Concert.length) {
Turner_Concert[numConcert] = name;
}
numConcert++;
for (int j = 0; j < numConcert; j++) {
System.out.print(Turner_Concert[j] + ",");
}
break;
// ... continue for last two ...
}
}
}
}
I do agree with the other answerer that you should be using List/ArrayList for this, but if the purpose of the assignment was to use arrays, here's how you could do it.
Since you need to loop for 4 users (as per your comment), you should have a loop around the whole input process:
for (int i = 0; i < 4; i++) {
// read the input
// add name to correct array
}
You should keep counters for each of your event types:
// here come all your variable declarations
// declare the counters
int hockeyCounter = 0;
int tinaCounter = 0;
int catsCounter = 0;
int startrekCounter = 0;
// no need to redeclare the keyboard all the time, just once is enough
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < 4; i++) {
System.out.println("Which Event would you like to purchase a ticket for?");
System.out.println("1. Hockey Game 2. Tina Turner Concert \n"
+ "3. Cats Play 4. Star Trek Convention");
int input = keyboard.nextInt();
System.out.println("Please enter your first and last name");
String name = scan.nextLine();
switch (input) {
case 1: Hockey_Game[hockeyCounter++] = name; break;
case 2: Turner_Concert[tinaCounter++] = name; break;
case 3: Cats_Play[catsCounter++] = name; break;
case 4: StarTrek_Convention[startrekCounter++] = name; break;
default: System.out.println(input + " is not a valid input");
}
}
Is this now perfect? No, not quite. There are still some problems:
I didn't account for the maximum number of available tickets. This code will crash if all customers want a ticket to the cats' play.
There is a lot of code duplication. It already annoyed me enough to ignore the previously mentioned problem.
Variable names should always start with a lowercase (and preferably use camelCase). This is a Java convention, which helps other people read your code.
It would be better to somehow solve all these problems at once. For this I would propose an array of arrays (although that is maybe more complicated for a beginner, but would make the code much simpler):
final int EVENT_COUNT = 4;
final String[] EVENTS = { "Hockey Game", "Tina Turner Concert",
"Cats Play", "Star Trek Convention" };
final int[] LIMITS = { 10, 5, 3, 3 };
String[][] buyers = new String[EVENT_COUNT][];
int[] counters = new int[EVENT_COUNT];
for (int i = 0; i < EVENT_COUNT; i++) {
buyers[i] = new String[LIMITS[i]];
}
final int CUSTOMER_COUNT = 4;
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < CUSTOMER_COUNT; i++) {
System.out.println("Which Event would you like to purchase a ticket for?");
for (int j = 0; j < EVENT_COUNT; j++) {
System.out.print((j+1) + ". " + EVENTS[j] + " ");
}
System.out.println();
int input = keyboard.nextInt();
if (input < 1 || input > EVENT_COUNT) {
System.out.println(input + " is not a valid choice");
i--;
} else if (counters[input-1] >= LIMITS[input-1]) {
System.out.println(EVENTS[input-1] + " is sold out!");
i--;
} else {
System.out.println("Please enter your first and last name");
buyers[input-1][counters[input-1]++] = scan.nextLine();
}
}
Don't use String[] use List
List<String> event1 = new List<String>();
. . .
event1.add(name);
Also define an int[] (this time an array would suffice) that holds the maximum slots for each event, that way when the customer asks for a spot on an already maxed out event you can give him the bad news.
My problem is I don't know how to keep adding values to a String array using a loop without deleting the previous values.
Given the following string array definition:
String[] sa = new String[3];
You can replace existing elements' values...
sa[0] = "test"; // index 0 = "test"
sa[1] = "another"; // index 1 = "test", index 1 = "another"
sa[1] = "different"; // index 1 = "test", index 1 = "different"
You can append to a String array element just like a normal string...
sa[2] = "123"; // index 2 = "123"
sa[2] += "456"; // index 2 = "123456"
Now you can do either of those things in a loop as you see fit...
for (int i = 0; i < sa.length; i++) {
String userInputVar = getUserInput();
sa[i] = userInputVar; // replace value
sa[i] += "foo"; // append to value
}

Java - Scanner does not remove all of the desired objects

I am trying to make some kind of 'Evil Hangman game' (nifty Stanford CS exercises). The purpose of the game is to 'cheat' by removing as many possible word solutions as possible so the user cannot guess before the very end.
I have made a loop (below) which seems to remove many of the words possible words but for some reason it does not remove all of them. The input is a dictionary.txt file which contains about 120K words.
When I 'guess' the letter "a" it will take away roughly 60-70% of the words with "a" in them (estimate based on comparisons between the output with the first couple of words in the txt file)
File file = new File("dictionary.txt");
Scanner textScan = new Scanner(file);
List<String> wordList = new ArrayList<String>();
while ( textScan.hasNext() )
{
word = textScan.next();
wordList.add(word);
}
System.out.println("The ArrayList has " + wordList.size() + " objects stored in it.");
Scanner textScan1 = new Scanner(file);
for(int i = 0; i <= guessNumber; i++)
{
Collections.sort(wordList);
System.out.println("Type in your guess as a letter ");
String guess = keyboard.next();
guess = guess.toLowerCase();
while ( textScan1.hasNext() )
{
String word1 = textScan1.next();
if (wordLength != word1.length() && word1.contains(guess))
{
wordList.remove(word1);
}
}
}
I am aware that my code is a bit messy at this point, I am trying to improve everything about my programming so all feedback is greatly appreciated! I have the feeling that I am including stuff that does not have to be there and so on.
I will post the whole code below in case that helps:
import java.util.*;
import java.lang.*;
import java.io.*;
public class EvilHangman
{
public static void main(String[] args) throws IOException
{
// declaring variables
int wordLength;
int guessNumber;
// initiate the scanner
Scanner keyboard = new Scanner( System.in );
// introduction and prompting the user for word length
System.out.println("Welcome to Hangman. Let's play! ");
System.out.println("Please enter the desired word length: ");
wordLength = keyboard.nextInt();
while(wordLength < 0 || wordLength > 26)
{
System.out.println("This is not a valid word length. ");
System.out.println("Please enter the desired word length: ");
wordLength = keyboard.nextInt();
}
// prompt the user for number of guesses
System.out.println("How many guesses do you want to have? ");
guessNumber = keyboard.nextInt();
while(guessNumber < 0)
{
System.out.println("Number of guesses has to be a postive integer. ");
System.out.println("Please enter the desired number of guesses: ");
guessNumber = keyboard.nextInt();
}
// count the number of words with the specified length
/* int wordCount = 0;
String word = null;
while ( textScan.hasNext() )
{
word = textScan.next();
if (word.length() == wordLength)
{
wordCount++;
}
}
*/
// prompts the user whether he/she wants a running count of word length - using next() instead of nextLine() to clear buffer
/* System.out.println("Do you want a running total of number of words remaining? ");
String runningTotal = keyboard.next();
if (runningTotal.equalsIgnoreCase("yes"))
System.out.println("Words with that length: " + wordCount);
*/
// create a list (array) of all the words that matches the input length
String word = null;
File file = new File("dictionary.txt");
Scanner textScan = new Scanner(file);
List<String> wordList = new ArrayList<String>();
while ( textScan.hasNext() )
{
word = textScan.next();
wordList.add(word);
}
System.out.println("The ArrayList has " + wordList.size() + " objects stored in it.");
Scanner textScan1 = new Scanner(file);
for(int i = 0; i <= guessNumber; i++)
{
Collections.sort(wordList);
System.out.println("Type in your guess as a letter ");
String guess = keyboard.next();
guess = guess.toLowerCase();
while ( textScan1.hasNext() )
{
String word1 = textScan1.next();
if (wordLength != word1.length() && word1.contains(guess))
{
wordList.remove(word1);
}
}
}
System.out.println("The ArrayList has " + wordList.size() + " objects stored in it.");
System.out.println(wordList);
Finally figured out it had to do with the scanner. It had to be initiated inside the loop
for(int i = 1; i <= guessNumber; i++)
{
Scanner textScan2 = new Scanner(file1);
System.out.println("Type in your guess as a letter ");
String guess = keyboard.next();
//System.out.print(guess);
while ( textScan2.hasNext() )
{
String word1 = textScan2.next();
if (wordLength != word1.length() || (word1.contains(guess)))
{
wordList.remove(word1);
}
}
}

Categories