How to Loop User Input Until an Integer Is Inputted

How to loop user input until an integer is inputted?

Working on Juned's code, I was able to make it shorter.

int getInt(String prompt) {
System.out.print(prompt);
while(true){
try {
return Integer.parseInt(new Scanner(System.in).next());
} catch(NumberFormatException ne) {
System.out.print("That's not a whole number.\n"+prompt);
}
}
}

How to loop a user input until integer is entered?

try this

public int[] createArrays(Scanner s) {
int size;
System.out.print("Enter the number of students: ");

while(true) {
try {
size = Integer.parseInt(s.nextLine());
break;
}catch (NumberFormatException e) {
System.out.println();
System.out.println("You have entered wrong number");
System.out.print("Enter again the number of students: ");
continue;
}
}

int scores[] = new int[size];
System.out.println("Enter " + size + " scores:");
for (int i = 0; i < size; i++) {
scores[i]=getValidInt(s,"Score " + (i + 1) + ": ");
}
return scores;
}

User Input of Integers Infinite Loop Until User Inputs a Character (C)

Very close but I've marked a couple of changes:

#include <stdio.h>

int main(void)

{
int i=0;
char x = 'x'; // Note: single quotes for char, double for string

printf("Enter an integer to check whether your number is odd or even\n");
printf("Enter an ´x´ at any time to quit the program\n");

do
{
int n = scanf("%d", &i); // Check if number was read
if (n == 1) {
if (i % 2 == 0)
{
printf("The number is even\n");
}
else // Only other possibility
{
printf("The number is odd\n");
}

} else // No number, see if there's an 'x'
{
scanf(" %c", &x);
if (x == 'x')
{
printf("The program will now terminate\n");
return 0;
} else
{
printf("Unknown input %c\n", x);
}
}
}
while (i > 0); // Will also end if user enters <= 0

return 0;
}

Using a while loop to iterate through user input until specific number

Push the scanf into the while condition. Something like

while (scanf("%d", &x) != EOF && x != 84)
print("%d\n", x);

How to keep asking user to input until condition is satisfied in C?

I recommend that you use the following code:

#include <stdio.h>

int main( void )
{
int u1,u2,u3;

for (;;) //infinite loop, equivalent to while(true)
{
printf( "Enter 3 Numbers: " );
scanf( "%d %d %d", &u1, &u2, &u3 );

if ( u1!=u2 && u2!=u3 && u3!=u1 )
break;

printf( "Error: Condition is not satisfied!\n" );
}
}

In contrast to one of the other answers, this solution has the advantage that it only checks the condition once per loop iteration.

However, the above code (and the code of most other answers) has a serious issue: If the user enters an alphabetical letter instead of a number, the program will get stuck in an infinite loop. This is because it is not safe to call scanf without checking the return value. See the following page for more information on why it is unsafe: A beginners' guide away from scanf()

Therefore, it would be better to check the return value of scanf and to consume all characters on the remainder of the line. Consuming all leftover characters is important, because otherwise, if the user enters 6abc, then scanf will consume the 6, but leave abc on the input stream, so that the next time scanf is called (which will be in the next loop iteration), it will attempt to match abc and fail immediately without waiting for further input. This would cause an infinite loop.

#include <stdio.h>
#include <stdlib.h>

int main( void )
{
int u1,u2,u3;
int ret;

for (;;) //infinite loop, equivalent to while(true)
{
printf( "Enter 3 Numbers: " );
if ( ( ret = scanf( "%d %d %d", &u1, &u2, &u3 ) ) != 3 )
{
int c;

//check for unrecoverable error
if ( ret == EOF )
{
fprintf( stderr, "Unrecoverable input error!\n" );
exit( EXIT_FAILURE );
}

//print error message for recoverable error
printf( "Unable to convert input!\n" );

//consume all leftover characters on the line
do
{
c = getchar();

} while ( c != EOF && c != '\n' );
}

if ( u1!=u2 && u2!=u3 && u3!=u1 )
break;

printf( "Error: Condition is not satisfied!\n" );
}
}

Asking the user for input until they give a valid response

The simplest way to accomplish this is to put the input method in a while loop. Use continue when you get bad input, and break out of the loop when you're satisfied.

When Your Input Might Raise an Exception

Use try and except to detect when the user enters data that can't be parsed.

while True:
try:
# Note: Python 2.x users should use raw_input, the equivalent of 3.x's input
age = int(input("Please enter your age: "))
except ValueError:
print("Sorry, I didn't understand that.")
#better try again... Return to the start of the loop
continue
else:
#age was successfully parsed!
#we're ready to exit the loop.
break
if age >= 18:
print("You are able to vote in the United States!")
else:
print("You are not able to vote in the United States.")

Implementing Your Own Validation Rules

If you want to reject values that Python can successfully parse, you can add your own validation logic.

