Validate Scanner input on a numeric range - java

I'm currently creating my first game which is executed in a console.
I've been asked to validate an input which can be done with a simple code. The goal is to input, and then validate if that number is an integer, and is on a range of 1-4. If possible, the problem should be solved with basic algorithm.
The problem is that it won't give me the result I wanted. It works when I enter a string, but it loops on every number I put including the number in the range. Does anyone know why?
public class Menu {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
int input = 0;
int min = 1;
int max = 4;
boolean inputValidate;
System.out.println("Main Menu");
System.out.println("=========");
System.out.println("1. Play Game");
System.out.println("2. About");
System.out.println("3. View Saved Games");
System.out.println("4. Exit");
System.out.println("");
do {
System.out.print(">> ");
if (!scanner.hasNextInt()) {
inputValidate = false;
System.out.println("Not a number. Please input number 1-4.");
scanner.nextLine();
} else if (input <= max && !(input < min)) // if input <= 4 and input is not less than 1
{
input = scanner.nextInt();
inputValidate = true;
} else {
inputValidate = false;
System.out.println("Not in range. Please input number 1-4.");
scanner.nextLine();
}
} while (!(inputValidate));
switch (input) {
case 1:
break;
case 2:
System.out.println("Good work!");
break;
case 3:
break;
case 4:
break;
}
}
}
}

Because you instantiate input to be 0, but never give the user an opportunity to change this, the conditions for the first two conditionals are always false (nothing is read from the Scanner and 0 is not between min and max). Therefore, the program falls through to the else every time. Just add a statement before the do-while that will obtain a value for input from the user.
input = scanner.nextInt();
// your do-while loop
(You'll also probably have to adjust the code slightly to get the type of interaction you're looking for. Hint - you're reading two values from the user.)

As Clint said the problem was in your input. Here's a demo how you can fix this,
try (Scanner scanner = new Scanner(System.in)) {
int input = 0;
int min = 1;
int max = 4;
boolean inputValidate = false;
System.out.println("Main Menu");
System.out.println("=========");
System.out.println("1. Play Game");
System.out.println("2. About");
System.out.println("3. View Saved Games");
System.out.println("4. Exit");
System.out.println("");
do {
System.out.print(">> ");
try {
input = scanner.nextInt();
if (input >= min && input <= max) {
inputValidate = true;
} else {
System.out
.println("Not in range. Please input number 1-4.");
scanner.nextLine();
}
} catch (InputMismatchException exception) {
System.out
.println("Not a number. Please input number 1-4.");
scanner.nextLine();
}
} while (!(inputValidate));

Related

Two checks in while loop with Scanner - java

im trying to do two checks with a while loop:
1) To show "error" if the user inputs something other than an int
2) Once the user entered an int, if it is one digit, show "two digits only" and keep the loop on until a two digit int has been entered (so an IF should be used as well)
Currently I only have the first part done:
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number");
while (!scan.hasNextInt()) {
System.out.println("error");
scan.next();
}
However, if possible, I would like to have both checks in one while loop.
And that's where I'm stuck...
Since you already have two answers. This seems a cleaner way to do it.
Scanner scan = new Scanner(System.in);
String number = null;
do {
//this if statement will only run after the first run.
//no real need for this if statement though.
if (number != null) {
System.out.println("Must be 2 digits");
}
System.out.print("Enter a 2 digit number: ");
number = scan.nextLine();
//to allow for "00", "01".
} while (!number.matches("[0-9]{2}"));
System.out.println("You entered " + number);
As said above you should always take the input in as string and then try
and parse it for an int
package stackManca;
import java.util.Scanner;
public class KarmaKing {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = null;
int inputNumber = 0;
while (scan.hasNextLine()) {
input = scan.next();
try {
inputNumber = Integer.parseInt(input);
} catch (Exception e) {
System.out.println("Please enter a number");
continue;
}
if (input.length() != 2) {
System.out.println("Please Enter a 2 digit number");
} else {
System.out.println("You entered: " + input);
}
}
}
}
First take the input as a String. If it is convertible to Int then you do your checks, else say 2 digit numbers are acceptable. If it is not convertible to a number throw an error. All this can be done in one while loop. And you would like to have a "Do you want to continue? " kind of a prompt and check if the answer is "yes" / "No." Break from the while loop accordingly.
To have it as one loop, it's a bit messier than two loops
int i = 0;
while(true)
{
if(!scan.hasNextInt())
{
System.out.println("error");
scan.next();
continue;
}
i = scan.nextInt();
if(i < 10 || >= 100)
{
System.out.println("two digits only");
continue;
}
break;
}
//do stuff with your two digit number, i
vs with two loops
int i = 0;
boolean firstRun = true;
while(i < 10 || i >= 100)
{
if(firstRun)
firstRun = false;
else
System.out.println("two digits only");
while(!scan.hasNextInt())
{
System.out.println("error");
scan.next();
}
i = scan.nextInt();
}
//do stuff with your two digit number, i

