As part of our coursework myself and another person in my class have to make a Guessing Game where a random number is generated between 1 to 100 and the user has a maximum of 6 guesses to try and guess the number. I also have to create a "session" where the user can enter their name and it will store their results into a text file. I have got it working to a point where they can play the game and successfully input their name, but if you select the option that you want to play again, it says 'Process completed' and exits the program. Help would be greatly appreciated, here is what I have so far;
Code:
import java.util.Random; //importing the Random class
import java.util.Scanner; //importing the Scanner class
/* Author Laura Brown 28/02/2014 */
public class TheGuessingGame
{
public static void main(String[] args)
{
Random generator = new Random(); //creates a random number between 1-100
int TARGET = generator.nextInt(100) + 1; //establishes the target number
int guess;
int count = 0;
String userName;
String another = "y";
Boolean flag = false;
Boolean anotherFlag = true;
Scanner consoleIn = new Scanner(System.in); //creating a new Scanner object
Scanner name = new Scanner(System.in); //creating a new Scanner object
System.out.print("Hello! Please enter your name:\n"); //asking for user input
userName = name.nextLine();
System.out.print("Hello "+ userName+ ", and welcome to the game!\n");
System.out.print("Can you guess what it is?\n");
do { //beginning the loop
guess = consoleIn.nextInt();
count++;
if (guess > TARGET)
System.out.print("Sorry - Your guess is too high \n");
else
if (guess < TARGET)
System.out.print("Sorry - Your guess is too low \n");
}
while(guess != TARGET && count < 6);
if(guess == TARGET) {
System.out.println("Congratulations! - You found it!");
System.out.println();
}
else {
System.out.println("Sorry - You have used all 6 guesses");
}
System.out.println();
System.out.println("Would you like to guess again? (yes/no)");
another = consoleIn.next();
}
}
You need to add another loop. Stylistically speaking, I would avoid using do...while loops, as they are difficult to read. I have included a while loop done the more traditional way to show you how blissfully sexy they are.
while(anotherFlag)
{
TARGET = generator.nextInt(100) + 1; //establishes the target number
System.out.print("Can you guess what it is?\n");
do
{ //beginning the loop
guess = consoleIn.nextInt();
count++;
if (guess > TARGET)
System.out.print("Sorry - Your guess is too high \n");
else
if (guess < TARGET)
System.out.print("Sorry - Your guess is too low \n");
}
while(guess != TARGET && count < 6);
if(guess == TARGET) {
System.out.println("Congratulations! - You found it!");
System.out.println();
}
else
{
System.out.println("Sorry - You have used all 6 guesses");
}
System.out.println();
System.out.println("Would you like to guess again? (yes/no)");
another = consoleIn.next();
}
The above won't work fully, you need to set anotherFlag to false if the user inputs 'no'. That should be a relatively simple exercise, but the above will get the program to loop over and over.
public static void main(String[] args)
{
Random generator = new Random(); //creates a random number between 1-100
int guess;
int count = 0;
int Target;
String userName;
String another = "y";
Boolean flag = false;
Boolean anotherFlag = true;
Scanner consoleIn = new Scanner(System.in); //creating a new Scanner object
Scanner name = new Scanner(System.in); //creating a new Scanner object
System.out.print("Hello! Please enter your name:\n"); //asking for user input
userName = name.nextLine();
System.out.print("Hello "+ userName+ ", and welcome to the game!\n");
while (another.equalsIgnoreCase("y")) // this will check if your user input "another"
{
TARGET = generator.nextInt(100) + 1; //establishes the target number
System.out.print("Can you guess what it is?\n");
do { //beginning the loop
guess = consoleIn.nextInt();
count++;
if (guess > TARGET)
System.out.print("Sorry - Your guess is too high \n");
else
if (guess < TARGET)
System.out.print("Sorry - Your guess is too low \n");
}
while(guess != TARGET && count < 6);
if(guess == TARGET) {
System.out.println("Congratulations! - You found it!");
System.out.println();
}
else {
System.out.println("Sorry - You have used all 6 guesses");
}
System.out.println();
System.out.println("Would you like to guess again? (yes/no)");
another = consoleIn.next();
consoleIn.nextLine();
}
}
}
Added in another loop to loop the whole gaming process. And brought down the random generating method to be inside the loop to regenerate a new number. Try it. Anyway I added another line consoleIn.nextLine(); after your user input to clear the carriage return buffer for .next() method.
Related
first off, the secret word is printed out as dashes, then the user puts in what letter they want to guess. if they guess the letter correctly then it will update the dashes. so if the word is java, it will show as ---- and if the user types a, then it will update and show -a-a . my program does that but it also adds extra dashes at the end and i don't know how to make it not print those extra dashes. and that brings me to another problem i am having, the user is asked at what indexes they want to guess the letter. so if the user types the letter a and at index 1, then the updated word will show -a--, but my program updates all instances of where the a is at, so it shows -a-a. here is my code:
import java.util.Scanner;
public class HangMan2 {
private static final boolean testingMode = true;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int guessRemaining = 20;
int rounds = 1;
int roundScore;
String wordString = "";
String word = RandomWord.newWord();
int length = word.length();
for(int i = 0; i < length; i++)
{
wordString += "-";
}
System.out.println("The word is: " +wordString);
System.out.println("The secret word is: " +word);
System.out.println("Enter the number of spaces allowed");
int spacesAllowed = keyboard.nextInt();
keyboard.nextLine();
if(spacesAllowed > length)
{
System.out.println("Invalid input. Try again.");
System.out.println("Enter the number of spaces allowed");
spacesAllowed = keyboard.nextInt();
}
while(guessRemaining > 0) {
System.out.println("Please enter the letter you want to guess: ");
String letterGuess = keyboard.next();
char letterCharacter = letterGuess.charAt(0);
System.out.println("Please enter the number of spaces you want to check (seperated by spaces): ");
String spacesChecked = keyboard.next();
boolean guessCheck;
// check if the letter is in the string
guessCheck = (word.indexOf(letterCharacter)) != -1;
if(guessCheck == true)
{
for (int i = 0; i < word.length(); i++) {
if (letterCharacter == word.charAt(i)) {
wordString = wordString.substring(0, i) + letterGuess + wordString.substring(i);
System.out.println("Your guess is in the word!");
System.out.println("The updated word is: " +wordString);
} //end of if statement
} //end of for loop
}
else
{
System.out.println("Your letter was not found in the spaces you provided");
guessRemaining--;
System.out.println("You have " +guessRemaining+ " guesses remaining.");
}
}
if(guessRemaining != 0)
{
System.out.println("You win!");
System.out.println("You have guessed the word! Congratulations");
roundScore = (guessRemaining * 10) / spacesAllowed;
} //end of if
else{
System.out.println("Guesses Remaining: 0");
System.out.println("You have failed to guess the word... :(");
}
System.out.println("Would you like to play again? Yes (y) or No (n)");
String playAgain = keyboard.next();
if(!playAgain.equals("y") && !playAgain.equals("n"))
{
System.out.println("Invalid response, please try again... ");
}
if(playAgain.equals("y"))
{
rounds++;
}
else
{
System.exit(0);
}
}
}
wordString = wordString.substring(0, i) + letterGuess + wordString.substring(i);
if ((wordString.substring(0,i) + wordString.substring(i)).equals(wordString))
System.out.println("These are completely identical");
else
System.out.println("You solved it yourself ;)");
hint: it's 58 in your posted code.
Second part: Completely different program structure.
You'll need to track user's two guessed values, one as a character, the other as an int.
You will compare wordString.toCharArray()[indexUserGuessed] to characterUserGuessed and update the result or game state as needed, using similar code from the way you solved the if statement paradox I provided.
Finally, Welcome to Stack Exchange. MOST of us won't do your homework for you.
Oh and I would look up examples of "StringBuilder Java" as you might find it easier to manipulate your String with this class than with String.
We are meant to to create a program in java in which the computer randomly guesses a number between 1-100 and allows the user to guess to the number. If the number is lower than the random number the program should say: lower! and of higher, the program should say: higher! If the user guesses the right number it should say congratulations you guessed the right number in X amount of tries, This is what I have so far, when I execute in cmd it just spams either higher or lower and I need help working it out.
import java.util.Scanner;
import java.util.Random;
public class GuessingGame{
public static void main(String[] args) {
int random, guess, attempts;
Scanner keyboard = new Scanner(System.in);
Random generator = new Random();
random = generator.nextInt(100) + 1;
attempts = 1;
System.out.print("I am thinking of a number between 0 and 100, what do you think it is?");
guess = keyboard.nextInt();
while (guess != random) {
if (guess > random) {
System.out.print("Lower!");
attempts += 1;
}
else {
System.out.print("Higher!");
attempts +=1;
}
}
System.out.print(random + "is the correct answer and it took you" + attempts + "attempts to guess it!");
}
}
You're only reading the input once and then looping on it forever (you read the input outside the loop).
Try reading the input inside the loop and using do-while loop:
guess = 0;
do {
guess = keyboard.nextInt();
if (guess > random) {
System.out.print("Lower!");
attempts += 1;
} else {
System.out.print("Higher!");
attempts +=1;
}
} while (guess != random);
Place the guess = keyboard.nextInt(); into the while loop to ask again and again.
You only take a single guess and stuck yourself in the while loop, it's like if the number randomized by the program is 70, and for example if the user gave his first attempt as 50, the code will enter the while loop as the number is not 70, but it won't come out as you coded while(guess != random) and guess will ever equal random in our case, and it will be always lower for an infinite time because you give him the ability to enter a single attempt and then you enter an endless while loop without giving him the ability to change his attempt through it, So, you must allow him to has his second, third, ..etc attempts inside the while loop itself, like the following:
guess = keyboard.nextInt();
while (guess != random) {
if (guess > random) {
System.out.print("Lower!");
attempts += 1;
}
else {
System.out.print("Higher!");
attempts +=1;
}
guess = keyboard.nextInt();
}
The random number generate the number once the we will call the method isNumCorrect again using while loop until it returns true and the guess count will increase every time the number pass through isNumCorrect
import java.util.Random;
import java.util.Scanner;
class guessGame {
int guessedNumber;
int userNumber;
int guess_count;
public guessGame() {
Random rand = new Random();
guessedNumber = rand.nextInt(100);
}
void userNum() {
System.out.println("GUESS THE NUMBER");
Scanner sc = new Scanner(System.in);
userNumber = sc.nextInt();
}
boolean isNumCorrect() {
guess_count++;
if (userNumber == guessedNumber) {
System.out.printf("yes you guessed it right in %d guesses", guess_count);
return true;
} else if (userNumber < guessedNumber) {
System.out.println("too low");
} else {
System.out.println("too high");
}
return false;
}
}
public class cwh_42_guess_the_number {
public static void main(String[] args) {
guessGame g = new guessGame();
boolean b = false;
while (!b) {
g.userNum();
b = g.isNumCorrect();
}
}
}
I'm practicing Java and i tried to make a guess game but i want the game to ask for input again when the user don't guess the number right. When i guess the number wrong the loop just continuous to guess numbers until the number is the right one and the game ends.
import java.util.*;
class GuessGame {
private Scanner userInput = new Scanner(System.in);
public GuessGame(){
System.out.println("~~~Guess Game~~~");
System.out.println("~~~Guess a number between 0 and 9~~~");
}
int guessedNumber = 0;
public void gameStart(){
System.out.println("Guess a number: ");
boolean guessedRight = false;
boolean gameOn = true;
int userNumber = userInput.nextInt();
while(gameOn){
guessedNumber = userNumber;
int randomNumber = (int) (Math.random() * 10);
if(randomNumber == guessedNumber){
guessedRight = true;
}
if(guessedRight){
System.out.println("You guessed " + guessedNumber);
System.out.println("The number is " + randomNumber);
System.out.println("You won!!!");
System.out.println("Game Over!!!");
break;
}else{
System.out.println("You guessed " + guessedNumber);
System.out.println("The number is " + randomNumber);
System.out.println("Try again!!!");
}
}
}
}
The int userNumber = userInput.nextInt(); line is responsible for getting the number that the user entered from the input line. Moving this line inside the while loop will ask for a number each time the loop is ran (which is only once if the user guesses right the first time).
Just call the method from a loop:
public GuessGame(){
while(true) {
System.out.println("~~~Guess Game~~~");
System.out.println("~~~Guess a number between 0 and 9~~~");
gameStart();
}
}
This will simply restart the game as soon as the gameStart() method exists. (Which is when the user has guessed the right number)
I have wrote this code and now i'm practicing and i'm trying it to write it in a different or more efficient way. Basically this code asks the user to enter a word and the second player guesses the letters of the word with 6 tries and at the end there is one last chance to guess the whole entire word. Any suggestions on how i can write this code in a simple way?
static int NUM_OF_TRIES = 6;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Player 1 please enter the word");
String word = keyboard.next();
for (int i = 0; i < NUM_OF_TRIES; i++) {
System.out.println("Enter your guess please");
String guess = keyboard.next();
boolean a = true;
for (int j = 0; j < word.length(); j++) {
if (guess.charAt(0) == word.charAt(j)) {
System.out.println(" at position " + (j + 1));
a = false;
break;
}
}
if (a) {
System.out.println("Sorry not letter " + guess.charAt(0));
continue;
}
}
System.out.println("Enter your last guess: ");
String wordComp;
wordComp = keyboard.next();
if (wordComp.equals(word)) {
System.out.println("You got it!");
} else {
System.out.println("Sorry you lost!");
}
}
}
Well, here is a shorter version:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Player 1 please enter the word");
String word = keyboard.next();
for (int i = 0; i < NUM_OF_TRIES; i++) {
System.out.println("Enter your guess please");
String guess = keyboard.next();
int index = word.indexOf(guess.charAt(0));
if (index == -1)
System.out.println("Sorry not letter " + guess.charAt(0));
else
System.out.println(" at position " + (index + 1));
}
System.out.println("Enter your last guess: ");
String wordComp = keyboard.next();
if (wordComp.equals(word))
System.out.println("You got it!");
else
System.out.println("Sorry you lost!");
}
---First of all you'll have to ensure that
word.length <=guess.length
or you'll run into an exception.--- edit: that was obv not correct
Can't test right now bc I'm on my mobile, but as far as I can see, you'll run into problems if the word to guess has the same letter multiple times, since you're breaking out of the loop after finding the equal first letter.
As mentioned in comments, the comparison could be done by a method like
private static List<Integer> getLetterIndices(String word, char letter);
Then you won't need your boolean to indicate correct guesses, but a list of indices found
And of course you can do an object oriented approach instead of the static main method (not that it's faster to implement or better performance, just for practicing), perhaps something in the lines of this:
public class WordToGuess{
private Map<Character,List<Integer>> letter2indices;//...
public WordToGuess(String word){
parseIndices(word);
}
//parse indices of each letter to the map
private void parseIndices(String word);
public List<Integer> getLetterIndices(char letter);
}
I´m totally new to Java and I´m stuck. I have to create the game "guess the Number". I´m able to do the most parts but I´m don´t now how to handle the User Input if its a String.
I want to be able to tell the User that the Input was not correct if he enters a String, and repeatedly ask for Input. It would be great if someone could help me here :)
Here is my Code:
import java.util.Scanner;
import java.util.Random;
public class SWENGB_HW_2 {
public static void main(String[] args) {
System.out.println("Welcome to the guess the number game!\n");
System.out.println("Please specify the configuration of the game:\n");
Scanner input = new Scanner(System.in);
System.out.println("Range start number (inclusively):");
int startRange;
startRange = input.nextInt();
System.out.println("Range end (inclusively):");
int endRange;
endRange = input.nextInt();
System.out.println("Maximum number of attemps:");
int maxAttemp;
maxAttemp = input.nextInt();
System.out.println("Your Task is to guess the random number between "
+ startRange + " and " + endRange);
Random randGenerator = new Random();
int randNumber = randGenerator.nextInt((endRange - startRange) + 1)
+ startRange;
int numberOfTries = 0;
System.out
.println("You may exit the game by typing; exit - you may now start to guess:");
String exit;
exit = input.nextLine();
for (numberOfTries = 0; numberOfTries <= maxAttemp - 1; numberOfTries++) {
int guess;
guess = input.nextInt();
if (guess == randNumber) {
System.out.println("Congratz - you have made it!!");
System.out.println("Goodbye");
} else if (guess > randNumber) {
System.out.println("The number is smaller");
} else if (guess < randNumber) {
System.out.println("The number is higher");
}
}
if (numberOfTries >= maxAttemp) {
System.out.println("You reached the max Number of attempts :-/");
}
}
}
You can create a utility method that looks like this:
public static int nextValidInt(Scanner s) {
while (!s.hasNextInt())
System.out.println(s.next() + " is not a valid number. Try again:");
return s.nextInt();
}
and then, instead of
startRange = input.nextInt()
you do
startRange = nextValidInt(input);
If you want to deal with the "exit" alternative, I'd recommend something like this:
public static int getInt(Scanner s) throws EOFException {
while (true) {
if (s.hasNextInt())
return s.nextInt();
String next = s.next();
if (next.equals("exit"))
throw new EOFException();
System.out.println(next + " is not a valid number. Try again:");
}
}
and then wrap the whole program in
try {
...
...
...
} catch (EOFException e) {
// User typed "exit"
System.out.println("Bye!");
}
} // End of main.
Btw, the rest of your code looks great. I've tried it and it works like a charm :-)
You could check that the scanner has an int before you attempt to read it. You can do that by calling hasNextInt() with something like
while (input.hasNext() && !input.hasNextInt()) {
System.out.printf("Please enter an int, %s is not an int%n", input.next());
}
int startRange = input.nextInt();