Guessing a number - java

I want to create a program that gives you three tries to find any given number. It's going to essentially be a guessing game. The problem is, I have to do this without any loops. So far, I'm only able to get input from the user, read that input and tell them if they've won or 'lost' the game. The program only runs once and stops(as expected).
I was told that it could be done without loops, albeit with a lot more code. Can you guys let me know what I'm doing wrong here and give me some pointers on what I should change? If you need clarification let me know.
Thanks.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner ran = new Scanner(System.in);
System.out.println("Enter a number: ");
int x = ran.nextInt();
if (x < 3) {
System.out.println("Too low. Try again.");
System.out.println("Enter a number: ");
} else if (x > 3) {
System.out.println("Too high. Try again");
} else if(x == 3) {
System.out.println("You win. Nice job.");
} else {
System.out.println("You lose");
}
System.out.println("Number Guessing Game (c) 2017 Anna Gibson");
}
}

You can do this using recursion. See this program. Find explanations within comments.
import java.util.Scanner;
public class HelloWorld {
private static Scanner ran = new Scanner(System.in);
//this is number of tries you want to give to user
private static int counter = 5;
//The actual number
private static final int NUM = 3;
public static boolean guessingMachine() {
//counter indicates that number of attempts remaining
if(counter == 0) {
return false;
}
counter--;
System.out.println("Enter a number: ");
int x = ran.nextInt();
if (x < NUM) {
System.out.println("Too low. Try again.");
//try again... call this method again
return guessingMachine();
} else if (x > NUM) {
System.out.println("Too high. Try again");
//try again... call this method again
return guessingMachine();
} else {
//x == NUM success
return true;
}
}
public static void main(String[] args) {
boolean result = guessingMachine();
if(result)
System.out.println("You win. Nice job.");
else
System.out.println("You lose");
System.out.println("Number Guessing Game (c) 2017 Anna Gibson");
}
}

You could next conditions:
get user input
if input is correct, congratulation user and exit
else
get user input //second attempt
if input is correct, congratulation user and exit
...
You can continue from there. The code you provided, where you tell the user if they are too high or low, would have to be included in each of the branches of the pseudocode above.

I think the main purpose of this exercise is intended for you to strengthen your nested if-else concepts.
import java.util.Scanner;
public class HelloWorld{
public static void main(String []args){
int num=3;
int count=1;
Scanner ran = new Scanner(System.in);
System.out.println("Enter a number: ");
int x = ran.nextInt();
if(x>num || x<num)
{
System.out.println("incorrect guess");
count++;
System.out.println("Enter a number: ");
x = ran.nextInt();
if(x>num || x<num)
{
System.out.println("incorrect guess");
count++;
System.out.println("Enter a number: ");
x = ran.nextInt();
if(x>num || x<num)
{
System.out.println("incorrect guess YOU LOSE");
}
else
{
System.out.println("YOU WIN");
}
}
else
{
System.out.println("YOU WIN");
}
}
if(x==num && count==1)
{
System.out.println("YOU WIN");
}
System.out.println("Number Guessing Game (c) 2017 Anna Gibson");
}
}

Related

How do i add an play again option to this java code?

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);

Guessing game with integer input validation and number of right guessed answers displayed Java

I'm building a dice guessing game. the program has 5 die tosses. I've implemented hasNextInt() as it is the only one I can understand at the moment.
When I enter something that's not an Int it breaks out of the code but I want the program to continue for the rest of the goes (out of 5).
Also If the user guesses correctly I have to keep track of how many they get right.
If they guess wrong I have let them know what the die toss was, this keeps returning the first wrong die toss for the five goes.
At the end I have let the player know how many they got right out of 5.
This is my code so far
import java.util.Scanner;
public class Attempt11
{
public static void main(String args[]) {
int attempt = 1;
int userGuessNumber = 0;
int secretNumber = (int) (Math.random() * 6) + 1;
Scanner userInput = new Scanner(System.in);
System.out.println("Guess the next dice throw (1-6)");
do {
if (userInput.hasNextInt()) {
userGuessNumber = userInput.nextInt();
if (userGuessNumber == secretNumber) {
System.out.println("Congratulations you guessed right");
continue;
} else if (userGuessNumber < 1) {
System.out.println("Number must be between 1 and 6 inclusive, please try again ");
} else if (userGuessNumber > 6) {
System.out.println("Number must be between 1 and 6 inclusive, please try again ");
} else if (userGuessNumber > secretNumber) {
System.out.println("Hard luck the last throw was " + secretNumber);
} else if (userGuessNumber < secretNumber) {
System.out.println("Hard luck the last throw was " + secretNumber);
}
if (attempt == 5) {
System.out.println("You have exceeded the maximum attempt. Try Again");
break;
}
attempt++;
} else {
System.out.println("Enter a Valid Integer Number");
break;
}
} while (userGuessNumber != secretNumber);
userInput.close();
}
}