Reset variables back to zero in do-while loop Java

I am working on an example using a do-while loop and switch statement. What I basically need is to accumulate numbers and depending on user input either add, substract, multiply or divide (mini calculator type).
The problem is when I ask the user to go back to the main menu the program does not reset the value as it is before the loop. The result is always the previous result.
Here is the code, it will explain it better.
import java.util.Scanner;
public class SwitchLoopNumbers{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int numbers=0;
int result=0;
int option;
boolean quit = true;
String done="";
do{
System.out.println("CALCULATOR MENU");
System.out.println("********** ****");
System.out.println("\n1. Add");
System.out.println("2. Substract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.println();
System.out.print("Enter your option >> ");
option = scan.nextInt();
while(quit){
switch(option){
case 1:
System.out.print("Enter numbers, type 0 when done >> ");
numbers = scan.nextInt();
if(numbers==0)
quit=false;
result +=numbers;
break;
case 2:
System.out.print("Enter numbers, type 0 when done >> ");
numbers = scan.nextInt();
result -=numbers;
if(numbers==0)
quit=false;
break;
}
}
System.out.println("The total is: "+result);
System.out.println("Back to main menu ? y/n ");
scan.nextLine();
done = scan.nextLine();
//I did reset numbers and result here to zero but it did not work
}
while("y".equalsIgnoreCase(done));
System.out.println("Thank you for using calculator");
}
}
A couple things are going on here. To answer your question concisely, it's because you didn't reassign your variables before re-looping. Since you don't reassign result and quit, quit is false so it closes the loop, and result is unchanged so it then prints the same result. Try this:
System.out.println("The total is: "+result);
System.out.println("Back to main menu ? y/n ");
scan.nextLine();
done = scan.nextLine();
numbers = 0;
result = 0;
quit = true;
I think it's the most straight-forward solution to your problem.
EDIT: I also wanted to add that using quit as the while condition seems a little counter-intuitive. If I saw a condition quit that was true, my assumption would be that it would break the loop, not continue it. You might make your code a bit clearer by designating more meaningful variable names. So instead of saying something like:
boolean quit = true;
while(quit) {
//do stuff
if (some_condition) {
quit = false;
//close loop
}
}
This may be a little clearer:
boolean quit = false;
while(!quit) {
//do stuff
if (some_condition) {
quit = true;
//close loop
}
}
Just a general suggestion.
You can try to call main() again, but I'm not sure if it will work, solution can be make your own method eg. init() - where you will set vars into init state, and eg. work(), what will be remaining code :D
EDIT: you can make it this way
import java.util.Scanner;
public class main {
//if you want work with result after user will write "y" in the end
static int result = 0;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int numbers = 0;
int option;
boolean quit = false;
String done = "";
//int result = 0; // if you want also init result
// menu
System.out.println("CALCULATOR MENU");
System.out.println("********** ****\n");
System.out.println("1. Add");
System.out.println("2. Substract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
// user menu input read
System.out.println();
System.out.print("Enter your option >> ");
option = scan.nextInt();
switch (option) {
case 1:
while (!quit) {
System.out.print("Enter numbers, type 0 when done >> ");
numbers = scan.nextInt();
if (numbers == 0) {
quit = true;
}
result += numbers; // result = result + numbers
}
break;
case 2:
while (!quit) {
System.out.print("Enter numbers, type 0 when done >> ");
numbers = scan.nextInt();
result -= numbers; // result = result - numbers
if (numbers == 0) {
quit = true;
}
}
break;
default:
System.out.println("Bad inpout");
break;
}
System.out.println("The total is: " + result);
System.out.println("Back to main menu ? y/n ");
scan.nextLine();
done = scan.nextLine();
//recursive call - run main() again
if (done.equals("y")) {
main(args);
} else {
System.out.println("Thank you for using calculator");
}
}
}

