what is the best way to use a for loop? - java

This program is a guessing game in which you input a letter between a and j and try to guess the randomly chosen answer. It works correctly, but I want to use a for loop to encompass all three guesses instead of writing them all out separately. Any suggestions on how to start this?
import java.util.Scanner;
import java.lang.Math;
import java.util.Random;
class Guess{
public static void main( String[] args ){
Scanner sc = new Scanner(System.in);
System.out.println("I'm thinking of a letter in the range a to j. You have three guesses. ");
for(int i = 0; i<3; i++){ //this is where I'm having trouble
System.out.print("Enter your first guess: ");
Random r = new Random();
char i = (char)(r.nextInt(10) + 'a');
char b = sc.next().charAt(0);
if(b>i){
System.out.println("Your guess is too high. ");
} else if(b<i){
System.out.println("Your guess is too low. ");
} else if(b==i){
System.out.println("You win! ");
return;
}
System.out.print("Enter your second guess: ");
b = sc.next().charAt(0);
if(b>i){
System.out.println("Your guess is too high. ");
} else if(b<i){
System.out.println("Your guess is too low. ");
} else if(b==i){
System.out.println("You win! ");
return;
}
System.out.print("Enter your third guess: ");
b = sc.next().charAt(0);
if(b>i){
System.out.println("Your guess is too high. ");
} else if(b<i){
System.out.println("Your guess is too low. ");
} else if(b==i){
System.out.println("You win! ");
}
if(b!=i){
System.out.println("You lose. The letter was " +i+ ".");
}
}
}

Store the character the user should guess in a variable outside the loop.
Then inside the loop ask them to attempt guess number i+1 where i is the loop counter (or you can change to using a 1 based index).
If execution continues after the loop then it means they lost.
Here is an example:
import java.util.Random;
import java.util.Scanner;
class Guess {
public static void main(String[] args) {
int maxGuesses = 3;
System.out.println("I'm thinking of a letter in the range a to j. You have " + maxGuesses + " guesses. ");
Random r = new Random();
char i = (char) (r.nextInt(10) + 'a');
Scanner sc = new Scanner(System.in);
String[] guessDescription = { "First", "Second", "Third" };
for (int g = 0; g < maxGuesses; g++) {
// use predefined guess description for 1-3, otherwise a generic description that works for any number of guesses above 3
if (g < guessDescription.length) {
System.out.print("Enter your " + guessDescription[g] + " guess:");
} else {
System.out.print("Enter guess #" + (g + 1) + ":");
}
char b = sc.next().charAt(0);
if (b > i) {
System.out.println("Your guess is too high. ");
} else if (b < i) {
System.out.println("Your guess is too low. ");
} else if (b == i) {
System.out.println("You win! ");
return;
}
}
System.out.println("You lose. The letter was " + i + ".");
}
}

you can use a nested loop.
this part is basically the same, and can be in inner loop (of 3 iterations)
System.out.print("Enter your ... guess: ")
char b = sc.next().charAt(0);
if(b>i){
System.out.println("Your guess is too high. ");
} else if(b<i){
System.out.println("Your guess is too low. ");
} else if(b==i){
System.out.println("You win! ");
return;
}
but the System.out.print("Enter your ... guess: ") is different every iteration. You can create const array of string with the strings {"first", "second", "third"} and access the correct string by the index of the loop (use format string here...)

Map your letters into a List<> or ArrayList<> then use for-each loop
Check this answer for a simple example of how to use for-each loop:

You just need to replace your line Enter your .... guess.
Based on i, you should keep a mapping like
{ 0:First,1:Second,2:Third}
Scanner sc = new Scanner(System.in);
System.out.println("I'm thinking of a letter in the range a to j. You have three guesses. ");
List < String > strList = new ArrayList <String> ( );
strList.add("FIRST");
strList.add("SECOND");
strList.add("THIRD");
Random r = new Random();
char randX = (char)(r.nextInt(10) + 'a');
for(int i = 0; i<3; i++){ //this is where I'm having trouble
System.out.print("Enter your"+ strList.get(i)+ " guess: ");
char b = sc.next().charAt(0);
if(b==i){
System.out.println("You win! ");
return;
}
else
{
if(b>randX)
{
System.out.println("Your guess is too high. ");
}
else
System.out.println("Your guess is too low. ");
if ( b !=randX && i==2 )
{
System.out.println("You lose. The letter was " + randX + ".");
}
}
}

Here is a quick example with a loop to play again if the game is over
class Guess {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Random r = new Random();
char toGuess;
char yourGuess;
boolean playing = true;
boolean lost = true;
while(playing) {
toGuess = (char) (r.nextInt(10) + 'a');
System.out.println("NEW GAME");
System.out.println("========");
System.out.println("I'm thinking of a letter in the range a to j. You have three guesses. ");
for (int j = 0; j < 3; j++) {
switch (j) {
case 0:
System.out.print("Enter your first guess: ");
break;
case 1:
System.out.print("Enter your second guess: ");
break;
case 2:
System.out.print("Enter your third guess: ");
break;
default:
System.out.println("Something went wrong. Game is closing!");
System.exit(0);
break;
}
yourGuess = sc.next().charAt(0);
if (yourGuess > toGuess) {
System.out.println("Your guess is too high.");
} else if (yourGuess < toGuess) {
System.out.println("Your guess is too low. ");
} else if (yourGuess == toGuess) {
System.out.println("You win! ");
lost = false;
break;
}
}
if(lost==false){
System.out.println("Sorry, you lost!");
}
System.out.print("Do you want to play again? (y=yes | n=no): ");
if(!sc.next().equals("y")){
playing=false;
}
}
}
}

