import java.util.Scanner;
import java.util.Random;
/*
* 1) the user can attempt many times and you need to display the number of successful attempt
* 2) the range of random number 1..49
* 3) output >> You successfully guess the number in 16 attempts
* 4) output >> Do you want to play again?
* */
public class GuessingGame {
public static void main(String[] args) {
Scanner uInput = new Scanner(System.in);
Random randNum = new Random();
int guessNumber, number, count=0;
String in;
char again;
System.out.println("Welcome to Guessing Game");
do {
number = randNum.nextInt(50); // random number in the range of 1..50
for(int i=0; i<5; i++)
{
System.out.println("Enter a number to guess: ");
guessNumber = uInput.nextInt(); // get guess number from user
if(guessNumber > number)
{
System.out.println("Too big");
}else if(guessNumber < number)
{
System.out.println("Too small");
}else
{
System.out.println("Success");
count+=1;
return;
}
}
System.out.println("You successfully guess the number in "+count);
System.out.println("Do you want to play again? ");
in = uInput.nextLine();
again = in.charAt(0); //again will hold the first character from in var
}while(again =='Y'|| again =='y');
System.out.println("Guessing game terminate, thank you");
}
}
public static void main(String[] args) {
System.out.println("Welcome to Guessing Game");
guessNumber();
System.out.println("Guessing game terminate, thank you");
}
private static void guessNumber() {
Scanner uInput = new Scanner(System.in);
Random randNum = new Random();
int guessNumber, number, count = 0;
String in;
char again;
boolean isCorrect = false;
number = randNum.nextInt(50); // random number in the range of 1..50
while (!isCorrect) {
System.out.println("Enter a number to guess: ");
guessNumber = uInput.nextInt(); // get guess number from user
count += 1;
if (guessNumber > number) {
System.out.println("Too big");
} else if (guessNumber < number) {
System.out.println("Too small");
} else {
System.out.println("Success");
isCorrect = true;
}
}
System.out.println("You successfully guess the number in " + count + " attempts");
System.out.println("Do you want to play again? yes/no");
in = uInput.next();
again = in.charAt(0); //again will hold the first character from in var
if (again == 'Y' || again == 'y') {
guessNumber();
}
}
All you have to do is to replace your do while loop with a while loop. But the point is that you must set an initial value 'Y' to your again char to start the while loop. the condition of the loop will be just the same. The code will be like : char again = 'Y';
while (again == 'Y' || again == 'y') {
System.out.println("Welcome to Guessing Game");
number = randNum.nextInt(50);
for (int i = 0; i < 5; i++) {
System.out.println("Enter a number to guess: ");
guessNumber = uInput.nextInt();
if (guessNumber > number) {
System.out.println("Too big");
} else if (guessNumber < number) {
System.out.println("Too small");
} else {
System.out.println("Success");
count += 1;
break;
}
}
System.out.println("You have successfully guessed the number for " + count + " times");
System.out.println("Do you want to play again? ");
in = uInput.next();
again = in.charAt(0); //again will hold the first character from in var
}
System.out.println("Guessing game terminate, thank you");
I must note that your count variable, contains the number of games which user has guessed the number successfully, and not the number of attempts during a single game. If you want to handle this too, create attempts variable inside the while loop and increase it whenever the user attempts.
Also I changed the line in = uInput.nextLine(); to in = uInput.next(); because I believe your scanner input will be skipped.
I want to give the user a choice to quit the program while the program is running whenever they feel like it. E.g. Press Q and ENTER at anytime to quit and end program.
I have a try and catch method but whenever I press Q and ENTER, it just displays whats in the catch part.
Here is the code:
public static void partB() {
//Code for partB goes here.
//Continues on with partA but with few changes
/* The number of multiplication problems should not be fixed. Instead,
the program should keep posing new multiplication problems until the user decides to quit by entering the letter "q".
The program should be able to deal with invalid input by the user.
It should ignore such input and restate the current multiplication problem.
*/
//Uses the imported Random function.
Random num = new Random();
//Initialises the minimum and maximum numbers.
int minNumber = 10; //Minimum number to start random
int maxNumber = 20; //Maximum number to start random
int counter = 0; //Counts the number of questions answered.
int correctAnswers = 0; //Counts the number of correct answers given.
final int numberOfQuestions = 0;
while(numberOfQuestions >= 0) {
//Generates a random integer between 10 and 20.
int randInt1 = (num.nextInt(maxNumber - minNumber) + minNumber);
//Repeats for the 2nd integer to get the product of the two numbers.
int randInt2 = (num.nextInt(maxNumber - minNumber) + minNumber);
//Initialise the Scanner function.
Scanner input = new Scanner(System.in);
//Output the Question.
System.out.println("What is " + randInt1 + " X " + randInt2 + "?" + " " + "(Press 'q' and ENTER to quit)");
//Waits for user input.
try {
int userInput = input.nextInt();
String quit = input.nextLine();
//If user input is 'q', quit program.
if(quit.equalsIgnoreCase("q")) {
System.out.println("Exiting...");
System.exit(0);
} else {
int answer = randInt1 * randInt2;
//Checks if the users input is correct.
if (answer == userInput) {
System.out.println("That is correct!");
correctAnswers++;
}
else {
System.out.println("That is incorrect! " + "The correct answer should be " + answer);
counter++;
}
}
} catch(InputMismatchException e) {
System.out.println("You have entered something other than an integer or 'q'! Please try again with a different question!");
}
}
}
If you want to accept both a number and a letter, it is better to use nextLine(). First you check for q, and then parse to number, as follows (note that parseInt will throw a NumberFormatException):
try {
String userInput = input.nextLine();
// If user input is 'q', quit program.
if (userInput.equalsIgnoreCase("q")) {
System.out.println("Exiting...");
System.exit(0);
} else {
int userAnswer = Integer.parseInt(userInput);
int answer = randInt1 * randInt2;
// Checks if the users input is correct.
if (answer == userAnswer) {
System.out.println("That is correct!");
correctAnswers++;
} else {
System.out.println("That is incorrect! " + "The correct answer should be " + answer);
counter++;
}
}
} catch (NumberFormatException e) {
System.out.println(
"You have entered something other than an integer or 'q'! Please try again with a different question!");
}
My code does not show the number of wins, losses and numberOfGames I had played.
I've been trying to fix it for the last month and I'm going nowhere!
import java.util.Random;
import java.util.Scanner;
public class HangmanP2 {
public static void main(String[] args) {
Scanner Input = new Scanner(System.in);
String first, reverse = "";
String second, reverse2 = "";
Scanner in = new Scanner(System.in);
System.out.println("Welcome to Hangman!");
System.out.println("Enter your first name.");
first = in.nextLine();
System.out.println("Enter your last name to play.");
second = in.nextLine();
int length = first.length();
int length2 = second.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + first.charAt(i);
reverse = reverse.substring(0,1).toUpperCase() + reverse.substring(1).toLowerCase();
for ( int i = length2 - 1 ; i >= 0 ; i-- )
reverse2 = reverse2 + second.charAt(i);
reverse2 = reverse2.substring(0,1).toUpperCase() + reverse2.substring(1).toLowerCase();
System.out.println("Your name entered in reverse is: "+reverse+" "+reverse2);
startGame(reverse,reverse2);
}
public static void startGame(String reverse,String reverse2){
Random rnd = new Random ();
Scanner user = new Scanner (System.in);
String guess = "";
String message = "";
int count = 1;
boolean quit = false;
String fullWord = "";
int wins=0;
int loss=0;
int numberOfGames=0;
int guessC = 5;
String usedLetters ="";
String remainingLetters ="";
String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int hinter = 0;
int z = rnd.nextInt(10);
int k = rnd.nextInt(2);
String words[][] = {{"earth","stars","light",
"world","about","again",
"stars","light","music",
"happy","water","amber",
"apple","piano","green",
"mouth","suger","stone",
"japan","china","after","lemon",
"grand",
"lives","twice","print"},{"smile",
"puppy","latin","vegan","phone","april",
"south","house","hangs","woman",
"power","today","india","night","candy",
"forum","birth","other","chris","irish",
"paste","queen","grace","crazy","plant",
"knife","spike","darth","vader","eagle",
"egypt","range","fists","fight","glory",
"March","smart","magic","codes","rolls",
"match","honor","glass","board","teams",
"bully","zebra","under","mango","brain",
"dirty","eight","zeros","train","cycle",
"break","necks","terms","slide","large"},{"stake","guess","wrong","anime","stick","outer","input"},{ "thing","write","white","black"}};
//Prints info of the game and topic that as been selected
System.out.println("Welcome to Hangman"+" "+reverse+" "+reverse2);
//This prints the '-' and spaces for the first run of the game only
for(int index = 0; index < words[z][k].length();index++)
{
Character variableInt = words[z][k].charAt(index);
if(variableInt != ' ')
{
message += "-";
}
else
{
message += " ";
}
}
//Nothing will change, this prints information to the user about his current status in-game.
System.out.println("Secret word: \t\t" + message);
System.out.println("Letters Remaining: " + letters);
System.out.println("Letters Used: ");
System.out.println("Guesses Remaining: " + guessC);
//The loop that will continuously run the game, until the user fails or does not want to play again.
do{
//The following variable's make sure there is not stacking from previous data when the loop runs again.
remainingLetters = "";
count = 0;
//Ask the user for a letter to guess
System.out.println("\nEnter a letter to guess the word): ");
guess = user.nextLine();
//The following for-loop converts ASCII table [A-Z] to actually characters and if the player used a letter it will not show up or add to the string each run of the do-loop.
for(int x = 65; x < 91;x++){
Character current = new Character ((char)x);
String current2 = current.toString();
if(!usedLetters.contains(current2)){
remainingLetters += current;
}
}
//Converts the user's first character to a string which is converted into another character and again converted into a String (Seem's useless) but i used it this way cause i was getting an error.
Character convert = new Character (guess.charAt(0));
Character conv = new Character (convert);
String converted = convert.toString();
//The letters the player uses will be added to a string, if it has not already been added and only if it is a letter.
if(!usedLetters.contains(converted) && conv.isLetter(convert)){
usedLetters+=guess.charAt(0);
}
//Inside this for-loop it turns our word into a String and the user's first character into a string.
for(int index = 0; index < words[z][k].length();index++){
//This is a helper
count++;
//Conversion of variables
Character current2 = new Character ( words[z][k].charAt(index));
String current = current2.toString();
Character current3 = new Character (guess.charAt(0));
String current4 = current3.toString();
String current5 = current4.toUpperCase();
String current6 = words[z][k].toUpperCase();
//If the players gets a letter correct, do the following.
if(current4.equalsIgnoreCase(current))
{
//Add's on to the previous string from where the player got it correct and change it to the correct letter instead of a '-'.
message = message.substring(0,index) + guess + message.substring(index + 1);
}
//If the player gets it wrong and the helper variable is equal to 1 (so that it does not follow the loop of the for-loop and it is not one of the special characters in the game('!' or '?').
if(!current6.contains(current5) && count == 1 && guess.charAt(0) != '?' && guess.charAt(0) != '!'){
guessC--;
}
}
//Prints information to the user of their current topic
//The secret word the player has to guess
System.out.println("Secret word: \t\t" + message.toUpperCase());
//The letters in the alphabet that have not been used yet
System.out.print("\nLetters remaining: ");
System.out.print(remainingLetters.toUpperCase() + "\n\n");
//This will print a message to the user, telling them information on using a hint or the hint itself.
//Letters the user has used since the game session has been running
System.out.print("\nLetters Used: ");
System.out.print(usedLetters.toUpperCase() + "\n");
//The amount of guesses the player has left
System.out.println("\nGuesses Remaining: " +guessC );
//If the player enters a '?' it will do the following.
if(guess.charAt(0) == '?'){
if(hinter <2){
//Displays what is in the array and information about the delay, while losing guesses.
hinter++;
System.out.print("\nHint will appear after next guess! \n");
guessC -=2;
}
}
//If the user guesses the word correct
if(message.equalsIgnoreCase(words[z][k])){
System.out.println("YOU ARE CORRECT! " + words[z][k] + " is correct!");
wins++;
quit = true;
}
//If the user ask to guess the entire word it is stored in a separate variable and make quit equal to true.
if(guess.charAt(0) == '!')
{
System.out.print("\nEnter the secret word: ");
fullWord = user.nextLine();
//if the user guesses the word correct then it will tell the user they are correct and make quit equal to true.
if(fullWord.equalsIgnoreCase(words[z][k])){
System.out.println("YOU ARE CORRECT! " + words[z][k] + " is correct!");
wins++;
quit = true;
}
//If the user does not get it right it will tell the user they are wrong and make quit equal to true.
else{
System.out.println("YOU ARE INCORRECT! the word is: " + words[z][k] + " ");
loss++;
quit = true;
}
}
//If the guesses counter equal 0 then it will tell them that they have lost and make quit equal to true.
if(guessC == 0){
System.out.println("GAME OVER! The secret word was [ " + words[z][k] + " ]!");
loss++;
quit = true;
}
//This is what happens when quit eventually becomes true, the user is asked if they would like to play again.
if(quit == true){
System.out.println("\nWould you like to play again (Y or quit)? ");
System.out.println("\nOr type [stats] to check your work");
guess = user.nextLine();
//If they do want to play again, they will need to enter Y and if they do it will give them another word to guess and resets there information so that there will be no overlap.
if(guess.equalsIgnoreCase("Y")){
quit = false;
z = rnd.nextInt(10);
k = rnd.nextInt(2);
guess = " ";
guessC = 6;
message = "";
usedLetters = "";
hinter = 0;
for(int index = 0; index < words[z][k].length();index++)
{
Character variableInt = words[z][k].charAt(index);
if(variableInt != ' ')
{
message += "-";
}
else
{
message += " ";
}
}
System.out.println("Secret word: \t\t" + message);
System.out.println("Letters Remaining: " + letters);
System.out.println("Letters Used: ");
System.out.println("Guesses Remaining: " + guessC);
}
if(guess.equals("stats")){
printGameStats(wins,loss,numberOfGames);
}
else{
//If the user enters 'N' then they will be told the following and the scanner will be closed.
System.out.println("THANK YOU FOR PLAYING HAVE A GOOD DAY!");
user.close();
}
}
//end of the while loop which will only stop if quit equals true.
}while(quit != true );
}
private static void printGameStats(int wins,int loss,int numberOfGames) {
// Line
System.out.print("+");
printDashes(37);
System.out.println("+");
// Print titles
System.out.printf("| %6s | %6s | %12s |\n",
"WINS", "LOSSES", "GAMES PLAYED");
// Line
System.out.print("|");
printDashes(10);
System.out.print("+");
printDashes(10);
System.out.print("+");
printDashes(10);
System.out.print("+");
printDashes(16);
System.out.print("+");
printDashes(18);
System.out.println("|");
// Print values
System.out.printf("| %6d | %6d | %12d |\n",
wins, loss, numberOfGames);
// Line
System.out.print("+");
printDashes(37);
System.out.println("+");
}
private static void printDashes(int numberOfDashes) {
for (int i = 0; i < numberOfDashes; i++) {
System.out.print("-");
}
}
}
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.util.*;
public class GuessingGameGUI {
public static void main(String[] args) {
Random rand = new Random();
int value = rand.nextInt(32) + 1;
int guesses = 0, LowGuess = 0, HighGuess = 0; //ADDED LowGuess AND HighGuess
Scanner input = new Scanner(System.in);
int guess;
boolean win = false;
while (win == false) {
JOptionPane.showInputDialog("Guess a number between 1 and 32: ");
guess = input.nextInt();
guesses++;
if (guess == value) {
win = true;
} else if (guess < value) {
JOptionPane.showInputDialog("Your guess is lower than random number");
LowGuess++; //COUNTER TO KEEP TRACK OF LOW GUESSES
} else if (guess > value) {
JOptionPane.showInputDialog("Your guess is higher than random number");
HighGuess++; //COUNTER TO KEEP TRACK OF HIGH GUESSES
}
}
JOptionPane.showMessageDialog(null, "You win! You are the worst guesser in history!");
JOptionPane.showMessageDialog(null, "The number was: " + value);
// ADDED FROM HERE (GUESSES)
JOptionPane.showMessageDialog(null, "Number of Guesses:" + guesses);
for (int x = 1; x <= guesses; x++) {
for (int a = 1; a <= guesses; a++) {
if (a == guesses) {
JOptionPane.showMessageDialog(null, "*");
}
}
} // TO HERE FOR AMOUNT OF GUESSES
// I ADDED FROM HERE (LOW)
JOptionPane.showMessageDialog(null, "Smaller Guesses:" + LowGuess);
for (int Low_i = 1; Low_i <= LowGuess; Low_i++) {
for (int Low_e = 1; Low_e <= LowGuess; Low_e++) {
if (Low_e == LowGuess) {
JOptionPane.showMessageDialog(null, "*");
}
}
} // Then TO HERE FOR LOW
// I ADDED FROM HERE (HIGH)
JOptionPane.showMessageDialog(null, "Largest Guesses:" + HighGuess);
for (int High_i = 1; High_i <= HighGuess; High_i++) {
for (int High_e = 1; High_e <= HighGuess; High_e++) {
if (High_e == HighGuess) {
JOptionPane.showMessageDialog(null, "*");
}
}
} //FINALLY TO HERE FOR HIGH
}
}
// when I run my program the message box pops up when i enter my guessing number, however it seems to stop and nothing else pops up to let me know if i guessed to high or to low.
Take these lines, for example:
JOptionPane.showInputDialog("Guess a number between 1 and 32: ");
guess = input.nextInt();
A prompt displays that asks you to "Guess a number between 1 and 32". So you enter the number, and then execution stops because your Scanner is awaiting your input. You need to completely remove your Scanner so you won't have these frequent interruptions.
The showInputDialog method of JOptionPane returns a String, as shown in the example from the Javadocs:
Show a dialog asking the user to type in a String:
String inputValue = JOptionPane.showInputDialog("Please input a value");
As is, you're throwing away the value returned from the method when you should instead be assigning it to your variables. In order to assign the returned value to your int variable guess, use Integer.parseInt:
guess = Integer.parseInt(JOptionPane.showInputDialog("Guess a number between 1 and 32: "));
JOptionPane.showInputDialog returns String than you have to convert that String to int using Parse methods, every time you receive input.
String input = JOptionPane.showInputDialog();
Int number = Integer.parseInt(input);
I am trying to make a text-based Hangman in Java.
This is my Java code:
package hangman;
import java.util.Random;
import java.util.Scanner;
import java.lang.String;
public class Hangman {
public static void main(String[] args) {
// TODO code application logic here
Scanner chez = new Scanner(System.in);
Scanner waffle = new Scanner(System.in);
Random randomGenerator = new Random();
StringBuilder displayWord = new StringBuilder("______________________________");
String theWord = null;
String preLetter;
//String sbDisplayWord;
char letter = 0;
int randomNumber;
int lengthOfWord;
int numberOfLetterInWord = 0;
int gDisplay;
int guessWordNumber = 0;
String guessWord;
RandomWord troll = new RandomWord();
randomNumber = randomGenerator.nextInt(12);
//Fill var with the word.
theWord = troll.wordDecide(randomNumber);
System.out.println ("Welcome to Hangman!");
lengthOfWord=theWord.length( );
System.out.println("This word has " + lengthOfWord + " letters.");
System.out.println("You have 20 guesses.");
for (int g =19; g >= 0; g--) {
System.out.println("If you want to guess the word, type 0. If you want to guess a letter, type 1.");
guessWordNumber=chez.nextInt();
if (guessWordNumber==0) {
System.out.println("Enter the word now. Remember, don't capitalize it.");
guessWord=waffle.nextLine();
if (guessWord.equals(theWord)) {
System.out.println("YOU WIN");
System.exit(0);
} else {
System.out.println("Sorry, this wasn't the correct word.");
}
} else if (guessWordNumber==1) {
System.out.println("Please enter the letter you wish to guess with.");
//System.out.println("It will tell you if you have guessed right for any of the letters. If it is blank, that means none of the letters match.");
preLetter=chez.nextLine();
letter=preLetter.charAt(0);
System.out.println("");
for(int i = 0; i <= lengthOfWord -1; i++ ) { //-Eshan
if (letter == theWord.charAt( i )) {
numberOfLetterInWord=i+1;
System.out.println("This letter matches with letter number " + numberOfLetterInWord + " in the word.");
displayWord.setCharAt(i, letter);
} else {
numberOfLetterInWord=i+1;
System.out.println("This letter doesn't match with letter number " + numberOfLetterInWord + " in the word.");
}
}
System.out.println("");
System.out.println("The word so far is " + displayWord);
System.out.println("");
gDisplay = g + 1;
System.out.println("You have " + gDisplay + " guesses left.");
} else {
System.exit(0);
}
}
System.out.println("GAME OVER");
System.exit(0);
}
}
package hangman;
public class RandomWord {
private static String[] wordArray = {
"psychology",
"keratin",
"nostalgia",
"pyromaniac",
"chlorophyl",
"derivative",
"unitard",
"pterodactyl",
"xylophone",
"excommunicate",
"obituary",
"infinitesimal",
"concupiscent",
};
public String wordDecide(int randomNumber) {
String theWord;
theWord = wordArray[randomNumber];
return theWord;
}
}
Netbeans is giving me this error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:695)
at hangman.Hangman.main(Hangman.java:56)
Java Result: 1
This is probably happening when you call charAt(0) on a string of length 0. You should check to see that the string is not empty before calling the method.
You are getting a StringIndexOutOfBoundsException due to the fact the line
guessWordNumber = chez.nextInt();
does not consume newline characters and passes the character through to the line
preLetter = chez.nextLine();
which then doesn't block as it will have already received input. This assigns an empty String to preLetter resulting in the exception. You can use Scanner#nextLine to consume this character:
guessWordNumber = Integer.parseInt(chez.nextLine());