MasterMind-Resource Leak?

My code is running fine, but every line where I use a scanner it warns me that there is a "Resource leak; 'userGuess' is never closed" I don't understand what it means and could use some help solving it. Also if there is anything else in my code worth fixing I could use the help. Be warned I have a limited knowledge of Java programming. I also cannot get my TryCounter++ to work...
package masterMind2_1;
import java.util.Scanner;
public class MasterMind2_1 {
public static void main(String[] args) {
System.out.println("This is MasterMind, a logic game");
System.out.println("To win you must guess correctly where each number is(The Numbers Range from 1-4)");
System.out.println("You will be told if you get one correct");
System.out.println("You will only get 10 tries, then you lose");
System.out.println("Lets begin");
//Declare Array
int [] answerArray;
answerArray= new int [4];
//Initialize Array
//Change these value to change the answers needed to win
answerArray[0]=2;
answerArray[1]=3;
answerArray[2]=2;
answerArray[3]=2;
// //Create Board
// System.out.println("-- -- -- --");
boolean guessedAll = false;
int guessedCount=0;
int tryCounter=0;
while(tryCounter<9 || !guessedAll){
System.out.println("What is the first Number?");
Scanner userGuess = new Scanner(System.in);
int num = userGuess.nextInt();
if (num==answerArray[0]) {
guessedCount++;
}
System.out.println("What is the Second Number?");
Scanner userGuess1 = new Scanner(System.in);
int num1 = userGuess1.nextInt();
if (num1==answerArray[1]) {
guessedCount++;
}
System.out.println("What is the Third Number?");
Scanner userGuess2 = new Scanner(System.in);
int num2 = userGuess2.nextInt();
if (num2==answerArray[2]) {
guessedCount++;
}
System.out.println("What is the Fourth Number?");
Scanner userGuess3 = new Scanner(System.in);
int num3 = userGuess3.nextInt();
if (num3==answerArray[3]) {
guessedCount++;
}
System.out.println("Your guess was "+ num+" "+num1+" "+num2+" "+num3);
if (num==answerArray[0]) {
System.out.println("First number was correct");
} else {
System.out.println("First number was incorrect");
}
if (num1==answerArray[1]) {
System.out.println("Second number was correct");
} else {
System.out.println("Second number was incorrect");
}
if (num2==answerArray[2]) {
System.out.println("Third number was correct");
} else {
System.out.println("Third number was incorrect");
}
if (num3==answerArray[3]) {
System.out.println("Fourth number was correct");
} else {
System.out.println("Fourth number was incorrect");
}
if (guessedCount==4) {
System.out.println("YAY you won!!");
guessedAll=true;
tryCounter=10;
} else {
System.out.println("Try again, except this time don't fail!");
guessedAll=false;
tryCounter++;
guessedCount=0;
}
}//What if I collected all of the values first
} //then told them if they were right or Wrong?
//Black and White Pegs?
//Fix TryCounter...Why isn't it working
}
Thank you for the Help!
The error message is telling you that you never call the close() method on your Scanner object. A worse problem is that you create multiple Scanners when you only need one.
As for tryCounter not working...
while(tryCounter<9 || !guessedAll)
This will keep looping if either part of the condition is true. My guess is that !guessedAll is evaluating to true beyond 9 guesses, so your loop keeps running. You'll need to change the || to an && to get it stop looping after 9 tries. (Also, print out the values of your variables or use a debugger so you can verify that they are changing when you expect them to.)

