Hangman, exits the game without getting the user response (loop) - java

I got a couple issues with my code. I know it is not the best looking design/coding but I don't claim to be a good programmer yet. I have to other classes does their work correctly. Dictionary class which contains a word list and HangmanAnimation class which draws the hangman onto console.
Now, I want my game to ask to player if he/she wants to play again after the game finished. Actually, it does asking if player wants to play again but exits the game before the player can type anything.
I would appreciate any other suggestions aswell. Thanks in advance! You guys really rock! :)
public class HangmanGame {
public static void main(String[] args) {
HangmanUI ui = new HangmanUI();
ui.initialize();
String input = "";
if(ui.newGame(input).equalsIgnoreCase("yes"))
main(null);
}
}
public class HangmanUI {
private final Dictionary d = new Dictionary();
private final HangmanAnimation ha = new HangmanAnimation();
private String wordInProgress = d.getWordInProgress();
Scanner sc = new Scanner(System.in);
private int maxTries = 5;
String word;
public void initialize() {
int easyWords = 1;
int hardWords = 2;
System.out.println("Welcome to Hangman game.");
System.out.println("=========================");
System.out.println("Rules: You need to find the given word in 5 tries.");
System.out.println("You will continue guessing letters until you can either");
System.out.println("solve the word or all five body parts are on the gallows.");
System.out.println("In that case you will lose the game. Try not to enter");
System.out.println("same letter more than once. Those are counts too.");
System.out.println();
System.out.println("Choose your game level or Quit:");
System.out.println("1) Easy");
System.out.println("2) Hard");
System.out.println("3) Quit");
try {
int playersChoice = sc.nextInt();
switch (playersChoice) {
case 1:
d.wordList(easyWords);
break;
case 2:
d.wordList(hardWords);
break;
case 3:
System.out.println("Thank you for your time!");
System.exit(0);
default:
System.out.println("Invalid input. Try again!");
initialize();
}
word = d.pickRandomWord(d.getWordList());
hideWord(word);
while(maxTries > 0) {
if(wordInProgress.contains("-")) {
System.out.println(wordInProgress);
revealLetter(notifyGuess());
} else {
System.out.println("Good work! You found the word.");
}
}
} catch (InputMismatchException e) {
System.out.println("Invalid input. Use only digits!");
}
}
//TODO: Do not count same letter more than once & let player to know.
public char notifyGuess() {
ArrayList<Character> charSet = new ArrayList<>();
System.out.print("Please enter a letter: ");
char c = sc.next().charAt(0);
if(Character.isDigit(c)){
System.out.println("You can't use numbers. Please enter a letter.");
notifyGuess();
} else if(charSet.contains(c)) {
System.out.println("You already used '" + c + "' before.");
notifyGuess();
} else
charSet.add(c);
return c;
}
public void hideWord(String word) {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < word.length(); i++) {
sb.append("-");
}
wordInProgress = sb.toString();
}
public void revealLetter(char c) {
try {
String temp = wordInProgress;
char[] charArray = wordInProgress.toCharArray();
for (int i = 0; i < word.length(); i++) {
if(c == word.charAt(i))
charArray[i] = word.charAt(i);
}
wordInProgress = new String(charArray);
if(temp.equals(wordInProgress)){
maxTries--;
ha.drawHanging(maxTries);
} else {
System.out.println("Good! There is '" + c + "' in the word.");
}
} catch (StringIndexOutOfBoundsException e) {
System.err.println("You have to enter a character!");
}
}
public String newGame(String input) {
System.out.println("Do you want to play again? (yes/no)");
input = sc.nextLine();
return input;
}
}

Try using this:
System.out.println("Do you want to play again? (yes/no)");
input = sc.next(); //<== here is the change
return input;

Related

For two integer user inputs, how to detect that a string has been passed on the very first input?

