Else in loop not working when an invalid number is entered - java

System.out.println("Enter number of dice to throw, an integer [2, 10]: ");
Scanner keyboard = new Scanner (System.in);
n = keyboard.nextInt();
//if the input is valid
if (n>1 && n<11)
{`
System.out.println("good");
Random rn = new Random();
int random = rn.nextInt((6-1) +1) +1;
System.out.println("random number is " + random);
}
else
{
//if the users input is invalid
while (n<2 && n>10)
{
System.out.println("error, must be in [2,10] ");
n = keyboard.nextInt();
}
}

Your logic is incorrect. The number n can't be less than 2 and greater than 10 ever. You want less than 2 or greater then 10. Use || instead of &&.
while (n<2 || n>10)

If the condition in the "if" statement is not met, then wouldn't the program by default go to the 'else' statement? So would you even need the while statement?

Actually it does enter the ‘else’ but not inside the ‘while’. Because n cant be < 2 AND > 10 at the same time.
Replace
while (n<2 && n>10)
With
while (n<2 || n>10)

Related

How to fix this random number guessing game use a do-while loop program?

Create a program that randomly generates a number from 1-100 and asks the user to guess it. If the number the user inputs is to low or to high display a message to tell them so. When the user guesses the random number tell the user how much tries it took him to get that number. After that ask the user if they want to do it again if the user does repeat the process with a new random number generated.
The problem is that I can't seem to figure out how to let the user do it again, it seems to display an error in code when I run the program. If anyone can help me with this issue that would be great. Thank you!
import java.util.Scanner;
import java.util.Random;
public class RandomGuess
{
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
Random randy = new Random();
//#declaring variables
int num, count = 0;
final int random = randy.nextInt(100);
String input;
char yn;
//#random number
System.out.println("Num = " + random);
//#title or header
System.out.println("Random Number Guessing Game");
System.out.println("===========================");
//#asking user for input
do
{
System.out.print("Guess the random number " +
"from 1 to 100===> ");
num = keyboard.nextInt();
//#if the number the user entered
//#was less than the random number
if(num < random)
{
//#display this message
System.out.println("Your guess is too low try again...");
System.out.println();
}
//#if the number the user entered
//#was less than the random number
if(num > random)
{
//#display this message
System.out.println("Your guess is too high try again...");
System.out.println();
}
count++;
if (num == random)
{
System.out.println("You guessed the random number in " +
count + " guesses!");
break;
}
do
{
System.out.print("Continue? (Y or N)==> ");
input = keyboard.nextLine();
yn = input.charAt(0);
}
while(yn == 'Y' || yn == 'y');
}
while (num > 1 || num > 100);
}
}
There are a couple of problems with your code without even seeing the error that is displayed (I've put comments in those areas):
count++;
if (num == random)
{
System.out.println("You guessed the random number in " +
count + " guesses!");
break;
} // You should put an else here
do
{
System.out.print("Continue? (Y or N)==> ");
input = keyboard.nextLine();
yn = input.charAt(0);
}
while(yn == 'Y' || yn == 'y'); // This will keep asking if you want to try again so long as you enter a "y"
// But it won't actually let you try.
// Why? Because if you enter a y" it will loop back to the question.
}
while (num > 1 || num > 100); // This should probably be (random != num)
}
}
Here is a revised version
count++;
if (num == random) {
System.out.println("You guessed the random number in " +
count + " guesses!");
} else {
yn = 'x'; // can be anything other than y or n
while(yn != 'y' && yn != 'n') {
System.out.print("Continue? (Y or N)==> ");
input = keyboard.nextLine();
yn = input.toLowerCase().charAt(0);
}
}
}
while (num != random && yn == 'y');
}
}
Hopefully this is enough to move you forward.
Also, please post the error message and/or a description of what it is doing wrong along with a description as to what you actually wnt it to do.
As for the exception, the problem is that scanner.nextInt does not consume the newline at the end of the numbe you entered. So, your "continue Y/N" question gets what's left over from the previous line (i.e. a new line => an empty string).
You could try this:
num = -1; // Initialise the number to enable the loop
while (num <= 1 || num >= 100) {
System.out.print("Guess the random number from 1 to 100===> ");
String ans = keyboard.nextline();
try {
num = Integer.parseInt(); // Convert the string to an integer - if possible
} catch (NumberFormatException e) {
// If the user's input can not be converted to an integer, we will end up here and display an error message.
System.out.println ("Please enter an integer");
}
}

unable to re-loop through a while loop successfully

my goal in the following code is to keep getting guesses until the user either guesses the right number, or quit. To quit, I am able to easily break out of my loops, but when I try to continue in my loops, it doesn't work right. First it requires multiple inputs, and then also entirely regenerates my number, while what I want to do is to keep getting guesses (asking user) for the SAME random number.
Below is my code:
public class Test {
public static void main(String[] args) {
int count, randNum, guess;
count = 0;
Scanner scan = new Scanner(System.in);
while (true) {
Random rand = new Random();
randNum = rand.nextInt(100) + 1;
System.out.println("Guess a number b/w 1 and 100");
guess = scan.nextInt();
count += 1;
if (guess == randNum) {
System.out.println("Correct guess.");
System.out.println("It took " + count + " tries to guess the right number");
System.out.println("Would you like to play again? ");
System.out.println("Press any letter to play again or q to quit: ");
if (scan.next().charAt(0) == 'q' || scan.next().charAt(0) == 'Q') {
break;
}
else{
continue;
}
}
if (guess > randNum) {
System.out.println("Your guess is bigger than actual number. Would you like to try again?");
System.out.println("Press q to quit or any other letter to try again");
if (scan.next().charAt(0) == 'q' || scan.next().charAt(0) == 'Q') {
break;
}
else {
continue;
}
}
else if (guess < randNum) {
System.out.println("Your guess is smaller than actual number. Would you like to try again?");
System.out.println("Press q to quit or any other letter to try again");
if (scan.next().charAt(0) == 'q' || scan.next().charAt(0) == 'Q') {
break;
}
else {
continue;
}
}
}
}
}
The code for generating the random number should be before the while statement. When you call continue, it goes back to the first line of the while block and consequently generates another random number.
Your statement declaring the int randNum is inside of the while loop, so every time the while loop repeats, the number is declared (again) and set to a value between 1 and 100.
If you want to prevent this, declare the variable and initialize it with a random value outside of the while loop.
A small side note: by initializing the variable inside of the while loop, you are limiting its scope more than you probably want to. Every time it loops through, the previous randNum you created no longer exists, and it then creates a new one. Basically, if you want it to be more permanent, initialize it outside of the loop.
Also, if you only want it to ask for a number between 1 and 100 the very first time, move it outside of the loop. This however is up to you on whether or not you want it to ask each time, or just once.
//…
public static void main(String[] args) {
int count, randNum, guess;
count = 0;
Scanner scan = new Scanner(System.in);
Random rand = new Random();
randNum = rand.nextInt(100) + 1;
System.out.println("Guess a number b/w 1 and 100");
while (true) {
/*Random rand = new Random();
randNum = rand.nextInt(100) + 1;
System.out.println("Guess a number b/w 1 and 100");*/
guess = scan.nextInt();
count += 1;
//…

Want to bullet proof while loop with try-catch

I have this hw problem - Write a program that reads a number and prints all of its binary digits: Print the remainder number % 2, then replace the number with number / 2. Keep going until the number is 0.
It successfully displays the binary digits, but I want to bullet proof it so that it won't crash when letters are used. It doesn't crash but I want to allow the user to enter another number without restarting the program. Any tips on how I can do this?
Scanner scanIn = new Scanner(System.in);
int number = 0;
System.out.print("Please enter a number: ");
try {
number = scanIn.nextInt();
} catch (InputMismatchException ime) {
System.out.println("Please only enter integers!");
number = 0;
scanIn.nextLine();
}
while (number > 0) {
System.out.println(number % 2);
number /= 2;
}
}
One approach is to surround your code in another while loop that iterates forever and breaks out of the loop when a certain condition is met. I also modified your code to repeatedly prompt for an integer if invalid input is entered.
Scanner scanIn = new Scanner(System.in);
int number = 0;
while(true) {
System.out.print("Please enter an integer, or 0 to quit: ");
// input verification
boolean valid = false;
while(!valid) {
try {
number = scanIn.nextInt();
valid = true;
} catch (InputMismatchException ime) {
System.out.println("Please only enter integers!");
System.out.print("Please enter an integer, or 0 to quit: ");
valid = false;
}
}
// break out of the loop if 0 is entered
if(number == 0) {
break;
}
while (number > 0) {
System.out.println(number % 2);
number /= 2;
}
}
You need 2 loops,
The first one will take an input until it is an integer (Integer.parseInt()) Surrounded by a try/catch
Then when you have confirmed an input that is an integer you begin your loop.

how do i prevent the scanner from accepting strings, negative integers, or numbers less than 2?

How do i prevent negative numbers from being returned by this method?
I have tried setting the while loop to
(n < 0 && n != 0)
to no avail.
Here is my code for the method currently:
public int getNumber() {
int n = 1;
while(n < 2 && n != 0) {
if(n < 0) {
System.out.print("Error, please enter a valid number greater than 0(0 to exit): ");
scan.next();
n = scan.nextInt();
}
try {
System.out.print("Enter the upper bound(0 to exit): ");
n = scan.nextInt();
break;
}
catch(java.util.InputMismatchException e) {
System.out.print("Error, please enter a valid number greater than 0(0 to exit): ");
scan.next();
continue;
}
}
return n;
}
I have also tried to put my if statement inside the try block like this:
public int getNumber() {
int n = 1;
while(n < 2 && n != 0) {
try {
System.out.print("Enter the upper bound(0 to exit): ");
n = scan.nextInt();
if(n < 0) {
System.out.print("Error, please enter a valid number greater than 0(0 to exit): ");
scan.next();
n = scan.nextInt();
}
break;
}
catch(java.util.InputMismatchException e) {
System.out.print("Error, please enter a valid number greater than 0(0 to exit): ");
scan.next();
continue;
}
}
return n;
}
When i put the if statement inside the try block, i started to input negative numbers consecutively to test. It worked for the first time i entered a negative number, then gave me a blank scanner input line, and then finally allowed a negative number to return, which in turn screws the rest of my program up. Please help, im a first semester student in java. Thank you.
You input a negative number, then it goes into your n<0 if and you put in another one and then break out of the loop.
Try changing your if to:
while(n < 0)
Do not use while loop condition for validating input. Your loop condition does not give your program a chance to accept and check the number before making a decision to keep or to reject the entered value. As the result, your program starts prompting end-users with an error message even before they typed anything.
You should not call nextInt without first checking if the Scanner is ready to give you an int by calling hasNextInt.
Finally, you need a rejection loop to throw away non-integer input until hasNextInt succeeds. This is usually done with a nested while loop, which prints an error prompt, and throws away the entered value.
The overall skeleton for reading and validating an int looks like this:
System.err.println("Enter a number between 0 and 5, inclusive");
int res = -1;
while (true) {
while (!scan.hasNextInt()) {
System.err.println("Incorrect input. Please enter a number between 0 and 5, inclusive");
scan.nextLine(); // Discard junk entries
}
res = scan.nextInt();
if (res >= 0 && res <= 5) {
break;
}
System.err.println("Invalid number. Please enter a number between 0 and 5, inclusive");
}
// When you reach this point, res is between 0 and 5, inclusive
couldn't you just check for 'hasNextInt', then test the input.
int n = 0;
System.out.println("Enter a number between 0 and 5);
while (scan.hasNextInt()) {
n = scan.nextInt();
if (n >= 0 && n <= 5) {
break;
}else{
//prompt error message or handle however you wish
}
}
return n;
likewise you could also force with an unsigned integer.
Final code to not return negative integers or strings:
public int getNumber() {
System.out.print("Enter the upper bound(0 to exit): ");
int nums = 1;
while(true) {
while(!scan.hasNextInt()) {
System.out.print("Error. Please enter a valid integer greater than 1(0 to exit): ");
scan.nextLine();
}
nums = scan.nextInt();
if(nums > 2 || nums == 0) {
break;
} else {
System.out.print("Error. Please enter a valid integer greater than 1(0 to exit): ");
scan.nextLine();
}
}
return nums;
}
Thanks a million you guys!

initializing scanner values in a loop to an array

I have created a game where the user guesses a random number that was created 0-100. If their guess is too high, the system tells them to guess higher, and the same for if their guess is lower than the actual number. However, I need to initialize each guess to an array, in the order that they inputted. I know how to initialize an array, but I need help on storing the player's guesses into the array. Here is my code, and any help/advice is appreciated!
public static void randomNumGame(){
// begin of method
Scanner numbers = new Scanner(System.in);
Random randomGenerator = new Random();
int[] guess;
guess = new int[6];
guess[0]=0;
guess[1]=0;
guess[2]=0;
guess[3]=0;
guess[4]=0;
guess[5]=0;
System.out.println("running ...");
int thisRandomInt = randomGenerator.nextInt(100);
int attempt = 0;
boolean done = false;
while(!done){
System.out.print("Guess a number from 0 to 100 : ");
int myGuess = numbers.nextInt();
attempt++;
if(myGuess == thisRandomInt && attempt <= guess.length){
done = true;
System.out.println("You won. It took " + attempt+ " times to guess my number.");
}else if (attempt >= guess.length){
System.out.println("Game Over. My number is "+thisRandomInt );
done = true;
}else if (myGuess < thisRandomInt){
System.out.println("Guess a higher number");
}else{
System.out.println("Guess a lower number");
}
}
}// end of method
if(myGuess == thisRandomInt && attempt <= guess.length){
done = true;
System.out.println("You won. It took " + attempt+ " times to guess my number.");
}else if (attempt >= guess.length){
System.out.println("Game Over. My number is "+thisRandomInt );
done = true;
}else if (myGuess < thisRandomInt){
guess[attempt-1] = myGuess;
System.out.println("Guess a higher number");
}else{
guess[attempt-1] = myGuess;
System.out.println("Guess a lower number");
}
You don't need to explicitly init your quest array with zeroes. Apart from that, you can do something like this:
System.out.print("Guess a number from 0 to 100 : ");
int myGuess = numbers.nextInt();
guess[attempt++] = myGuess;
Also, instead of the done flag, you can call break instead of declaring the flag true - it will escape the loop.

Categories

Resources