How to loop user input until an integer is inputted? - java

I'm new to Java and I wanted to keep on asking for user input until the user enters an integer, so that there's no InputMismatchException. I've tried this code, but I still get the exception when I enter a non-integer value.
int getInt(String prompt){
System.out.print(prompt);
Scanner sc = new Scanner(System.in);
while(!sc.hasNextInt()){
System.out.println("Enter a whole number.");
sc.nextInt();
}
return sc.nextInt();
}
Thanks for your time!

Take the input using next instead of nextInt. Put a try catch to parse the input using parseInt method. If parsing is successful break the while loop, otherwise continue.
Try this:
System.out.print("input");
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter a whole number.");
String input = sc.next();
int intInputValue = 0;
try {
intInputValue = Integer.parseInt(input);
System.out.println("Correct input, exit");
break;
} catch (NumberFormatException ne) {
System.out.println("Input is not a number, continue");
}
}

Shorter solution. Just take input in sc.next()
public int getInt(String prompt) {
Scanner sc = new Scanner(System.in);
System.out.print(prompt);
while (!sc.hasNextInt()) {
System.out.println("Enter a whole number");
sc.next();
}
return sc.nextInt();
}

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

Keep gently scanning while you still have input, and check if it's indeed integer, as you need:
String s = "This is not yet number 10";
// create a new scanner
// with the specified String Object
Scanner scanner = new Scanner(s);
while (scanner.hasNext()) {
// if the next is a Int,
// print found and the Int
if (scanner.hasNextInt()) {
System.out.println("Found Int value :"
+ scanner.nextInt());
}
// if no Int is found,
// print "Not Found:" and the token
else {
System.out.println("Not found Int value :"
+ scanner.next());
}
}
scanner.close();

As an alternative, if it is just a single digit integer [0-9], then you can check its ASCII code. It should be between 48-57 to be an integer.
Building up on Juned's code, you can replace try block with an if condition:
System.out.print("input");
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter a whole number.");
String input = sc.next();
int intInputValue = 0;
if(input.charAt(0) >= 48 && input.charAt(0) <= 57){
System.out.println("Correct input, exit");
break;
}
System.out.println("Input is not a number, continue");
}

Related

How do I make ( if condition ) only accept numbers?

I want to put if () condition to length, So that the user can enter numbers only, if he enters string or char, an error appears.
System.out.print("Determine the length of array> ");
int length = input.nextInt();
You can use Scanner#hasNextInt to guard against invalid input.
if(input.hasNextInt()){
int length = input.nextInt();
System.out.println(length);
} else System.out.println("Invalid input");
One of the ways you could achieve it is as below:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Integer val = null;
try {
val = scan.nextInt();
System.out.println(val);
// do whatever you want to do with your input value
} catch (Exception exception) {
System.out.println("you can enter integer only");
// exit program or log error message
}
}
You can use java regex,which is only looking numbers
^[0-9]*$
So let's check if this is valid,
public static void main(String[] args) {
boolean valid = false;
String regexForNumbers = "^[0-9]*$";
Scanner scanner = new Scanner(System.in);
while (!valid) {
System.out.print("Input Value:");
String s = scanner.nextLine();
if(!s.matches(regexForNumbers)){
valid= false;
System.out.println("Not only Numbers, try again\n");
}else{
valid = true;
System.out.println("Only Numbers:"+ s);
}
}
}
So what happens is if the user input contains only numbers the execution will end, otherwise, it will keep asking the user to input, and the output of this simple logic will be.
Input Value:maneesha
Not only Numbers, try again
Input Value:maneesha123
Not only Numbers, try again
Input Value:123
Only Numbers:123

Java incorrect input [duplicate]

This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 6 years ago.
public static void main(String[] args) {
{
Scanner reader = new Scanner(System.in);
System.out.println("Enter your name: ");
String n = reader.nextLine();
System.out.println("You chose: " + n);
}
{
Scanner reader = new Scanner(System.in);
System.out.println("Enter your age: ");
int n = reader.nextInt();
System.out.println("You chose: " + n);
}
{
Scanner reader = new Scanner(System.in);
System.out.println("Enter your email: ");
String n = reader.nextLine();
System.out.println("You chose: " + n);
}
}
If a user places anything else under Enter your age other than a number, how do I make it say that the input is not correct and ask again?
You can get the line provided by the user, then parse it using Integer.parseInt(String) in a do/while loop as next:
Scanner reader = new Scanner(System.in);
Integer i = null;
// Loop as long as i is null
do {
System.out.println("Enter your age: ");
// Get the input from the user
String n = reader.nextLine();
try {
// Parse the input if it is successful, it will set a non null value to i
i = Integer.parseInt(n);
} catch (NumberFormatException e) {
// The input value was not an integer so i remains null
System.out.println("That's not a number!");
}
} while (i == null);
System.out.println("You chose: " + i);
A better approach that avoids catching an Exception based on https://stackoverflow.com/a/3059367/1997376.
Scanner reader = new Scanner(System.in);
System.out.println("Enter your age: ");
// Iterate as long as the provided token is not a number
while (!reader.hasNextInt()) {
System.out.println("That's not a number!");
reader.next();
System.out.println("Enter your age: ");
}
// Here we know that the token is a number so we can read it without
// taking the risk to get a InputMismatchException
int i = reader.nextInt();
System.out.println("You chose: " + i);
No need to declare a variable scanner so often, simply once
care with nextLine(); for strings; presents problems with blanks, advise a .next();
use do-while
do
{
//input
}
while(condition);//if it is true the condition returns to do otherwise leaves the cycle
use blocks try{ .. }catch(Exception){..}
to catch exceptions mismatch-input-type exception is when the input is not what I expected in the example enter a letter when a number expected
Scanner reader = new Scanner(System.in);
int n=0;
do
{
System.out.println("Enter your age: ");
try {
n = reader.nextInt();
}
catch (InputMismatchException e) {
System.out.print("ERROR NOT NUMBER");
}
}
while(n<0 && n>100);//in this case if the entered value is less than 0 or greater than 100 returns to do
System.out.println("You chose: " + n);

