checking input for positive number - java

So for my programming assignment the user has to enter the number of grades, but we have to check the input and return the proper error. The number has to be a positive number, and the program needs to differ between the error and give the proper response and loop it back until the right number is inputed. I got the error checking part but I'm having trouble getting the program to continue to the next part. any help would be appreciated
do {
System.out.println("Enter number of grades");
if (input.hasNextInt()){
numGrade = input.nextInt();
if (numGrade < 0){
System.out.println("Your number of grades needs to positive! Try again");
count1++;
continue;
}
}
else{
System.out.println("You did not enter a number! Try again");
count1++;
input.next();
continue;
}
}while (count1 > 0);

Try this,
//use a boolean to tell the loop to continue or not
boolean cont = true;
do {
System.out.println("Enter number of grades");
if (input.hasNextInt()){
numGrade = input.nextInt();
//I assume 0 is a valid response (not a negative int)
if (numGrade <= 0){
System.out.println("Your number of grades needs to positive! Try again");
continue;
}
else {
cont = false;
System.out.println("Your input is valid! Value entered is " + numGrade);
}
}
else {
System.out.println("You did not enter a number! Try again");
input.next();
continue;
}
}
while (cont);

Related

Scanner input with exception handling in a try/catch is not working like intended

I am making an atm program that takes in an account number and a pin. When I try to type in anything except the accepted accounts and pins that are predetermined, it is supposed to give an error message and the user tries again. The only problem is that it prints out the error message but moves on to the next input instead of repeating the previous input. i.e. goes from entering the account number to entering the pin number. The same thing happens for the pin as well. I really don't know what to make of it. Thanks in advance! Here's a snippet of my code:
import java.util.*;
import java.lang.*;
public class Menu {
Scanner input = new Scanner(System.in);
//Bank bank = new Bank();
boolean keepGoing = true;
public static void main(String[] args){
Menu menu = new Menu();
menu.startMenu();
}//end main
public void startMenu(){
int choice = 0;
int verify1 = 0;
int verify2 = 0;
int account = 0;
int pin = 0;
printGreet();
while(keepGoing){
System.out.print("Please enter Account number: ");
do{
try{
account = input.nextInt();
}//end try
catch(NumberFormatException e){
System.out.print("ERROR: That is not a valid account number. Please enter a valid account number (#####): ");
input.nextLine();//clear buffer
}//end catch
catch(InputMismatchException e){
System.out.print("Error: That is not a valid account number. Please enter a valid account number (#####): ");
input.nextLine();//clear buffer
}//end catch
if(account < 0 || account > 99999){
System.out.print("ERROR: That is not a valid account number. Please enter a valid account number (#####): ");
//input.nextLine();//clear buffer
}//end if
}while(!(account >= 0 && account <= 99999));//end do/while
System.out.print("Please enter PIN number: ");
do{
try{
pin = input.nextInt();
}//end try
catch(NumberFormatException e){
System.out.print("ERROR: That is not a valid pin number. Please enter a valid pin number (#####): ");
input.nextLine();//clear buffer
}//end catch
catch(InputMismatchException e){
System.out.print("ERROR: That is not a valid pin number. Please enter a valid pin number (#####): ");
input.nextLine();//clear buffer
}//end catch
if(pin < 0 || pin > 99999){
System.out.print("ERROR: That is not a valid pin number. Please enter a valid pin number (#####): ");
//input.nextLine();//clear buffer
}//end if
}while(!(pin >= 0 && pin <= 99999));//end do/while
verify1 = verifyAccount(account);
verify2 = verifyPin(pin);
if((verify1 == 1) && (verify2 == 1)){
printAdminMenu();
choice = getAdminChoice();
adminChoices(choice);
}else if((verify1 == 2) && (verify2 == 2)){
printUserMenu();
choice = getUserChoice();
userChoices(choice);
}else{
System.out.println("ERROR: YOU ARE NOT AN AUTHORIZED USER...GOODBYE");
System.exit(0);
}//end if/else
}//end while
}//end startMenu()
The whiles only check if the account number is invalid. When a parsing error occurs the account/pin variable is still 0 so it doesn't repeat.
I fixed/improved the code for you. Note you should always debug your code before you ask a question on StackOverflow.
public void startMenu() {
int account = 0;
int pin = 0;
printGreet();
while (keepGoing) {
System.out.print("Please enter Account number: ");
boolean invalid;
do {
invalid = false;
try {
account = input.nextInt();
// Cancel if the number is invalid
if (account < 0 || account > 99999) {
throw new NumberFormatException();
}
} catch (NumberFormatException | InputMismatchException e) {
System.out.print("ERROR: That is not a valid account number. Please enter a valid account number (#####): ");
input.nextLine();
// Mark the loop iteration as invalid
invalid = true;
}
} while (invalid);
System.out.print("Please enter PIN number: ");
do {
invalid = false;
try {
pin = input.nextInt();
// Cancel if the number is invalid
if (pin < 0 || pin > 99999) {
throw new NumberFormatException();
}
} catch (NumberFormatException | InputMismatchException e) {
System.out.print("ERROR: That is not a valid pin number. Please enter a valid pin number (#####): ");
input.nextLine();
invalid = true;
}
} while (invalid);
verify1 = verifyAccount(account);
verify2 = verifyPin(pin);
if ((verify1 == 1) && (verify2 == 1)) {
printAdminMenu();
choice = getAdminChoice();
adminChoices(choice);
} else if ((verify1 == 2) && (verify2 == 2)) {
printUserMenu();
choice = getUserChoice();
userChoices(choice);
} else {
System.out.println("ERROR: YOU ARE NOT AN AUTHORIZED USER...GOODBYE");
System.exit(0);
}
}
}

How do I include a question asking the user if they want to play again?

I am still new to Java and as such I am still figuring some things out. I have been having issues with including code asking the user if they want to play again. I have attempted putting it in the main class in a print statement which gave me an error. After that, I attempted putting it in the Guess.java class in multpile places but I just recieved errors. I have read up on the issue and some sites have suggested a while loop but I am unsure how to implement it into my current code. I have included both the main class which is called GuessingGame.java and the Guess.java class below. Thank you for any assistance that can be provided.
GuessingGame.java
public class GuessingGame {
public static void main(String[] args) {
new Guess().doGuess();
}
}
Guess.java
class Guess {
private int answer = 0;
int tries = 0;
Scanner input = new Scanner(System.in);
int guess, i;
boolean win = false;
int amount = 10;
public Guess() {
answer = generateRandomNumber();
}
//Generate a private number between 1 and a thousand
private int generateRandomNumber() {
Random rand = new Random();
return rand.nextInt(1000) + 1;
}
public void doGuess() {
while (!win) {
System.out.println("You are limited to ten attempts."
+ " Guess a number between 1 and 1000: ");
guess = input.nextInt();
if (tries > 9) {
System.out.println("You should be able to do better!"
+ " You have hit your ten guess limit. The number"
+ " was: " + answer);
System.out.println("Do you want to play again?: ");
return;
}
if (guess > 1000) {
System.out.println("Your guess is out of the range!");
} else if (guess < 1) {
System.out.println("Your guess is out of the range!");
} else if (guess == answer) {
win = true;
tries++;
} else if (guess < answer && i != amount - 1) {
System.out.println("Your guess is too low!");
tries++;
} else if (guess > answer && i != amount - 1) {
System.out.println("Your guess is too high!");
tries++;
}
}
System.out.println("Congragulations! You guessed the number!"
+ "The number was: " + answer);
System.out.println("It took you " + tries + " tries");
}
}
You already found a good position for adding this functionality:
System.out.println("Do you want to play again?: ");
The first step now is to also tell the user what he/she should enter after that question:
System.out.println("Do you want to play again? (enter 0 for yes and 1 for no): ");
After that we need to get the user input of course:
int number;
//If the user enters e.g. a string instead of a number, the InputMismatchException
//will be thrown and the catch-block will be executed
try {
number = input.nextInt();
//If number < 0 OR number > 1
if(number < 0 || number > 1) {
//The rest of the try-block will not be executed.
//Instead, the following catch-block will be executed.
throw new InputMismatchException();
}
break;
}
catch(InputMismatchException e) {
System.out.println("Enter 0=yes or 1=no");
//Clears the scanner to wait for the next number
//This is needed if the user enters a string instead of a number
input.nextLine();
}
If you don't know about try-catch-statements yet, I suggest to read this explanation. For details about the InputMismatchException, please see the documentation.
The problem now is that the user only has one chance to enter 0 or 1. If the user makes a wrong input the program will just stop. One solution to this problem is to just put the code in a while-loop:
int number;
while(true) {
try {
number = input.nextInt();
if(number < 0 || number > 1) {
throw new InputMismatchException();
}
break;
}
catch(InputMismatchException e) {
System.out.println("Enter 0=yes or 1=no");
input.nextLine();
}
}
After this block, we can be sure that number is either 0 or 1. So now we can add a simple if-statement to check the value:
if(number == 0) {
new Guess().doGuess();
}
return;
So all in all the code looks like this:
System.out.println("Do you want to play again? (enter 0 for yes and 1 for no): ");
int number;
while(true) {
try {
number = input.nextInt();
if(number < 0 || number > 1) {
throw new InputMismatchException();
}
break;
}
catch(InputMismatchException e) {
System.out.println("Enter 0=yes or 1=no");
input.nextLine();
}
}
if(number == 0) {
new Guess().doGuess();
}
return;
Don't forget to add the following import-statements:
import java.util.Scanner;
import java.util.InputMismatchException;
import java.util.Random;
Try this. Basically, if the user responds with "yes" , we will call the function again.
if (tries > 9) {
System.out.println("You should be able to do better!"
+ " You have hit your ten guess limit. The number" + " was: " + answer);
System.out.println("Do you want to play again? (yes/no): "); // modified line
if("yes".equalsIgnoreCase(input.next())){ // newly added if block
answer = generateRandomNumber();
tries=0;
i=0;
win = false;
doGuess();
}
return;
}

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

Do While loops and nested if statement [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to write a program that randomly generates a number and the user tries to guess the number. The program keeps count of how many tries it took to guess the right number. The issue that I am having is getting past the while loop. When I run the program, it doesn't go past the while loop until I hit -1, in which case it outputs "Your number is too low". I am not real sure where I went wrong.
import java.util.Scanner;
import java.util.Random;
public class DoGuessingGame
{
public static void main(String[] args)
{
int number1, userInput; //assign vars
int tries = 0;
Random rand = new Random();
Scanner keyboard = new Scanner(System.in); //define Random and scanner input
System.out.println("Welcome to the Guessing Game!");
System.out.println("-----------------------------");
number1 = rand.nextInt(20) + 1;
do
{
System.out.println("\nI'm thinking of a number between 1 and 20. Enter -1 if you would like to quit");
userInput = keyboard.nextInt();
tries++;
}
while(userInput != -1);
{
if (userInput > 0 && userInput < 21)
{
if(userInput == number1)
{
System.out.println("That is the correct number");
tries++;
System.out.println("The Number of tries: " + tries);
System.out.println("Game Over.");
}
else if(userInput > number1)
{
System.out.println("Your number is too high");
System.out.println("Please try again");
userInput = keyboard.nextInt();
tries++;
}
else if(userInput < number1);
{
System.out.println("Your number is too low");
System.out.println("Please try again");
userInput = keyboard.nextInt();
tries++;
}
}
else
{
System.out.println("Please enter a number between 1 and 20");
}
}
System.out.println("The number of tries: " + tries);
}
}
Your nesting and placement of braces is confusing. No wonder you're having problems.
Learn to pay more attention to style and readability.
I did not compile or run your code. I didn't think too deeply to see if you did this correctly. But I might do it more like this:
import java.util.Scanner;
import java.util.Random;
public class DoGuessingGame
{
public static void main(String[] args) {
int number1, userInput; //assign vars
int tries = 0;
Random rand = new Random();
Scanner keyboard = new Scanner(System.in); //define Random and scanner input
System.out.println("Welcome to the Guessing Game!");
System.out.println("-----------------------------");
number1 = rand.nextInt(20) + 1;
do
{
System.out.println("\nI'm thinking of a number between 1 and 20. Enter -1 if you would like to quit");
userInput = keyboard.nextInt();
tries++;
if (userInput > 0 && userInput < 21) {
if(userInput == number1) {
System.out.println("That is the correct number");
System.out.println("The Number of tries: " + tries);
System.out.println("Game Over.");
userInput = -1;
} else if(userInput > number1) {
System.out.println("Your number is too high");
System.out.println("Please try again");
} else if(userInput < number1) {
System.out.println("Your number is too low");
System.out.println("Please try again");
}
} else {
System.out.println("Please enter a number between 1 and 20");
}
} while(userInput != -1);
System.out.println("The number of tries: " + tries);
}
You have an extra pair of braces directly after your do-while loop, as well as a semicolon directly after an if-statement which will alter the flow of your program.
else if(userInput < number1);
Your do/while loop is not doing what you think. You have:
do {
System.out.println("\nI'm thinking of a number between 1 and 20. Enter -1 if you would like to quit");
userInput = keyboard.nextInt();
tries++;
} while(userInput != -1);
Code below this point is executing after the do while loop, hence userInput will always be -1 when you reach here!
I think your do.... while loop should look like this
do
{
System.out.println("\nI'm thinking of a number between 1 and 20. Enter -1 if you would like to quit");
userInput = keyboard.nextInt();
tries++;
if (userInput > 0 && userInput < 21)
{
if(userInput == number1)
{
System.out.println("That is the correct number");
tries++;
System.out.println("The Number of tries: " + tries);
System.out.println("Game Over.");
}
else if(userInput > number1)
{
System.out.println("Your number is too high");
System.out.println("Please try again");
userInput = keyboard.nextInt();
tries++;
}
else if(userInput < number1);
{
System.out.println("Your number is too low");
System.out.println("Please try again");
userInput = keyboard.nextInt();
tries++;
}
}
else
{
System.out.println("Please enter a number between 1 and 20");
}
}
while(userInput != -1);

Scanner object does not return intended result

I am trying to use the scanner object to validate some user input. According to my requirement if user input is 100>inputs<0 I need to provide some console output. However, the following code does not work when I enter 100/0 and provides me some empty console output. I tried to test this code block with 102 and -1 with same (empty) console output
public int validateScore(Scanner sc) {
int score = 0;
System.out.println("Please Enter Student's Score.");
for (;;) {
if (!sc.hasNextInt()) {
System.out.println("Please enter the score and in number");
sc.next(); // discard
}else if (sc.nextInt() > 100){
sc.next(); // discard
System.out.println("Please enter the score and in number in between 0-100 only: ");
}else if (sc.nextInt() < 0){
sc.next(); // discard
System.out.println("Please enter the score and in number in between 0-100 only: ");
}else {
score = sc.nextInt();
break;
}
}
return score;
}
The error is causing because of using nextInt() in the if else block . Use the method hasNextInt() and store the value in a temporary variable before validating the value .
You should not read from the Scanner several times. Just read the number once via nextInt into the variable and check it. Otherwise on every if branch you will be prompted for a new number.
public int validateScore(Scanner sc) {
int score = 0;
System.out.println("Please Enter Student's Score.");
for (;;) {
if (!sc.hasNextInt()) {
System.out.println("Please enter the score and in number");
sc.next(); // discard
} else {
int nextInt = sc.nextInt();
if (nextInt > 100) {
System.out.println("Please enter the score and in number in between 0-100 only: ");
} else if (nextInt < 0) {
System.out.println("Please enter the score and in number in between 0-100 only: ");
} else {
score = nextInt;
break;
}
}
}
return score;
}

Categories

Resources