Related

How to combine two programs in one class

I have created two games and now I am working on menu
It should run each game after user selected each of them
Menu Must look like this:
Hello! Type 'letter' or 'number' to choose game
Heres first game:
import java.util.Scanner;
public class GuessTheNumber {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String playAgain = "";
System.out.println("Guess a number between 1 and 100:");
int theNumber = (int)(Math.random() * 100 + 1);
int numberOfTries = 0;
int guess = 0;
while (guess != theNumber)
{
guess = scan.nextInt();
numberOfTries = numberOfTries + 1;
if (guess < theNumber)
System.out.println(guess + " is too low. Try again.");
else if (guess > theNumber)
System.out.println(guess + " is too high. Try again.");
else {
System.out.println(guess + " is correct. You win!");
System.out.println("It only took you " + numberOfTries + " tries! Good work!");
}
}
System.out.println("Would you like to play again (y/n)?");
playAgain = scan.next();
while (playAgain.equalsIgnoreCase("y"));
System.out.println("Thank you for playing! Goodbye.");
scan.close();
}
}
Heres the second
import java.util.Scanner;
public class GuessTheLetter {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String playAgain = "";
int numberOfTries = 0;
do {
System.out.println("Guess the Letter");
char randomLetter = (char) (Math.random() * 26 + 65);
char enteredLetter = 0;
while(true){
enteredLetter = Character.toUpperCase(scan.next().charAt(0));
numberOfTries = numberOfTries + 1;
if(enteredLetter==randomLetter)
{
System.out.println("Correct Guess");
System.out.println("The letter is:"+randomLetter);
System.out.println("It only took you " + numberOfTries + " tries! Good work!");
break;
}
else if(enteredLetter>randomLetter)
{
System.out.println("Incorrect Guess");
System.out.println("The letter entered is too high");
}
else if(enteredLetter<randomLetter)
{
System.out.println("Incorrect Guess");
System.out.println("The letter entered is too low");
}
}
System.out.println("Would you like to play again (y/n)?");
playAgain = scan.next();
} while (playAgain.equalsIgnoreCase("y"));
System.out.println("Thank you for playing! Goodbye.");
scan.close();
}}
Must i use multiple classes, or put everything into 1, how can i combine theese two games in one?
You can put each game into one function and then just call them in the main of that class. You do not need 2 classes for this. You can also add a condition that would decide which function to call.

Have trouble with a while loop and trying to terminate the program by a press of a letter