Simple Java Guessing program. Continuing

I am just playing around with java and wanted to make a simple program where the user; me has to guess/type in the correct number until it's correct. What can I do so the program can keep running, printing out "Make another guess" until the user/me puts in the correct number. Maybe a boolean? I'm not sure. This is what I have so far.
import java.util.Scanner;
public class iftothemax {
public static void main(String[] args) {
int myInt = 2;
// Create Scanner object
Scanner input = new Scanner(System.in);
//Output the prompt
System.out.println("Enter a number:");
//Wait for the user to enter a number
int value = input.nextInt();
if(value == myInt) {
System.out.println("You discover me!");
}
else {
//Tell them to keep guessing
System.out.println("Not yet! You entered:" + value + " Make another guess");
input.nextInt();
}
}
You might want to use a while loop to repeat some code:
while (value != myInt) {
System.out.println("Not yet! You entered: " + value + ". Make another guess");
value = input.nextInt();
}
System.out.println("You discovered me!");
This program would do the trick:
public static void main(String [] args){
int myInt = 2;
int value = 0;
Scanner input = new Scanner(System.in);
boolean guessCorrect = false;
while(!guessCorrect){
System.out.println("Not yet! You entered:" + value + " Make another guess");
value = input.nextInt();
if(value == myInt){
guessCorrect = true
}
}
System.out.println("You discover me!");
}
Simply introduce a loop.
import java.util.Scanner;
public class iftothemax {
public static void main(String[] args) {
int myInt = 2;
// Create Scanner object
Scanner input = new Scanner(System.in);
for(;;) {
//Output the prompt
System.out.println("Enter a number:");
//Wait for the user to enter a number
int value = input.nextInt();
if(value == myInt) {
System.out.println("You discover me!");
break;
}
else {
//Tell them to keep guessing
System.out.println("Not yet! You entered:" + value + " Make another guess");
}
}
}
}

How can I code a console-based Java game to replay when the user types in "1"?

First of all, I'd like to say that I am REALLY new to all of this... I've tried learning as much as I can, so apologies if any of my code seems ridiculous or all-over-the-place, but I needed somewhere to start. (By the way, credit to the very base of this code goes to CrossCoastGaming: http://tinyurl.com/kktyq4e).
Now to the matter at hand. I have improved (for lack of a better word) on the coding that the man in the video shows, by adding several different phrases, making use of variables and adding a try counter. Here is my code:
import java.util.Random;
import java.util.Scanner;
public class Main {
public static int number, guess, tryCount, replay;
public static int maxValue =1;
public static Scanner scan;
public static Random rand;
public static void main(String args[]) {
scan = new Scanner(System.in);
rand = new Random();
System.out.print("Enter a maximum number: ");
while(maxValue < 2)
maxValue = scan.nextInt();
number = rand.nextInt(maxValue);
System.out.print("Guess a number from 1 to " + maxValue + ": ");
while (guess != number) {
guess = scan.nextInt();
tryCount++;
if (guess < 1) {
System.out.print("Guess is not positive. Try again: ");
}else if (guess < number) {
System.out.print("Too low! Try again: ");
}
if (guess > maxValue) {
System.out.println("Guess is higher than " + maxValue + ". Try again: ");
}else if (guess > number) {
System.out.print("Too high! Try again: ");
}
}
if (tryCount == 1) {
System.out.println("Nailed it! It only took you 1 try!");
}
else {
System.out.println("Nailed it! It took you " + tryCount + " tries.");
}
System.out.println("Type 0 to play again. Type 1 to quit.");
if (replay == 1) {
replay = scan.nextInt();
}
}
}
Ok, so hopefully that gives anyone who knows what they're doing an idea of my goal. Now, as you can see by this line:
if (replay == 1) {
replay = scan.nextInt();
}
I would like to write a way so people can replay the game without having to reboot the file. I already have an idea of what I kind of would like to do, but I've searched everywhere and can't seem to find out what to continue with after this point. I'm sure that I'm missing something. Any help would be greatly appreciated.
You can use a do-while loop to achieve this:
import java.util.Random;
import java.util.Scanner;
public class Main {
public static int number, guess, tryCount, replay;
public static int maxValue = 1;
public static Scanner scan;
public static Random rand;
public static void main(String args[]) {
scan = new Scanner(System.in);
rand = new Random();
do { // start of do-while loop
tryCount = 0; // reset tryCount
System.out.print("Enter a maximum number: ");
while(maxValue < 2) {
maxValue = scan.nextInt();
}
number = rand.nextInt(maxValue);
System.out.print("Guess a number from 1 to " + maxValue + ": ");
while (guess != number) {
guess = scan.nextInt();
tryCount++;
if (guess < 1) {
System.out.print("Guess is not positive. Try again: ");
} else if (guess < number) {
System.out.print("Too low! Try again: ");
}
if (guess > maxValue) {
System.out.println("Guess is higher than " + maxValue + ". Try again: ");
} else if (guess > number) {
System.out.print("Too high! Try again: ");
}
}
if (tryCount == 1) {
System.out.println("Nailed it! It only took you 1 try!");
} else {
System.out.println("Nailed it! It took you " + tryCount + " tries.");
}
do { // check the user's input
System.out.println("Type 0 to play again. Type 1 to quit.");
replay = scan.nextInt();
if (replay != 0 && replay != 1) {
System.out.println("Input not recognized.");
}
} while (replay != 0 && replay != 1);
} while (replay == 0); // end of do-while loop
}
}
do-while loops are always executed at least once. The condition is checked at the end of the loop.

Show error message instead of exception

I'm trying to make a program that gets a number from the user and checks the number is a prime number or not. I was thinking about the error handling. When the user enters a string the program should give an error message instead of an exception. I tried many methods but couldn't be successful. Could you guys help me with that?
import java.util.Scanner;
public class PrimeNumber {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int inputNum;
int remainingNum;
System.out.println("Enter a number: ");
inputNum = input.nextInt();
if(inputNum < 0){
System.out.println("Please enter a possitive number.");
}
for(int i = 2; i<=inputNum; i++) {
remainingNum = inputNum % i;
if(remainingNum == 0){
System.out.println("This number is not a prime number.");
break;
}
if(remainingNum == 1){
System.out.println("This is a prime number!");
break;
}
}
}
}
If user enters a non-integer input, this line
inputNum = input.nextInt();
will throw an exception (an InputMismatchException). The way Java handles exceptions is through a try-catch block:
try {
inputNum = input.nextInt();
// ... do domething with inputNum ...
} catch (InputMismatchException e) {
System.out.println("Invalid input!");
}
Note: If you want to know more about exceptions (and you must) you can read Java tutorials.
just put it in try-catch and then print your message when exception occurs mean in the catch clause..its simple thing
If you need to check the input first and if it is a number check for prime and if it is invalid prompt user for another input until he enter a valid one, try this.
String inputString;
boolean isValid = false;
while(isValid == false){
//sysout for input
inputString = input.nextLine();
if(inputString.matches("[0-9]+")){
// check for prime
isValid = true;
}else{
//printin error
}
}
}
Thank you to every one especially to Christian. Here is the latest code.
import java.util.InputMismatchException;
import java.util.Scanner;
public class PrimeNumber {
public static void main(String[] args) {
try {
Scanner input = new Scanner(System.in);
int inputNum;
int remainingNum;
System.out.println("Enter a number: ");
inputNum = input.nextInt();
for(int i = 2; i<=inputNum; i++) {
remainingNum = inputNum % i;
if(remainingNum == 0){
System.out.println("This number is not a prime number.");
break;
}
if(remainingNum == 1){
System.out.println("This is a prime number!");
break;
}
}
}
catch (InputMismatchException e) {
System.out.println("Invalid input!");
}
}
}

Categories