Here is a simple java number guessing game.
After the game has finished I would like to ask the user whether he wants to play again like: Do you want to play again? (Answer with Y/N) If the user inputs Y the game will restart and random a new number, if he reply with 'N ' the game will end. Here's my code :
import static java.lang.Math.*;
import java.util.Scanner;
public class HomeWorkLoopGame1 {
public static void main(String[] args) {
System.out.print("Welcome to number guessing game !\n");
System.out.println("Guess a number range from 1 to 100, You have 5 guess to win this game");
int answer = (int) (random()*100);
Scanner guess1 = new Scanner (System.in);
System.out.println("To begin please input your number");
int num1 = guess1.nextInt();
if (num1<answer) {
System.out.print(num1);
System.out.print(" Your answer is too small\n");
System.out.println("Try again! Please input your second guess");
}
else if (num1>answer){
System.out.println(num1);
System.out.print("Your answer is too big\n");
System.out.println("Try again! Please input your second guess");
}
else {
System.out.println("Congratulation! Your answer is correct! You win !");
}
int num2 = guess1.nextInt();
if (num2<answer) {
System.out.print(num2);
System.out.print(" Your answer is too small\n");
System.out.println("Try again! Please input your third guess");
}
else if (num2>answer){
System.out.println(num2);
System.out.print("Your answer is too big\n");
System.out.println("Try again! Please input your third guess");
}
else {
System.out.println("Congratulation! Your answer is correct! You win !");
}
int num3 = guess1.nextInt();
if (num3<answer) {
System.out.print(num3);
System.out.print(" Your answer is too small\n");
System.out.println("Try again! Please input your fourth guess");
}
else if (num3>answer){
System.out.println(num3);
System.out.print("Your answer is too big\n");
System.out.println("Try again! Please input your fourth guess");
}
else {
System.out.println("Congratulation! Your answer is correct! You win !");
}
int num4 = guess1.nextInt();
if (num4<answer) {
System.out.print(num4);
System.out.print(" Your answer is too small\n");
System.out.println("Try again! Please input your final guess");
}
else if (num4>answer){
System.out.println(num4);
System.out.print("Your answer is too big\n");
System.out.println("Try again! Please input your final guess");
}
else {
System.out.println("Congratulation! Your answer is correct! You win !");
}
int num5= guess1.nextInt();
if (num5<answer) {
System.out.print(num5);
System.out.print(" Your answer is too small\n");
System.out.println("Game Over");
}
else if (num5>answer){
System.out.println(num5);
System.out.print("Your answer is too big\n");
System.out.println("Game Over");
}
else {
System.out.println("Congratulation! Your answer is correct! You win !");
}
System.out.println("Correct Answer is "+ answer);
Scanner userReply = new Scanner (System.in);
char reply;
System.out.println("Do you want to play again? Answer with Y/N)");
}
}
You can try something like this. By the way this is not a good way to do this.
Scanner userReply = new Scanner(System.in);
System.out.println("Do you want to play again? Answer with Y/N)");
String answer= userReply.nextLine().toLowerCase();
if("y".equals(answer)){
main(args); // recursively call
}else {
System.out.println("game exit");
}
You can use do-while to do it in proper way.
Better way
public static void main(String[] args) {
boolean isValid;
do {
isValid = true;
runGame();
Scanner userReply = new Scanner(System.in);
System.out.println("Do you want to play again? Answer with (Y/N)");
String answer = userReply.nextLine().toLowerCase();
if ("y".equals(answer)) {
isValid =true;
} else {
isValid =false;
System.out.println("game exit");
}
} while (isValid);
}
public static void runGame() {
// your game logic
}
It is better (I think) to make a method for the play function.
public static void main(String[] args) {
playGame ();
System.out.print("Enter something:");
String input = System.console().readLine();
if (input=="y"){
playGame();
} else {
System.exit(0);
}
}
private void playGame() {
System.out.print("Welcome to number guessing game !\n");
System.out.println("Guess a number range from 1 to 100, You have 5 guess to win this game");
int answer = (int) (random()*100);
Scanner guess1 = new Scanner (System.in);
....
System.out.println("Correct Answer is "+ answer);
Scanner userReply = new Scanner (System.in);
char reply;
System.out.println("Do you want to play again? Answer with Y/N)");
}
You can call the main method for the class and create an instance of the class as so:
HomeWorkLoopGame1 variable = new HomeWorkLoopGame1();
HomeWorkLoopGame1.main(args);
Basically, it runs the game again from scratch - as if the player were starting to play the game again for the first time.
It would be something like this:
Scannner in = new Scanner(System.in);
System.out.println("Do you want to play again? Answer with Y/N");
String answer = in.nextLine().toLowerCase();
if(answer.equals.("Y")){
HomeWorkLoopGame1 variable = new HomeWorkLoopGame1();
HomeWorkLoopGame1.main(args);
}
else{
//exit
}
However I haven't tested this so I'm not 100% sure it might work. Best of luck
Edit:
- Wrap the code in a for loop to repeat it numerous times rather than just once
Just put a do-while loop inside your main method.
As the first line put:
do {
Immediately after System.out.println("Do you want to play again? Answer with Y/N)"); put:
while (reply=='Y' or reply=='y');
You'll need to make sure you're reading in the reply properly etc of course.
You could do the whole thing in a loop:
public static void main(String[] args) {
while (true) {
// your code goes here
System.out.println("Do you want to play again? Answer with Y/N)");
try {
char reply;
reply = (char) System.in.read(); // read a char
if (Character.toLowerCase(reply) != 'y') // when equals to Y break the loop
break;
} catch (Exception e) {
e.printStackTrace();
}
}
}
I tried not to change too much of your original code. I added a few while loops, some comments and additional code to handle the user's response. I hope it helps.
import static java.lang.Math.*;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
boolean play = true;
boolean notCorrect = true;
while (play) {
while (notCorrect) {
System.out.print("Welcome to number guessing game !\n");
System.out.println("Guess a number range from 1 to 100, You have 5 guess to win this game");
int answer = (int) (random() * 100);
Scanner guess1 = new Scanner(System.in);
//Guess 1
System.out.println("To begin please input your number");
int num1 = guess1.nextInt();
if (num1 < answer) {
System.out.print(num1);
System.out.print(" Your answer is too small\n");
System.out.println("Try again! Please input your second guess");
} else if (num1 > answer) {
System.out.println(num1);
System.out.print("Your answer is too big\n");
System.out.println("Try again! Please input your second guess");
} else {
System.out.println("Congratulation! Your answer is correct! You win !");
break;
}
//Guess 2
int num2 = guess1.nextInt();
if (num2 < answer) {
System.out.print(num2);
System.out.print(" Your answer is too small\n");
System.out.println("Try again! Please input your third guess");
} else if (num2 > answer) {
System.out.println(num2);
System.out.print("Your answer is too big\n");
System.out.println("Try again! Please input your third guess");
} else {
System.out.println("Congratulation! Your answer is correct! You win !");
break;
}
//Guess 3
int num3 = guess1.nextInt();
if (num3 < answer) {
System.out.print(num3);
System.out.print(" Your answer is too small\n");
System.out.println("Try again! Please input your fourth guess");
} else if (num3 > answer) {
System.out.println(num3);
System.out.print("Your answer is too big\n");
System.out.println("Try again! Please input your fourth guess");
} else {
System.out.println("Congratulation! Your answer is correct! You win !");
break;
}
//Guess 4
int num4 = guess1.nextInt();
if (num4 < answer) {
System.out.print(num4);
System.out.print(" Your answer is too small\n");
System.out.println("Try again! Please input your final guess");
} else if (num4 > answer) {
System.out.println(num4);
System.out.print("Your answer is too big\n");
System.out.println("Try again! Please input your final guess");
} else {
System.out.println("Congratulation! Your answer is correct! You win !");
break;
}
//Guess 5
int num5 = guess1.nextInt();
if (num5 < answer) {
System.out.print(num5);
System.out.print(" Your answer is too small\n");
System.out.println("Game Over");
} else if (num5 > answer) {
System.out.println(num5);
System.out.print("Your answer is too big\n");
System.out.println("Game Over");
} else {
System.out.println("Congratulation! Your answer is correct! You win !");
break;
}
System.out.println("Correct Answer is " + answer);
break;
} // while(correct)
Scanner userReply = new Scanner(System.in);
String reply;
System.out.println("Do you want to play again? Answer with (Y/N)");
reply = userReply.next().toLowerCase();
if (reply.equals("y")) {
play = true;
} else if (reply.equals("n")) {
play = false;
} else {
System.out.println("Invalid choice.");
break;
}
} // while(play)
} // main()
} // class Test
Related
This question is similar to a question I had previously about loops taking my enter key as input. For my class, I need to write a program that is a number-guessing game that whenever the user enters correctly, the loop ends. But I run into the problem as the enter key being taken as input. How can I stop this from occurring? Here is my code I have so far.
String secretNumber = "6";
String guess = "";
while(!guess.equals(secretNumber)) {
System.out.println("Guess a number between 1 and 10");
guess = scan.next();
if(guess == "6") {
System.out.println("You Win!");
}
else if(guess == "5") {
System.out.println("Try again!");
}
else if(guess == "4") {
System.out.println("Try again!");
}
else if(guess == "3") {
System.out.println("Try again!");
}
else if(guess == "2") {
System.out.println("Try again!");
}
else if(guess == "1") {
System.out.println("Try again!");
}
else if(guess == "7") {
System.out.println("Try again!");
}
else if(guess == "8") {
System.out.println("Try again!");
}
else if(guess == "9") {
System.out.println("Try again!");
}
else if(guess == "10") {
System.out.println("Try again!");
}
else {
System.out.println("You did not enter a number between 1 and 10");
}
}
}
}
If you use == operator it doesn't compare the value of the string. So to check if a string's value equals to another, you must use string.equals(anotherString) method. In your case your code should be like :
String secretNumber = "6";
String guess = "";
while(!guess.equals(secretNumber)) {
System.out.println("Guess a number between 1 and 10");
guess = scan.next();
if(guess.equals("6")) {
System.out.println("You Win!");
}
else if(guess.equals("5")) {
System.out.println("Try again!");
}
..........
Also to refactor the code this version is more readable and simpler.
String secretNumber = "6";
String guess = guess = scan.next();
System.out.println("Guess a number between 1 and 10");
while(!guess.equals(secretNumber)) {
if(guess.equals(secretNumber)) {
System.out.println("You Win!");
break;
}
else{
System.out.println("Try again!");
}
First Strings are compared by equals second you need to learn how to reduce your code because while(!guess.equals(secretNumber)) will continue until 6 is entered so it will print anything inside it you we just print Try Again
public class GuessIt{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String secretNumber = "6";
String guess = "";
System.out.println("Guess a number between 1 and 10");
guess = scan.next();
while(!guess.equals(secretNumber)) {
System.out.println("Try again");
System.out.println("Guess a number between 1 and 10");
guess = scan.next();
}
System.out.println("You guessed it");
}
}
While your code is not the best way to implement a guessing game, I will play along if it helps you.
I don't entirely know what you mean by the enter key being taken as input. Are you typing a value into the terminal before you press enter?
String secretNum = 6;
String guess = "";
System.out.println("Guess a number between 1 and 10");
while(!guess.equals(secretNum)) {
guess = scan.next();
if(Integer.parseInt(guess)>10 || Integer.parseInt(guess)<1) {
System.out.println("Re-enter a number between one and ten");
}
}
System.out.println("You guessed it!");
is there a way to declare a char early on but use it only later, because when i try to declare it as 0 early on then it will just cause an error because the answer of while is supposed to be 'Y'. i could get it to loop and play again by asking the question before playing but I only want it to ask the option to play again at the end of the game. would appreciate it if anyone could tell me how to get this to work, thank you.
public class soodsami_a3 {
public static void main(String[] args) {
Scanner sam = new Scanner(System.in);
// Random number generator
int Randomizer = (int)(Math.random() * 100) + 1;
while (playagain == 'y') {
System.out.println("I'm thinking of a number between 1 and 100");
System.out.println("What is it?");
System.out.print("Guess: ");
int Useranswer = sam.nextInt();
while (Useranswer != Randomizer) {
if (Useranswer < Randomizer) {
System.out.println("Too low.");
System.out.print("Guess: ");
Useranswer = sam.nextInt();
} else if (Useranswer > Randomizer) {
System.out.println("Too high.");
System.out.print("Guess: ");
Useranswer = sam.nextInt();
}
if (Useranswer == Randomizer) {
System.out.println("You got it!");
}
System.out.print("would you like to play again (Y/N) ");
char playagain = sam.next().toUpperCase().charAt(0);
}
}
System.out.println("Thanks for playing");
}
}
public static void main(String[] args) {
// ...
char playagain = 'y';
while (playagain == 'y') {
// ...
playagain = scan.next().toLowerCase().charAt(0);
}
System.out.println("Thanks for playing");
}
It would be a better practice to have playagain as a boolean and have it set to false on initialization. Then use a do-while cycle, to have the condition evaluated at the end of the cycle, so that it runs at least once
boolean playAgain = false;
do {
System.out.println("I'm thinking of a number between 1 and 100");
//..other code..
playAgain = sam.next().toUpperCase().charAt(0) == 'Y';
} while (playAgain);
package oddsorevens;``
import java.util.Scanner;
import java.util.Random;
public class OddsOrEvens
{
public static void main(String[] args)
{
Scanner name= new Scanner (System.in); // getting input from user
System.out.print("Hi! What's your name: ");
String user = name.nextLine(); // getting user name
System.out.println("Hello: "+user);
System.out.println("Let's play OddsOrEvens");
System.out.println("Choose Odd or Even");
String s ="oddOrEven";
Scanner str = new Scanner(System.in); // getting new string from user
String s1 = str.next(); //storing odd or even here
o:
if (s1.equals("even")||(s1.startsWith("e")))
{
System.out.println("You choose even");
System.out.println("Computer choose odd");
}
else if (s1.equals("odd")||(s1.startsWith("o")))
{
System.out.println("You choose odd");
System.out.println("Computer choose even");
}
else
{
System.out.println("Entered wrong keyword");
}
System.out.print("How many fingers you want to put out: ");
Scanner num = new Scanner(System.in);
int n=num.nextInt();
Random rand = new Random();
int computer = rand.nextInt(6);
System.out.println("Computer choose "+ computer +" fingers");
int sum;
sum=n+computer;
System.out.println(sum);
if(sum%2==0)
{
System.out.println(sum+" is even");
}
else
{
System.out.println(sum+" is odd");
}
int u = s1.length();
if(u/2==0)
{
System.out.println("You won :)");
}
else
{``
System.out.println("You lose :(");
}
}
}
This is my first pgm in java. here if the user enter wrong keyword pgm should be break and based on the user input the output of the pgm will be win or lose. help please.
Whenever you want your application to stop, you have to explicitly tell that you want to exit. To do so you have write just piece of line of code and that is System.exit(0)
Here sample code to understand it better:
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
if (s.next().equals("o")) {
System.out.println("game is still on");
} else {
System.out.println("game end!");
System.exit(0);
}
}
This is the output of the program
I was able to do till to get this result by doing this program below
import java.util.Scanner;
public class aLittleQuiz {
public static void main(String[] args) {
// declaring varibles
String quizStart;
int quizAns1, quizAns2, quizAns3;
Scanner input = new Scanner(System.in);
System.out.println("Are you ready for a quiz? (y / n)");
quizStart = input.next();
System.out.println("Okay, here it comes!");
// quiz answer 1
System.out.println("\nWhat is the capital of Alaska? \n1) Melbourne\n2) Anchorage\n3) Juneau");
quizAns1 = input.nextInt();
if (quizAns1 == 3) {
System.out.println("That's right");
} else {
System.out.println("Your answer is wrong, sorry!");
}
// quiz answer 2
System.out.println("Q2) Can you store the value ''cat'' in a variable of type int? \n1) yes \n2) no");
quizAns2 = input.nextInt();
if (quizAns2 == 1) {
System.out.println("Sorry, ''cat'' is a string. ints can only store numbers.");
} else if (quizAns2 == 2) {
System.out.println("Correct!");
}
// quiz answer 3
System.out.println("What is the result of 9+6/3? \n1) 5\n2) 11 \n3) 15/3");
quizAns3 = input.nextInt();
if (quizAns3 == 2) {
System.out.println("That's correct!");
} else {
System.out.println("");
}
// if (quizAns == 3 && quizAns == ) {
// }
}
}
but how I can program this part?
"Overall, you got 2 out of 3 correct.
Thanks for playing!"
Declare a variable like int marks and increment it by one inside if\else block(which made for correct answer). And at the end print
System.out.println("Overall, you got" +marks+" out of 3 correct. Thanks for playing!");
Assuming your no of question is fixed( 3 )
String quizStart;
int quizAns1, quizAns2, quizAns3;
int marks=0;
Scanner input = new Scanner(System.in);
System.out.println("Are you ready for a quiz? (y / n)");
quizStart = input.next();
System.out.println("Okay, here it comes!");
// quiz answer 1
System.out.println("\nWhat is the capital of Alaska? \n1) Melbourne\n2) Anchorage\n3) Juneau");
quizAns1 = input.nextInt();
if (quizAns1 == 3) {
System.out.println("That's right");
++marks;
} else {
System.out.println("Your answer is wrong, sorry!");
}
// quiz answer 2
System.out.println("Q2) Can you store the value ''cat'' in a variable of type int? \n1) yes \n2) no");
quizAns2 = input.nextInt();
if (quizAns2 == 1) {
System.out.println("Sorry, ''cat'' is a string. ints can only store numbers.");
} else if (quizAns2 == 2) {
System.out.println("Correct!");
++marks;
}
// quiz answer 3
System.out.println("What is the result of 9+6/3? \n1) 5\n2) 11 \n3) 15/3");
quizAns3 = input.nextInt();
if (quizAns3 == 2) {
System.out.println("That's correct!");
++marks;
} else {
System.out.println("");
}
System.out.println("Overall, you got " +marks+" out of 3 correct. Thanks for playing!");
I'm making a guessing game, all the code works fine except for that I want them to make a number to guess between, I can't seem to figure out how to make it so that if the user inputs a letter like "d" instead of a number like "15" it will tell them they can't do that.
Code:
import java.util.Scanner;
import java.util.Random;
public class GuessingGame {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
while (true) {
System.out.print("Pick a number: ");
int number = input.nextInt();
if (number != int) {
System.out.println("That's not a number");
} else if (number == int) {
int random = rand.nextInt(number);
break;
}
}
System.out.println("You have 5 attempts to guess the number or else you fail. Goodluck!");
System.out.println("");
System.out.println("Type 'begin' to Begin!");
System.out.print("");
String start = input.next();
if (start.equals("begin")) {
System.out.print('\f');
for(int i=1; i<6; i++) {
System.out.print("Enter a number between 1-" + number + ": ");
int number = input.nextInt();
if (number > random) {
System.out.println("Too Big");
System.out.println("");
} else if (number < random) {
System.out.println("Too Small");
System.out.println("");
} else if (number == random) {
System.out.print('\f');
System.out.println("Correct!");
break;
}
if (i == 5) {
System.out.print('\f');
System.out.println("You have failed");
System.out.println("Number Was: " + random);
}
}
} else if (start != "begin") {
System.out.print('\f');
System.out.println("Incorrect Command");
System.out.println("Please Exit Console And Retry");
}
}
}
use try catch
for example
try{
int a=sc.nextInt();
}catch(Exception e){
System.out.println("not an integer");
}
You could use nextLine() instead of nextInt() and check the out coming String if it matches() the regular expression [1-9][0-9]* and then parse the line with Integer.valueOf(str).
Like:
String str=input.nextLine();
int i=0;
if(str.matches("[1-9][0-9]*"){
i=Integer.valueOf(str);
} else {
System.out.println("This is not allowed!");
}
I hope it helps.
Do something like this:
Scanner scan = new Scanner(System.in);
while(!scan.hasNextInt()) { //repeat until a number is entered.
scan.next();
System.out.println("Enter number"); //Tell it's not a number.
}
int input = scan.nextInt(); //Get your number here