I have a problem with my program.
Program is a HILO game which requires the user to guess a number between a range of a generated number.
The problem is that once i press 0 on my keyboard, it reveals the random number, and essentially must end the loop and ask whether the user wants to continue or end the program. Instead, it continues the loop, and whenever I press a letter on the keyboard it shows me an Exception error which describes and input Miss Match. Can some one guide me on how to fix it?, maybe I wrote the program wrong, I tried multiple ways, it still doesn't work as it supposed to work.
Thank you.
import java.util.Scanner;
import java.util.Random;
import java.lang.Math;
public class HILOGAME
{
public static void firstGame()
{
final int range = 50;
int answer = 0;
int guesses;
int number;
int guessNum = 0;
String choice = "";
boolean Loop = false;
Scanner input = new Scanner(System.in);
Random r = new Random();
answer = r.nextInt(range) + 1;
System.out.println("IF YOU WISH TO GIVE UP, PRESS 0 ON THE KEYBOARD");
while (!Loop)
{
for (int exit = 0; exit < 10; exit++)
{
System.out.print("Guess a number between 1 and " + range + " : ");
number = input.nextInt();
guessNum = guessNum++;
guessNum += 1;
if (number == answer)
{
System.out.println(" Your guess was correct ");
System.out.println();
System.out.println("The number was: " + answer);
System.out.println("You guess the number with: " + guessNum + " guesses ");
System.out.println();
System.out.println("Enter x to continue to play or y to endgame");
choice = input.nextLine();
if (!choice.equalsIgnoreCase("x"))
{
Loop = true;
answer = r.nextInt(range) + 1;
System.out.print("A new number");
break;
}
else if (choice.equalsIgnoreCase("y"))
{
Loop = false;
System.out.print("END OF GAME");
exit = 11;
}
}
if (number > answer)
{
System.out.println("TOO HIGH");
}
if (number < answer)
{
System.out.println("TOO LOW");
}
if (number == 0)
{
System.out.println("YOU GAVE UP. THE NUMBER WAS " + answer);
System.out.println("Enter x to continue to play or y to endgame");
}
}
}
}
}
EDIT 1:
This code is working perfectly for me i have tried running it:
final int range = 50;
int answer = 0;
int guesses;
int number;
int guessNum = 0;
String choice = "";
boolean Loop = false;
Scanner input = new Scanner(System.in);
Random r = new Random();
answer = r.nextInt(range) + 1;
System.out.println("IF YOU WISH TO GIVE UP, PRESS 0 ON THE KEYBOARD");
while (!Loop)
{
int exit;
for (exit = 0; exit < 10; exit++)
{
System.out.print("Guess a number between 1 and " + range + " : ");
number = input.nextInt();
guessNum = guessNum++;
guessNum += 1;
if (number == answer)
{
System.out.println(" Your guess was correct ");
System.out.println();
System.out.println("The number was: " + answer);
System.out.println("You guess the number with: " + guessNum + " guesses ");
System.out.println();
System.out.println("Enter x to continue to play or y to endgame");
choice = input.next();
// HERE YOU ARE DOING THE WRONG THING
// What is the meaning of "not(!)" here ? !choice.equalsIgnoreCase("x")
// Remove "NOT(!)" from here your program will work as expected
if (choice.equalsIgnoreCase("x"))
{
//here you should assign loop to false if they continue
Loop = false;
answer = r.nextInt(range) + 1;
System.out.print("A new number");
break;
}
else if (choice.equalsIgnoreCase("y"))
{
//better to insert break here as well
//here you should assign loop to true if they wanna exit.
Loop = true;
System.out.print("END OF GAME");
exit = 11;
break;
}
}
else if (number > answer)
{
System.out.println("TOO HIGH");
}
else if (number < answer)
{
System.out.println("TOO LOW");
}
if (number == 0)
{
System.out.println("YOU GAVE UP. THE NUMBER WAS " + answer);
System.out.println("Enter x to continue to play or y to endgame");
// MADE CHANGES HERE
choice = input.next();
if (choice.equalsIgnoreCase("x"))
{
//here you should assign loop to false if they continue
Loop = false;
answer = r.nextInt(range) + 1;
System.out.print("A new number");
break;
}
else if (choice.equalsIgnoreCase("y"))
{
//better to insert break here as well
//here you should assign loop to true if they wanna exit.
Loop = true;
System.out.print("END OF GAME");
exit = 11;
break;
}
}
}
}
Please do copy-paste the code. Because it is working perfectly without any Exception..!!
My sample outputs:
SAMPLE 1:
Guess a number between 1 and 50 : 1
TOO LOW
Guess a number between 1 and 50 : 0
TOO LOW
YOU GAVE UP. THE NUMBER WAS 27
Enter x to continue to play or y to endgame
y
END OF GAME
SAMPLE 2:
Guess a number between 1 and 50 : 20
TOO HIGH
Guess a number between 1 and 50 : 19
TOO HIGH
Guess a number between 1 and 50 : 15
Your guess was correct
The number was: 15
You guess the number with: 3 guesses
Enter x to continue to play or y to endgame
x
A new numberGuess a number between 1 and 50 : 20
TOO LOW
Guess a number between 1 and 50 : 0
TOO LOW
YOU GAVE UP. THE NUMBER WAS 42
Enter x to continue to play or y to endgame
y
END OF GAME
Do let me know if there is any problem.
Well, if you wish to end a loop, you could use the break; command. It jumps out of a while or for loop. So you could use this if the number is 0:
if (number == 0)
{
System.out.println("YOU GAVE UP. THE NUMBER WAS " + answer);
System.out.println("Enter 'x' to continue to play or y to endgame");
choice = input.nextLine();
if(choice == "y")
{
break;
}
and add:
if(choice == "y") {break;} to the very end of the while(!Loop) loop.
And with the time when the answer is correct, you set Loop to false, which means !Loop would evaluate to true. You should change Loop = false to Loop = true when they decide to continue the game.
a small modification
public class HILOGAME {
public static void firstGame() {
final int range = 50;
int answer;
int number;
int guessNum = 0;
String choice = "";
Scanner input = new Scanner(System.in);
Random r = new Random();
answer = r.nextInt(range) + 1;
System.out.print("Guess a number between 1 and " + range + " : ");
number = input.nextInt();
if (number == answer) {
System.out.println(" Your guess was correct ");
System.out.println();
System.out.println("The number was: " + answer);
System.out.println("You guess the number with: " + guessNum + " guesses ");
System.out.println();
} else {
System.out.println("you entered a wrong value");
System.out.println("do you really want to try again? press y to continue or other alphabet to exit");
choice = input.next();
playAgain(choice);
}
}
public static void playAgain(String choice) {
if (choice.equalsIgnoreCase("Y")) {
firstGame();
} else {
System.out.println("you chose to quit");
System.exit(0);
}
}

Having issues with having a program re-run

I am writing a program that will ask the user to guess a random number 6 times. The program has to ask if they want to play again and will keep a running total of the wins/losses.
How would I have the program rerun?
heres the code:
import java.util.Scanner;
import java.util.Random;
public class Project {
public static void main(String[] args) {
String input;
double guess = 0;
int number;
double wins = 0;
double losses = 0;
String repeat;
Scanner keyboard = new Scanner(System.in);
Random randomNumbers = new Random();
System.out.println("Welcome to Higher/Lower!");
System.out.println("Enter your name: ");
input = keyboard.nextLine();
while(input.equalsIgnoreCase("yes")); {
number = randomNumbers.nextInt(100) + 1;
System.out.println("I've chosen my number, " + input + "You only have 6 tries, good luck!"); }
for(int num = 1; number != guess && number <= 6; num++) {
System.out.println("Enter guess " + num + ":");
guess = keyboard.nextDouble();
if(guess < number)
System.out.println("higher.");
else if(guess > number)
System.out.println("lower.");
else
System.out.println("Congratulations!"); }
if(guess == number) {
System.out.println("You guesses my number!"); wins++; }
if(guess != number) {
System.out.println("Sorry, " + input + " my number was " + number +
"You lose!"); losses++; }
System.out.println("Do you want to play again? (Yes/No): ");
repeat = keyboard.nextLine();
if(input.equalsIgnoreCase("no")); {
System.out.println("Thanks for playing!"); }
System.out.println(wins + " wins");
System.out.println(losses + " losses");
}
}
It is skipping over asking me if i want to play again or not and i dont know what kind of loop to use
Wihtout your code, I'm assuming this is what you need.
boolean doContinue = true;
do {
//guess random number 6 times
//do you want to continue?
// yes -> doContinue = true;
// no -> doContinue = false;
} while (doContinue );
I would suggest making your loop a do-while loop like this:
do {
for (int i=0; i<6; i++){
/*
insert code for the guessing/checking/etc.
*/
}
System.out.print("Would you like to continue? [Y/n] ");
} while (scan.next().toUpperCase().charAt(0) != 'Y');

Blackjack.java while loop input validation

I am creating a simple Blackjack java program and I am stumped with the while loop input validation. When a user is requested to draw a card, he/she has the option: (y/n) to choose from as well as if they want to play again. My problem is when I am prompted to draw a card and I choose y, that character only should prompt a card draw...but it seems as if any character would do that trick. The same goes for the play loop if I want to play again. Also when I am prompted to play again I want to return to the beginning of the while loop but I can't seem to call on that function. I need help! Here is my code:
import java.util.Random;
import java.util.Scanner;
public class BlackJack
{
public static void main(String[] args)
{
char play = 'y';
char drawAgain;
int card1, card2;
int nextCard = 0;
Scanner keyboard = new Scanner(System.in);
Random number = new Random();
while (play != 'n')
{
card1 = number.nextInt(10) + 1;
card2 = number.nextInt(10) + 1;
System.out.print("First cards: ");
System.out.println(card1 + ", " + card2);
int cardTotal = card1 + card2;
System.out.println("Total: " + cardTotal);
System.out.print("Draw again? (y/n): ");
drawAgain = keyboard.next().charAt(0);
while (drawAgain != 'n')
{
int card3 = number.nextInt(10) + 1;
System.out.println("Card: " + card3);
cardTotal += card3;
System.out.println("Total: " + cardTotal);
if (cardTotal <= 21) {
System.out.print("Draw Again? (y/n): ");
drawAgain = keyboard.next().charAt(0);
}
if (cardTotal > 21) {
System.out.println("Bust");
System.out.print("Would you like to play again? (y/n): ");
play = keyboard.next().charAt(0);
}
}
}
}
}
There's a few problems with this code.
You will incur an infinite for loop because the drawAgain is never reset to n if the the points value is > 21.
In order to enforce the user must specify either a yes or no, you must check for it. Below does so with a while loop.
The play variable is never reset which forces the user to play until busting, then choose if want to keep playing or not.
The below addresses these issues. This should be what you want.
import java.util.Random;
import java.util.Scanner;
public class BlackJack
{
public static char getValidInput(){
Scanner keyboard = new Scanner(System.in);
String input = keyboard.next();
while(!input.equals("yes") || !input.equals("no")){
System.out.println("please input yes or no");
input = keyboard.next();
}
return input.charAt(0);
}
public static void main(String[] args)
{
char play = 'y';
char drawAgain;
int card1, card2;
int nextCard = 0;
Random number = new Random();
while (play != 'n')
{
card1 = number.nextInt(10) + 1;
card2 = number.nextInt(10) + 1;
System.out.print("First cards: ");
System.out.println(card1 + ", " + card2);
int cardTotal = card1 + card2;
System.out.println("Total: " + cardTotal);
System.out.print("Draw again? (y/n): ");
drawAgain = getValidInput();
while (drawAgain != 'n')
{
int card3 = number.nextInt(10) + 1;
System.out.println("Card: " + card3);
cardTotal += card3;
System.out.println("Total: " + cardTotal);
if (cardTotal <= 21) {
System.out.print("Draw Again? (y/n): ");
drawAgain = getValidInput();
}else{ //if (cardTotal > 21) {
System.out.println("Bust");
drawAgain ='n';
}
}
play = getValidInput();
}
}
}

Very simple game about Guessing The Number

/hello, I am trying to learn how to use "break" commend in java as well as continuing loop with "y or n" choice. I am writing this game Guessing Number and I have some trouble with "y" choice. I will try to explain, to write a game of guessing number was easy so I started to add some conditions like the possibility on the and to play again or not, later I was thinking that would be more interesting if I add possibility to quit any time player wish, but that does not working correctly. Please help, thats my code
package guessinggame;
import java.util.Random;
import java.util.Scanner;
/**
*
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println(" Welcome ");
Random rand = new Random();
Scanner input = new Scanner(System.in);
boolean play_again = true;
while (play_again)
{
int number_guess = rand.nextInt(100)+1;
int number_of_tries = 0;
int guess;
String another = "y";
boolean win = false;
while (win == false)
{
System.out.println(" Try too guess a number between 1 and 100 ");
guess = input.nextInt();
number_of_tries++;
if (guess == number_guess)
{
win = true;
}
else if (guess < number_guess)
{
System.out.println(" Guess is too low " + "\n Guess another number to continue or n to quit ");
if (input.hasNext("n"))
{
play_again = false;
break;
}
}
else if (guess > number_guess)
{
System.out.println(" Guess is too high " + "\n Guess another number to continue or n to quit ");
if (input.hasNext("n"))
{
play_again = false;
break;
}
}
}
System.out.println(" You Win!!! ");
System.out.println(" The number was " + number_guess);
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? (y/n): ");
if (another.equalsIgnoreCase("y") == true)
play_again = true;
else
{
play_again = false;
}
}
}
}
Here is an alternative that achieves that same outcome
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
System.out.println(" Welcome ");
Random rand = new Random();
Scanner input = new Scanner(System.in);
int guess = 0;
int number_of_tries = 0;
System.out.println(" Try too guess a number between 1 and 100 -1 to close");
guess = input.nextInt(); //get first input
while (guess != -1)
{
int number_guess = rand.nextInt(5) + 1;
++number_of_tries;
//check if user wins and exits loop
if (isWin (number_guess,guess))
{
System.out.println(" You Win!!! ");
System.out.println(" The number was " + number_guess);
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? [1 yes/ -1 no]: ");
guess = input.nextInt();
if (guess == -1)
break;
else
System.out.println(" Try too guess a number between 1 and 100 -1 to close");
}
else if (number_guess < guess )
{
System.out.println(" Guess is too High " + "\n Guess another number to continue or -1 to quit ");
guess = input.nextInt();
continue;
}
else if (number_guess > guess)
{
System.out.println(" Guess is too low " + "\n Guess another number to continue or -1 to quit ");
guess = input.nextInt();
continue;
}
}
System.out.println ("bye bye");
}
public static boolean isWin (int number,int guess)
{
return (number == guess) ? true :false;
}
}
You forgot to wait for user input after this statement:
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? (y/n): ");
E.g. you could try next approach:
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? (y/n): ");
if (input.hasNext()) {
if (another.equalsIgnoreCase("y")) {
play_again = true;
input.next();
} else {
play_again = false;
}
}
It looks like your braces are messed up for your play again if statement
This will work.
package aa;
import java.util.Random;
import java.util.Scanner;
public class abc {
public static void main(String[] args) {
System.out.println(" Welcome ");
Random rand = new Random();
Scanner input = new Scanner(System.in);
boolean play_again = true;
while (play_again)
{
int number_guess = rand.nextInt(100)+1;
int number_of_tries = 0;
int guess;
String another = "y";
boolean win = false;
while (win == false)
{
System.out.println(" Try too guess a number between 1 and 100 ");
guess = input.nextInt();
number_of_tries++;
if (guess == number_guess)
{
win = true;
break;
}
else if (guess < number_guess)
{
System.out.println(" Guess is too low " + "\n Guess another number to continue or n to quit ");
if (input.hasNext("n"))
{
play_again = false;
break;
}
}
else if (guess > number_guess)
{
System.out.println(" Guess is too high " + "\n Guess another number to continue or n to quit ");
if (input.hasNext("n"))
{
play_again = false;
break;
}
}
}
input.next();
if (win == true){
System.out.println(" You Win!!! ");
}
else{
System.out.println(" Good Luck Next Time!!! ");
System.out.println(" The number was " + number_guess);
}
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? (y/n): ");
another = input.next();
if (another.equalsIgnoreCase("y") == true)
play_again = true;
else
{
play_again = false;
}
}
System.out.println("Thank you!!!");
}
}

Categories

Resources