while True:
data = input("Please enter a loud message (must be all caps): ")
if not data.isupper():
print("Sorry, your response was not loud enough.")
continue
else:
#we're happy with the value given.
#we're ready to exit the loop.
break

while True:
data = input("Pick an answer from A to D:")
if data.lower() not in ('a', 'b', 'c', 'd'):
print("Not an appropriate choice.")
else:
break

Combining Exception Handling and Custom Validation

Both of the above techniques can be combined into one loop.

while True:
try:
age = int(input("Please enter your age: "))
except ValueError:
print("Sorry, I didn't understand that.")
continue

if age < 0:
print("Sorry, your response must not be negative.")
continue
else:
#age was successfully parsed, and we're happy with its value.
#we're ready to exit the loop.
break
if age >= 18:
print("You are able to vote in the United States!")
else:
print("You are not able to vote in the United States.")

Encapsulating it All in a Function

If you need to ask your user for a lot of different values, it might be useful to put this code in a function, so you don't have to retype it every time.

def get_non_negative_int(prompt):
while True:
try:
value = int(input(prompt))
except ValueError:
print("Sorry, I didn't understand that.")
continue

if value < 0:
print("Sorry, your response must not be negative.")
continue
else:
break
return value

age = get_non_negative_int("Please enter your age: ")
kids = get_non_negative_int("Please enter the number of children you have: ")
salary = get_non_negative_int("Please enter your yearly earnings, in dollars: ")

Putting It All Together

You can extend this idea to make a very generic input function:

def sanitised_input(prompt, type_=None, min_=None, max_=None, range_=None):
if min_ is not None and max_ is not None and max_ < min_:
raise ValueError("min_ must be less than or equal to max_.")
while True:
ui = input(prompt)
if type_ is not None:
try:
ui = type_(ui)
except ValueError:
print("Input type must be {0}.".format(type_.__name__))
continue
if max_ is not None and ui > max_:
print("Input must be less than or equal to {0}.".format(max_))
elif min_ is not None and ui < min_:
print("Input must be greater than or equal to {0}.".format(min_))
elif range_ is not None and ui not in range_:
if isinstance(range_, range):
template = "Input must be between {0.start} and {0.stop}."
print(template.format(range_))
else:
template = "Input must be {0}."
if len(range_) == 1:
print(template.format(*range_))
else:
expected = " or ".join((
", ".join(str(x) for x in range_[:-1]),
str(range_[-1])
))
print(template.format(expected))
else:
return ui

With usage such as:

age = sanitised_input("Enter your age: ", int, 1, 101)
answer = sanitised_input("Enter your answer: ", str.lower, range_=('a', 'b', 'c', 'd'))

Common Pitfalls, and Why you Should Avoid Them

The Redundant Use of Redundant input Statements

This method works but is generally considered poor style:

data = input("Please enter a loud message (must be all caps): ")
while not data.isupper():
print("Sorry, your response was not loud enough.")
data = input("Please enter a loud message (must be all caps): ")

It might look attractive initially because it's shorter than the while True method, but it violates the Don't Repeat Yourself principle of software development. This increases the likelihood of bugs in your system. What if you want to backport to 2.7 by changing input to raw_input, but accidentally change only the first input above? It's a SyntaxError just waiting to happen.

Recursion Will Blow Your Stack

If you've just learned about recursion, you might be tempted to use it in get_non_negative_int so you can dispose of the while loop.

def get_non_negative_int(prompt):
try:
value = int(input(prompt))
except ValueError:
print("Sorry, I didn't understand that.")
return get_non_negative_int(prompt)

if value < 0:
print("Sorry, your response must not be negative.")
return get_non_negative_int(prompt)
else:
return value

This appears to work fine most of the time, but if the user enters invalid data enough times, the script will terminate with a RuntimeError: maximum recursion depth exceeded. You may think "no fool would make 1000 mistakes in a row", but you're underestimating the ingenuity of fools!

Write a program that repeatedly asks a user to enter a positive integer until they enter a positive integer number

num = int(input("Enter a positive integer: "))

while num <= 0:
num = int(input("Enter a positive integer: "))

print(f"{num} is positive.")

This should work. Your while-loop is checking if the number is positive, but you are not changing the number based on the new input.

C programming - Loop until user inputs number scanf

scanf returns the count of items that it has successfully read according to your format. You can set up a loop that exits only when scanf("%d", &number2); returns 1. The trick, however, is to ignore invalid data when scanf returns zero, so the code would look like this:

while (scanf("%d",&number2) != 1) {
// Tell the user that the entry was invalid
printf("You did not enter a valid number\n");
// Asterisk * tells scanf to read and ignore the value
scanf("%*s");
}

Since you read a number more than once in your code, consider making a function to hide this loop, and call this function twice in your main to avoid duplication.



Related Topics



Leave a reply



Submit