Scanning Inputs in Java using Scanner - java

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

Related

Java program reading indefinite amount of numbers from a user till a positive is entered

I need to write a java program reading in an indefinite amount of numbers and saves them to a collection of numbers, until an (even number) is entered in by the user. I have tried with a while loop, that when a positive number is found in it it stops. But it is not really working. Here is codes I have tried:
public static void main(String[] args) {
int programInteger = 1;
int inputtedInteger;
while (programInteger < 2) {
System.out.println("Enter a number: "); //Asks user to input a number
Scanner in = new Scanner(System.in);
inputtedInteger = Scanner(in.nextLine);
if (inputtedInteger != 0) {
System.out.println("The number "+ inputtedInteger +" that you inputted is not an even number, try again: ");
inputtedInteger=in.nextInt();
}
else if (inputtedInteger % 2 == 0){
programInteger =+1;
System.out.println("The number "+inputtedInteger+" that you entered is an even number!");
}
}
}
/* if(inputtedInteger % 2 == 0) {
System.out.println("The number "+ inmatatTal +" you entered is an even number!");
}
else {
System.out.println("Enter a number?! ");
inputtedInteger = in.nextInt();
}
Fixing a few things in the logic of the loop should work:
int inputtedInteger = 0;
Scanner in = new Scanner(System.in);
while (inputtedInteger < 1) {
System.out.println("Enter a number: "); //Asks user to input a number
inputtedInteger = in.nextInt();
if (inputtedInteger % 2 != 0) {
System.out.println("The number "+ inputtedInteger +" that you inputted is not an even number, try again: ");
}
else if (inputtedInteger % 2 == 0){
System.out.println("The number "+inputtedInteger+" that you entered is an even number!");
}
}
I would setup an outline for the code like this:
setup Scanner, create collection
while true:
userInput = scanner.nextInt()
if userInput > 0: break
collection.add(userInput)
print('user entered', collection.length(), 'numbers.')
Hope that helps. I'll leave you to fill this using actual Java syntax.
I wrote a comment on the OP on why your structure is failing to solve the issue at hand.

How do I safely scan in an integer in a while loop? [duplicate]

This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
Closed 4 years ago.
I want to scan in an integer and put it in a while loop so that if an invalid entry is entered the program will ask to enter another integer but when I run this it won't allow me to enter and new integer and just prints invalid entry multiple times.
do {
System.out.println("Maximum number of Students:");
if(input.hasNextInt()) {
maxstudents = input.nextInt();
if (maxstudents > 0) {
break;
}
} else {
System.out.println("Invalid entry");
}
} while(true);
Change the else to :
else {
System.out.println("Invalid entry");
input.nextLine();
}
So on an invalid input you need to move the cursor to the next line so that you can accept the input again.
#Nicholas K is right. But I offer you to add another warning message for situation with negative integer and move this code into separate method.
public static int getMaxStudents(Scanner scan) {
do {
System.out.print("Maximum number of Students: ");
if (scan.hasNextInt()) {
int maxStudents = scan.nextInt();
if (maxStudents > 0)
return maxStudents;
}
System.out.println("Enter a valid positive integer number");
scan.nextLine(); // <-- this is mandatory
} while (true);
}
do {
System.out.println("Maximum number of Students:");
if(input.hasNextInt()) {
maxstudents = input.nextInt();
if (maxstudents > 0) {
break;
}
}
else {
System.out.println("Invalid entry:"+scanner.next());
}
}while(true);

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

Validate Scanner input on a numeric range

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

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

Categories