This is my code. A program to check for prime numbers between user inputs, 'start' and 'stop'.
import java.util.*;
public class test
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
while(true)
{
System.out.println("Enter start: ");
String start = sc.nextLine();
if(start.equalsIgnoreCase("stop"))
{
break;
}
System.out.println("Enter stop: ");
String stop = sc.nextLine();
if(stop.equalsIgnoreCase("stop"))
{
break;
}
try
{
int s1 = Integer.parseInt(start);
try
{
int s2 = Integer.parseInt(stop);
for(int i = s1; i<=s2;i++)
{
if(p1.isPrime(i))
{
System.out.print(i+" ");
}
}
System.out.println("");
}
catch(java.lang.NumberFormatException er)
{
System.out.println("Invalid Input");
}
}
catch(java.lang.NumberFormatException er1)
{
System.out.println("Invalid Input");
}
}
}
}
When taking start input, if I enter any string, I want the code to instantly detect NumberFormatException and ask for the same input again.
What happens instead, is that, it takes both inputs, whether string and integer, and only then evaluates whether it's a string.
I don't use sc.nextLine() because I want the stop functionality. I want the program to stop execution if I input "stop" anywhere.
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int start = -1;
int stop = -1;
while (true)
{
if (start == -1)
{
System.out.println("Enter start: ");
if (sc.hasNextInt())
{
start = sc.nextInt();
} else if (sc.nextLine().equalsIgnoreCase("stop")) break;
else
{
System.out.println("Invalid Input");
continue;
}
}
if (stop == -1)
{
System.out.println("Enter stop: ");
if (sc.hasNextInt())
{
stop = sc.nextInt();
} else if (sc.nextLine().equalsIgnoreCase("stop")) break;
else
{
System.out.println("Invalid Input");
continue;
}
}
for (int i = start; i <= stop; i++)
{
// Prime number method call here
System.out.print(i + " ");
}
System.out.println();
start = stop = -1;
}
}

Hangman if comparison running all branches

I'm working on a hangman assignment, but I am stuck in one part of it;
A player (user) is playing a game of words with the computer.
The users plays the game couple of times. When they stop the overall score of the user is displayed .
Each play the user sees a menu.
String S;
int s2;
System.out.println("WELCOME TO WORD GAME V.12.01.16");
System.out.println("****MENU****");
System.out.println("FIRST YOUR NUMBER AND PRESS 'ENTER' ");
System.out.printf("0:Stop \n 1:Name \n 2:City \n 3:Animal \n 4:Thing ");
s=input.nextInt();
if(s==0) {
System.out.println("GOODBYE");
}
for(int i=0;i<category.length;i++) {
if(s==i){
System.out.println("GUESS FOR 1,CHARACTER FOR 2");
s2=input.nextInt();
if(s2==1){
System.out.println("ENTER YOUR GUESS");
S=input.nextLine();
boolean result=correct(S);
if(result==true) {
System.out.println("Congrats");
}
}
}
}
}
public static boolean correct(String X) {
for(int i=1;i<5;i++){
for(int j=0;j<10;j++){
if (category[i][j].equals(X)) {
}
}
}
return true;
}
}
Your if statement if(category[s][j]==S); is done the wrong way
Also noted by #resueman in his comment that comparing strings was done the wrong way as well. You want to use .equals() to compare strings.
S=input.nextLine();
System.out.println("Please Enter : ")
for(int j=0;j<11;j++){
if (category[s][j].equals(S)){
System.out.println("CONGRATS");
}else {
System.out.println("FAIL");
}
}
Edit - New code from OPs edit
public static void main(String args[]) {
String string;
Scanner input = new Scanner(System.in);
int s, s2;
System.out.println("WELCOME TO WORD GAME V.12.01.16");
System.out.println(
"****MENU****");
System.out.println(
"FIRST YOUR NUMBER AND PRESS 'ENTER' ");
System.out.printf(
"0:Stop \n 1:Name \n 2:City \n 3:Animal \n 4:Thing ");
s = input.nextInt();
if (s == 0) {
System.out.println("GOODBYE");
}
for (int i = 0; i < category.length; i++) {
if (s == i) {
System.out.println("GUESS FOR 1,CHARACTER FOR 2");
s2 = input.nextInt();
if (s2 == 1) {
System.out.println("ENTER YOUR GUESS");
string = input.nextLine();
// Dont need to assign the boolean to a value
// if(booleanVariable == true) is the same thing as writing if(boolean)
// If it is true, it will execute, if false it will not
if (correct(string)) {
System.out.println("Congrats");
}
} // if(s2==1)
}// if (s == i)
}// for
}// run
public static boolean correct(String X) {
for (int i = 1; i < 5; i++) {
for (int j = 0; j < 10; j++) {
if (category[i][j].equals(X)) {
// the guess was right
return true;
}
}
}
// Nothing equaled the guess
return false;
}

Unsure of where to add certain piece of code