Need to close out java with the letter q

I'm pretty new to programming. I need it to say "Enter the letter q to quit or any other key to continue: " at the end. If you enter q, it terminates. If you enter any other character, it prompts you to enter another positive integer.
import java.util.Scanner;
public class TimesTable {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a postive integer: ");
int tableSize = input.nextInt();
printMultiplicationTable(tableSize);
}
public static void printMultiplicationTable(int tableSize) {
System.out.format(" ");
for(int i = 1; i<=tableSize;i++ ) {
System.out.format("%4d",i);
}
System.out.println();
System.out.println("------------------------------------------------");
for(int i = 1 ;i<=tableSize;i++) {
System.out.format("%4d |",i);
for(int j=1;j<=tableSize;j++) {
System.out.format("%4d",i*j);
}
System.out.println();
}
}
}
Do this to have the user input a letter
Info:
System.exit(0) exits the program with no error code.
nextLine() waits for user to enter string and press enter.
nextInt() waits for user to enter int and press enter.
Hope this helps!
Scanner input = new Scanner(System.in);
String i = input.nextLine();
if(i.equalsIgnoreCase("q")) {
System.exit(0);
}else {
System.out.println("Enter a postive integer: ");
int i = input.nextInt();
//continue with your code here
}
This looks like homework ;-)
One way to solve this problem is to put your code that prints your messages and accepts your input inside a while loop, maybe something like:
Scanner input = new Scanner(System.in);
byte nextByte = 0x00;
while(nextByte != 'q')
{
System.out.println("Enter a postive integer: ");
int tableSize = input.nextInt();
printMultiplicationTable(tableSize);
System.out.println("Enter q to quit, or any other key to continue... ");
nextByte = input.nextByte();
}
use a do-while loop in your main method as below
do {
System.out.println("Enter a postive integer: ");
String tableSize = input.next();
if (!"q".equals(tableSize) )
printMultiplicationTable(Integer.parseInt(tableSize));
}while (!"q".equals(input.next()));
input.close();
you would also want to have a try-catch block to handle numberFormatException

How to validate user's input, and read-in their input again if it invalidates, using try-catch?

I want to validate user input using the exception handling mechanism.
For example, let's say that I ask the user to enter integer input and they enter a character. In that case, I'd like to tell them that they entered the incorrect input, and in addition to that, I want them to prompt them to read in an integer again, and keep doing that until they enter an acceptable input.
I have seen some similar questions, but they do not take in the user's input again, they just print out that the input is incorrect.
Using do-while, I'd do something like this:
Scanner reader = new Scanner(System.in);
System.out.println("Please enter an integer: ");
int i = 0;
do {
i = reader.nextInt();
} while ( ((Object) i).getClass().getName() != Integer ) {
System.out.println("You did not enter an int. Please enter an integer: ");
}
System.out.println("Input of type int: " + i);
PROBLEMS:
An InputMismatchException will be raised on the 5th line, before the statement checking the while condition is reached.
I do want to learn to do input validation using the exception handling idioms.
So when the user enters a wrong input, how do I (1) tell them that their input is incorrect and (2) read in their input again (and keep doing that until they enter a correct input), using the try-catch mechanism?
EDIT: #Italhouarne
import java.util.InputMismatchException;
import java.util.Scanner;
public class WhyThisInfiniteLoop {
public static void main (String [] args) {
Scanner reader = new Scanner(System.in);
int i = 0;
System.out.println("Please enter an integer: ");
while(true){
try{
i = reader.nextInt();
break;
}catch(InputMismatchException ex){
System.out.println("You did not enter an int. Please enter an integer:");
}
}
System.out.println("Input of type int: " + i);
}
}
In Java, it is best to use try/catch for only "exceptional" circumstances. I would use the Scanner class to detect if an int or some other invalid character is entered.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean gotInt = false;
while (!gotInt) {
System.out.print("Enter int: ");
if (scan.hasNextInt()){
gotInt = true;
}
else {
scan.next(); //clear current input
System.out.println("Not an integer");
}
}
int theInt = scan.nextInt();
}
}
Here you go :
Scanner sc = new Scanner(System.in);
boolean validInput = false;
int value;
do{
System.out.println("Please enter an integer");
try{
value = Integer.parseInt(sc.nextLine());
validInput = true;
}catch(IllegalArgumentException e){
System.out.println("Invalid value");
}
}while(!validInput);
You can try the following:
Scanner reader = new Scanner(System.in);
System.out.println("Please enter an integer: ");
int i = 0;
while(true){
try{
i = reader.nextInt();
break;
}catch(InputMismatchException ex){
System.out.println("You did not enter an int. Please enter an integer:");
}
}
System.out.println("Input of type int: " + i);

Determine wether input is an int or a string

I have been using Scanner and System.in recently, but I am not able to find a code that can judge whether the input is a String or an integer and then treat it accordingly.
Does anonye know a way?
Use Scanner.next() to get the input String then test with Integer.parseInt(String) if it's integer or not.
try this code:
Scanner scanner = new Scanner(System.in);
if(scanner.hasNext())
{
String s = scanner.next();
try
{
int number = Integer.parseInt(s);
System.out.println("Your input is an integer.");
}
catch(NumberFormatException e)
{
System.out.println("Your input is a String.");
}
}
try{
Integer.parseInt(input);
}catch(NumberFormatException e){
System.out.printerr("Not an integer: " + input);
}

Categories