How to check nextInt from Scanner without consuming the int itself - java

What I am attempting to do is verify user input of an integer between 0-136, while also making sure that the input IS in fact an integer. I can't figure out a good way to do so, as using nextInt in the conditional consumes the int, and you can't compare hasNextInt to integers. Any help would be greatly appreciated!
Here is my code:
public static int retrieveYearsBack() {
Scanner input = new Scanner(System.in);
//Retrieve yearsBack
System.out.println("How many years back would you like to search? (Enter only positive whole numbers less than 136)");
while (!input.hasNextInt([0-136]) {
System.out.println("Invalid entry. Please enter a positive whole number less than 136 only.");
input.next();
}
return input.nextInt();
}
I have also tried:
int myYears = -1;
int tempValue = 0;
while (!input.hasNextInt() || (myYears < 0 || myYears > 136)) {
if (input.hasNextInt())
tempValue = input.nextInt();
if (tempValue > 0 && tempValue < 136)
myYears = tempValue;
else {
System.out.println("Invalid entry. Please enter a positive whole number less than 136 only.");
input.next();
}
}
This try gets stuck in an infinite loop.

I believe that you do need the input.next() call despite what Vivin says. If you can't read an integer from the next line of stdin then you will end up in an infinite loop. Furthermore, you should handle the case where you run out of lines of stdin to process, which can happen where your application's input is from a pipe instead of an interactive session.
In a more verbose style, this might look something like:
public static int retrieveYearsBack() throws Exception
{
Scanner input = new Scanner(System.in);
while (input.hasNext()) {
if (input.hasNextInt()) {
int years = input.nextInt();
if (0 <= years && years <= 136) {
return years;
}
} else {
input.next();
}
System.out.println("Invalid entry. Please enter a positive whole number less than 136.");
}
throw new Exception("Standard in was closed whilst awaiting a valid input from the user.");
}

Related

how to capture enter key when asking for integer input [duplicate]

This question already has an answer here:
hasNextInt() keeps waiting for input when pressing Enter
(1 answer)
Closed 11 months ago.
How do you capture the enter key when using hasNextInt()? I have the following code and am trying to exit gracefully if the user just enters the return key. In the example below I was expecting to get back -9, but the program just hangs on the hasNextInt() line
import java.util.Scanner;
public class InputInt{
public static void main(String[] args){
InputInt x = new InputInt();
System.out.println(x.enterInt());
}
public int enterInt(){
int myInt = -9;
boolean isValid = false;
String lf = "";
Scanner kb = new Scanner(System.in);
while(!isValid){
System.out.print("please enter an integer: ");
if(kb.hasNextInt()){
myInt = kb.nextInt();
isValid = true;
}else{
lf = kb.nextLine();
if (lf.length() == 0)isValid = true;
}
}
return myInt;
}
}
When asking for user input, always use nextLine(), which clears the input buffer (including the trailing newline), then check/parse the input for correctness:
while (true) {
System.out.print("Please enter an integer: ");
String input = kb.nextLine();
if (input.matches("\\d{1,8}")) {
myInt = Integer.parseInt(input);
isValid = true;
break;
} else if (input.ieEmpty()) {
break;
} else {
System.out.print("1 to 8 digits only please, or blank to exit.");
}
The final else is optional, but a nice touch.
The limiting of input to up to 8 digits means you'll never get a error on parsing. To allow every valid integer using regex, see this answer (it's ugly, so viewer discretion is advised).
Note also the more succinct and conventional while (true) with break combination, which obviates the need for overloading the isValid variable, which now means the user entered a valid integer.
To also allow negative numbers, use instead:
if (input.matches("-?\\d{1,8}"))

Where should I put the variable scanner declaration? "int figureNumber = stdin.nextInt();"

I want to make it so that a user entering the wrong data type as figureNumber will see a message from me saying "Please enter an integer" instead of the normal error message, and will be given another chance to enter an integer. I started out trying to use try and catch, but I couldn't get it to work.
Sorry if this is a dumb question. It's my second week of an intro to java class.
import java. util.*;
public class Grades {
public static void main(String args []) {
Scanner stdin = new Scanner(System.in);
System.out.println();
System.out.print(" Please enter an integer: ");
int grade = stdin.nextInt();
method2 ();
if (grade % 2 == 0) {
grade -= 1;
}
for(int i = 1; i <=(grade/2); i++) {
method1 ();
method3 ();
}
}
}
public static void main(String args[]) {
Scanner stdin = new Scanner(System.in);
System.out.println();
System.out.print(" Welcome! Please enter the number of figures for your totem pole: ");
while (!stdin.hasNextInt()) {
System.out.print("That's not a number! Please enter a number: ");
stdin.next();
}
int figureNumber = stdin.nextInt();
eagle();
if (figureNumber % 2 == 0) { //determines if input number of figures is even
figureNumber -= 1;
}
for (int i = 1; i <= (figureNumber / 2); i++) {
whale();
human();
}
}
You need to check the input. The hasNextInt() method is true if the input is an integer. So this while loop asks the user to enter a number until the input is a number. Calling next() method is important because it will remove the previous wrong input from the Scanner.
Scanner stdin = new Scanner(System.in);
try {
int figureNumber = stdin.nextInt();
eagle();
if (figureNumber % 2 == 0) { //determines if input number of figures is even
figureNumber -= 1;
}
for(int i = 1; i <=(figureNumber/2); i++) {
whale();
human();
}
}
catch (InputMismatchException e) {
System.out.print("Input must be an integer");
}
You probably want to do something like this. Don't forget to add import java.util.*; at the beginning of .java file.
You want something in the form:
Ask for input
If input incorrect, say so and go to step 1.
A good choice is:
Integer num = null; // define scope outside the loop
System.out.println("Please enter a number:"); // opening output, done once
do {
String str = scanner.nextLine(); // read anything
if (str.matches("[0-9]+")) // if it's all digits
num = Integer.parseInt(str);
else
System.out.println("That is not a number. Please try again:");
} while (num == null);
// if you get to here, num is a number for sure
A do while is a good choice because you always at least one iteration.
It's important to read the whole line as a String. If you try to read an int and one isn't there the call will explode.
You can actually test the value before you assign it. You don't need to do any matching.
...
int figureNumber = -1;
while (figureNumber < 0) {
System.out.print(" Welcome! Please enter the number of figures for your totem pole: ");
if (stdin.hasNextInt()){
figureNumber = stdin.nextInt(); //will loop again if <0
} else {
std.next(); //discard the token
System.out.println("Hey! That wasn't an integer! Try again!");
}
}
...

looping back to beginning of statement using while loop (java)

I've been given the task of making a factorial calculator that takes input from 9 to 16 using a while loop. The conditions are that if the user puts in an input that is not 9 to 16 or an int, it should loop back in the beginning and ask for input again.
My code looks like this:
Scanner myScanner;
int x = 1;
int factorial=1;
int input;
myScanner = new Scanner(System.in);
System.out.println("put in an int and i will show you its factorial");
while (true) {
input = myScanner.nextInt();
if (input<9 || input >16) {
System.out.println("please enter a valid int");
}
else{
break;
}
}
for (int i=input; i >0; i--) {
factorial *= i;
}
The problem is that this isn't really using a while loop to go back to the beginning of the code. I'm really just inputting a redundant statement to make it a while loop.
So I guess my question is, how can I make a while loop that goes back to the beginning of the loop if the wrong input is typed in?
an alternative is to use a boolean value such as
boolean validInput = false;
and loop until you have valid input. that way you won't try to calculate a value when users enter -1 in the other answer
Try doing it this way:
Scanner myScanner;
int x = 1;
int factorial=1;
int input = 0;
myScanner = new Scanner(System.in);
System.out.println("Put in an integer value between 9 and 16 and I will show you its factorial. Type -1 to exit.");
while (input != -1) {
//Try block for handling invalid string inputs
try {
input = myScanner.nextInt();
} catch (Exception e){
input = 0;
}
if (input<9 || input >16) {
System.out.println("please enter a valid int");
}
else {
for (int i=input; i >0; i--) {
factorial *= i;
//input = -1; //Optionally end here if that's how things are intended to function
}
System.out.println(factorial);
}
}
Initialize the input with a value (0). And inform the user if they type in a certain value (i.e. -1) the loop ends. Move your for loop in the else block and set the while condition as input != 1.
Alternatively, if you want the program to end if the user supplies a valid value, then in the else block, set the input value to -1 manually, or just break out of the loop using the break keyword.

how do i prompt a user to re enter their input value, if the value is invalid?

public int inputNumber() {
Scanner input = new Scanner (System.in);
System.out.print("Enter the number of cookies you'd like to make ");
int number = input.nextInt();
if (number <=0) {
System.out.println(" please enter a valid number")
int number = input.nextInt();
}
input.close();
return number;
}
EDIT:
I should have used a while loop.. throwback to literally my first project.
System.out.print("Enter the number of cookies you'd like to make:");
int number = input.nextInt();
while(number<=0) //As long as number is zero or less, repeat prompting
{
System.out.println("Please enter a valid number:");
number = input.nextInt();
}
This is about data validation. It can be done with a do-while loop or a while loop. You can read up on topics of using loops.
Remarks on your codes:
You shouldn't declare number twice. That is doing int number more than once in your above codes (which is within same scope).
This way you have fewer superfluous print statements and you don't need to declare you variable multiple times.
public int inputNumber() {
Scanner input = new Scanner (System.in);
int number = 0;
do {
System.out.print("Enter the number of cookies you'd like to make ");
number = input.nextInt();
} while(number <= 0);
input.close();
return number;
}
Couple of issues:
You are missing semicolon in you println method.
You are redefining the number within if
you are using if which is for checking number instead use while so until and unless user enters correct number you dont proceed.
public int inputNumber() {
Scanner input = new Scanner (System.in);
System.out.print("Enter the number of cookies you'd like to make ");
int number = input.nextInt();
while (number <=0) {
System.out.println(" please enter a valid number");
number = input.nextInt();
}
input.close();
return number;
}
The classical way of doing that is to limit the number of retry and abort beyond that ::
static final int MAX_RETRY = 5; // what you want
...
int max_retry = MAX_RETRY;
int number;
while (--max_retry >= 0) {
System.out.print("Enter the number of cookies you'd like to make ");
number = input.nextInt();
if (number > 0) {
break;
}
System.out.println("Please enter a valid number")
}
if (max_retry == 0) {
// abort
throw new Exception("Invalid input");
}
// proceed with number ...

Right Loop for this exercise in Java

Hi guys i am learning java in order to code in Android, i got some experience in PHP, so i got assigned an exercise but cant find the right loop for it, i tried else/if, while, still cant find it, this is the exercise:
1- prompt the user to enter number of students, it must be a number that can divide by 10 (number / 10) = 0
2- check of user input, if user input not dividable by 10 keep asking the user for input until he enter the right input
How i code it so far, the while loop not working any ideas how to improve it or make it work?
package whiledowhile;
import java.util.Scanner;
public class WhileDoWhile {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
/* int counter = 0;
int num;
while (counter <= 100) {
System.out.println("Enter number");
num = user_input.nextInt();
counter += num; // counter = counter + num
//counter ++ = counter =counter +1
}
System.out.println("Sum = "+ counter);
*/
int count = 0;
int num;
System.out.println("Please enter a number: ");
num = user_input.nextInt();
String ex;
do {
System.out.print("Wrong Number please enter again: " );
num++;
}
while(num/10 != 0 );
}
}
When using a while loop, you'll want to execute some code while a condition is true. This code needs to go inside the do or while block. For your example, a do-while loop seems more appropriate, since you want the code to execute at least one time. Also, you'll want to use the modulo operator, %, inside of your while condition, not /. See below:
Scanner s = new Scanner(System.in);
int userInput;
do {
// Do something
System.out.print("Enter a number: ");
userInput = s.nextInt();
} while(userInput % 10 != 0);
Two things:
I think you mean to use %, not /
You probably want to have your data entry inside of your while loop
while (num % 10 != 0) {
// request user input, update num
}
// do something with your divisible by 10 variable

Categories