I have written some code which allows me to get user input for games a user has played. I have done most of it, however I have come to a point where I do not know where to add this code totalScore = totalScore + score;. This code will get me the total score of the player each time they add a new game. As well as this I am also confused about how to get a total amount of invalid entries which a user has tried to enter, meaning for each invalid entry I need to keep count of it so I can later display the total amount of invalid entries.
import java.util.Scanner;
public class REQ3
{
public static void main (String[] args)
{
String playername;
String line;
String[] list = new String[100];
int count = 0;
int score;
int time;
int gamesplayed =0;
int totalScore =0;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your name");
playername = sc.nextLine();
if(playername.equals(""))
{
System.out.println("Player name was not entered please try again");
System.exit(0);
}
System.out.println("Please enter your game achivements (Game name:score:time played) E.g. Minecraft:14:2332");
while (count < 100){
line = sc.nextLine();
if(line.equals("quit")){
break;
}
if(line.equals("")){
System.out.println("Nothing was entered please try again");
break;
}
if(!(line.contains(":"))){
System.out.println("Please enter achivements with the proper \":\" sepration\n");
break;
}
list[count]=line;
System.out.println("list[count]" + list[count]);
count++;
gamesplayed++;
for (int i=0; i<count; i++){
line=list[i];
String[] elements =line.split(":");
if (elements.length !=3){
System.out.println("Error please try again, Please enter in the following format:\nGame name:score:timeplayed");
break;
}
try {
score = Integer.parseInt(elements[1].trim());
totalScore = totalScore + score; // added here
} catch(NumberFormatException ex) {
System.out.println("Incorrect score data, Please enter a valid integer");
}
try {
time=Integer.parseInt(elements[2].trim());
} catch(NumberFormatException ex) {
System.out.println("Incorrect time data, Please enter a valid integer");
}
}
}
System.out.println("Player : " + playername);
System.out.println("--------------------------------");
System.out.println("Games Played: " +gamesplayed);
}
}
I dont know why you are using a for loop . You should remove the for loop and do totalScore after reading score
import java.util.Scanner;
public class REQ3 {
public static void main(String[] args) {
String playername;
String line;
String[] list = new String[100];
int count = 0;
int time;
int gamesplayed = 0;
int totalScore = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your name");
playername = sc.nextLine();
if (playername.equals("")) {
System.out.println("Player name was not entered please try again");
System.exit(0);
}
System.out.println("Please enter your game achivements (Game name:score:time played) E.g. Minecraft:14:2332");
while (count < 100) {
line = sc.nextLine();
if (line.equals("quit")) {
break;
}
if (line.equals("")) {
System.out.println("Nothing was entered please try again");
break;
}
if (!(line.contains(":"))) {
System.out.println("Please enter achivements with the proper \":\" sepration\n");
break;
}
list[count] = line;
System.out.println("list[count]" + list[count]);
count++;
gamesplayed++;
String[] elements = line.split(":");
if (elements.length != 3) {
System.out.println(
"Error please try again, Please enter in the following format:\nGame name:score:timeplayed");
break;
}
try {
int score = Integer.parseInt(elements[1].trim());
totalScore += score;
} catch (NumberFormatException ex) {
System.out.println("Incorrect score data, Please enter a valid integer");
}
try {
time = Integer.parseInt(elements[2].trim());
} catch (NumberFormatException ex) {
System.out.println("Incorrect time data, Please enter a valid integer");
}
}
System.out.println("Player : " + playername);
System.out.println("--------------------------------");
System.out.println("Games Played: " + gamesplayed);
System.out.println("total score: " + totalScore);
}
}
Agree with awesome not sure why you need inner for loop. Below is the solution which work for both invalid entries and total score.
import java.util.Scanner;
public class REQ3 {
public static void main(String[] args) {
String playername;
String line;
String[] list = new String[100];
int count = 0;
int score = 0;
int time;
int gamesplayed = 0;
int totalScore = 0;
int invalidEntries = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your name");
playername = sc.nextLine();
if (playername.equals("")) {
System.out.println("Player name was not entered please try again");
System.exit(0);
}
System.out
.println("Please enter your game achivements (Game name:score:time played) E.g. Minecraft:14:2332");
while (count < 100) {
line = sc.nextLine();
if (line.equals("quit")) {
break;
}
if (line.equals("")) {
System.out.println("Nothing was entered please try again");
invalidEntries++;
continue;
}
if (!(line.contains(":"))) {
System.out
.println("Please enter achivements with the proper \":\" sepration\n");
invalidEntries++;
continue;
}
list[count] = line;
System.out.println("list[count]" + list[count]);
String[] elements = line.split(":");
if (elements.length != 3) {
System.out
.println("Error please try again, Please enter in the following format:\nGame name:score:timeplayed");
invalidEntries++;
continue;
}
try {
score = Integer.parseInt(elements[1].trim());
} catch (NumberFormatException ex) {
System.out
.println("Incorrect score data, Please enter a valid integer");
invalidEntries++;
continue;
}
try {
time = Integer.parseInt(elements[2].trim());
} catch (NumberFormatException ex) {
System.out
.println("Incorrect time data, Please enter a valid integer");
invalidEntries++;
continue;
}
count++;
gamesplayed++;
totalScore = totalScore + score;
}
System.out.println("Player : " + playername);
System.out.println("--------------------------------");
System.out.println("Games Played: " + gamesplayed);
System.out.println("Total Score: " + totalScore);
System.out.println("Invalid Entries: " + invalidEntries);
}
}