Checking user input is a number

I need to check users input. I have a menu and I need the user to select numbers 0-4 but if the user selects a letter instead of a number then I just get a InputMismatchException. So I am trying to validate that the user entered a number. Here is my code:
public class TestBankAccount {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException {
ArrayList<BankAccount> list = new ArrayList<BankAccount>();
int choice;
do {
System.out.println("1. Deposit money");
System.out.println("2. Withdraw money");
System.out.println("3. Check balance");
System.out.println("4. Create new account");
System.out.print("Your choice, 0 to quit: ");
choice = input.nextInt();
switch (choice) {
case 1:
depositMoney(list);
break;
case 2:
withdrawMoney(list);
break;
case 3:
checkBalance(list);
break;
case 4:
createNewAccount(list);
break;
case 0:
System.out.println("Thank you for trusting us with your banking needs!");
break;
default:
System.out.println("Invalid option is selected!");
}
System.out.println();
} while (choice != 0);
if (list.size() > 0) {
displayResults(list);
}
}
I was thinking to do something like while (choice != 0 && choice != input.hasNextInt()); but I get an error. Any ideas?
You can do somehting like this :
int choice = 0 ;
try{
choice = Integer.parseInt(input.next());
}
catch(NumberFormatException e)
{
System.out.println("invalid value enetered");
}
// Now you can check if option selected is between 1 & 4
// and throw some custom exception
Either catch the exception and handle it, or instead of Scanner use
(char) System.in.read();
to receive characters. In this way you can avoid handling exceptions, which takes a lot of time. You can work on chars instead of integers then or check their validity and convert them to integers in this way:
int x = Character.getNumericValue(choice);
Just wrap it in a try catch
do{
try{
System.out.println(choices)
choice = input.nextInt()
switch(choice){
....
}
}
catch(InputMismatchException){
System.out.println("Please enter a valid input")
}
}
while(whatever)
I found the answer out. This is how I would validate the account number's.
int number;
while(true){
System.out.print("\nEnter account number: ");
try{
number = input.nextInt();
break;
}catch(Exception e){
System.err.println("Error: Invalid Entry! Please try only Integers");
input=new Scanner(System.in);
}
}
and this is how I would validate the menu item selected is a number and not a letter:
int choice = 0;
do {
while(true)
{
System.out.println("1. Deposit money");
System.out.println("2. Withdraw money");
System.out.println("3. Check balance");
System.out.println("4. Create new account");
System.out.print("Your choice, 0 to quit: ");
try{
choice = Integer.parseInt(input.next());
break;
}
catch(Exception e){
System.err.println("Error: Invalid entry! Please Try Again!");
input=new Scanner(System.in);
continue;
}
}

Scanning Inputs in Java using Scanner

This code checks if the users input it is valid. if it is not a number it will continue to loop untill it receives a number. after that it will check if that number is in bounds or lesser than than the bound. it will continue looping until it receives an inbound number. but my problem here is that when I print choice it only shows the previous number after the last number that was inserted. why is it like that?
public void askForDifficulty(){
System.out.println("Difficulty For This Question:\n1)Easy\n2)Medium\n3)Hard\nChoice: ");
int choice = 0;
boolean notValid = true;
boolean notInbound = true;
do{
while(!input.hasNextInt()){
System.out.println("Numbers Only!");
System.out.print("Try again: ");
input.nextLine();
}
notValid = false;
choice = input.nextInt();
}while(notValid);
do{
while(input.nextInt() > diff.length){
System.out.println("Out of bounds");
input.nextLine();
}
choice = input.nextInt();
notInbound = false;
}while(notInbound);
System.out.println(choice);
}
This is because input.nextInt() inside the while condition consumes the integer, so the one after it reads the following one. EDIT You also need to combine the two loops, like this:
int choice = 0;
for (;;) {
while(!input.hasNextInt()) {
System.out.println("Numbers Only!");
System.out.print("Try again: ");
input.nextLine();
}
choice = input.nextInt();
if (choice <= diff.length) break;
System.out.println("Out of bounds");
}
System.out.println(choice);

Categories