How should I loop this program?

Basically I need to loop this. I created a game where you answer questions about fish in runescape and I would like it to loop like say would ‘you go again’ or something. How would I go about this?
import java.util.Scanner;
public class GameDriver
{
public static void main(String a[])
{
Game g = new Game();
Scanner s = new Scanner(System.in);
String buf = null;
for(int i = 0; i < 4; i++)
{
System.out.print(g.askQuestion());
buf = s.nextLine();
if(g.confirm(buf))
System.out.println("You're Right!");
else
System.out.println("You're Wrong...");
}
System.out.println("You got a " + g.getScore());
}
}
You could do while (true) loop and then if the user enters quit just break the loop like so:
if (buf.equals("quit"))
break;
PFB complete code for ‘you go again’ program:
import java.util.Scanner;
public class GameDriver {
public static void Gamer(Scanner s) {
Game g = new Game();
String buf = null;
for (int i = 0; i < 4; i++) {
System.out.print(g.askQuestion());
buf = s.nextLine();
if (g.confirm(buf))
System.out.println("You're Right!");
else
System.out.println("You're Wrong...");
}
System.out.println("You got a " + g.getScore());
}
public static void main(String a[]) {
Scanner s = new Scanner(System.in);
try {
while (true) {
System.out.print("Press Enter to continue; Type Exit to quit");
if (s.nextLine().equalsIgnoreCase("exit")) {
s.close();
break;
}
Gamer(s);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
As per i understand your question,you want to loop over the for loop.Kindly correct me if i m wrong.
char c='y';//'y' means user wants to go again
while(c=='y')// to check the user reply.
{
for(int i = 0; i < 4; i++)
{
System.out.print(g.askQuestion());
buf = s.nextLine();
if(g.confirm(buf))
System.out.println("You're Right!");
else
System.out.println("You're Wrong...");
}
System.out.println("You got a " + g.getScore());
System.out.println("Do you wanna go again?");
c=s.next.charAt(0);
}
This is shortest solution keeping all your code logic as is :
import java.util.Scanner;
public class GameDriver {
public static void Gamer(Scanner s) {
Game g = new Game();
String buf = null;
for (int i = 0; i < 4; i++) {
System.out.print(g.askQuestion());
buf = s.nextLine();
if (g.confirm(buf))
System.out.println("You're Right!");
else
System.out.println("You're Wrong...");
}
System.out.println("You got a " + g.getScore());
System.out.print("Press Enter to continue; Type Exit to quit");
if (s.nextLine().equalsIgnoreCase("exit")) {
s.close();
System.exit(0);
}
Gamer(s);
}
public static void main(String a[]) {
Gamer(new Scanner(System.in));
}
}

trouble with char in java

I am practicing and I want to create a code with a infinite loop the while loop, but my problem is that I don't know how to compare char or read char from the keyboard. So, far I have done the code below, any suggestions please ?
Scanner keyboard = new Scanner(System.in);
System.out.println("Guess my favorite character: ");
String letter = keyboard.nextLine();
char secret = 'a';
while (true) {
System.out.println(" Enter guess:");
String guess = keyboard.nextLine();
for (int i = 0; i < guess.length(); i++) {
if (guess.chartAt(i).equals('a')) {
break;
}
}
System.out.println("YOU got it!");
}
}
}
break only jumps out of the for loop, so you have a infinite while true loop. You may want to try this way.
Scanner keyboard = new Scanner(System.in);
System.out.println("Guess my favorite character: ");
String letter = keyboard.nextLine();
char secret = 'a';
while (true) {
System.out.println(" Enter guess:");
String guess = keyboard.nextLine();
for (int i = 0; i < guess.length(); i++) {
if (guess.chartAt(i).equals('a')) {
System.out.println("YOU got it!");
return;
}
}
}
Try like this;
String secret = "a";
Boolean isFounded = false;
while (true) {
System.out.println(" Enter guess:");
String guess = keyboard.nextLine();
for (int i = 0; i < guess.length(); i++) {
if (guess.equals(secret)) {
System.out.println("YOU got it!");
isFounded = true;
}
if(isFounded) break;
}
if(isFounded) break;
}
Only one loop here give it a try.
String secret = "a";
String guess = "";
Scanner keyboard = new Scanner(System.in);
while(!guess.contains(secret)){
System.out.println(" Enter guess:");
guess = keyboard.nextLine();
}
System.out.println("YOU got it!");

Categories

Resources