Determine wether input is an int or a string - java

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

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

input value stays 0 when trying to prompt their input

I am trying to prompt a user with the value they inputted and an error message if it's not an integer. When I try to prompt them, their input stays 0 when the input is a double or string.
//main method
public static void main(String[] args) {
int i = 0;
//instantiate new Scanner for user input
Scanner input = new Scanner(System.in);
//parse imput, display value
//and prompt user that their input is not a int
try {
inputNum = Integer.parseInt(input.next());
System.out.println("Value entered is " +
String.valueOf(inputNum));
} catch(NumberFormatException e) {
System.out.println("Value entered is " +
String.valueOf(inputNum));
System.out.println(String.valueOf(inputNum) + " is not an integer.");
}
}
}
If the input is a double or a string then parseInt would throw an exception and inputNum would not be assigned any new value. You could store input.next() in a string before passing it to parseInt - or you might be able to use e in the catch block to figure out the bad value
String s;
//parse imput, display value
//and prompt user that their input is not a int
try {
s = input.next();
System.out.println("Value entered is " + s);
inputNum = Integer.parseInt(s);
} catch(NumberFormatException e) {
System.out.println(s + " is not an integer.");
}
}
}
Well, it's a concept ('ask user for some input, keep asking if it is not valid') that you may want to do more than once, so it has no business being in main.
Give it its own method.
This method would take as input a 'prompt' and will return a number. The purpose is to ask the user (with that prompt) for a number, and to keep asking until they enter one.
You can use while() to loop code until a certain condition is met, or simply forever, using return to escape the loop and the entire 'ask the user for a number' method in one fell swoop.
I've modified the code to make it work according to your need:
public static void main(String[] args) {
//instantiate new Scanner for user input
Scanner input = new Scanner(System.in);
//parse imput, display value
//and prompt user that their input is not a int
String inputNum = input.next();
try {
System.out.println("Value entered is " +
Integer.parseInt(inputNum));
} catch (NumberFormatException e) {
System.out.println("Value entered is " +
inputNum);
System.out.println(inputNum + " is not an integer.");
}
}
Above is the standard approach to check if a String is an integer in java. If you want a simpler & powerful way you can leverage the Apache Commons library:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
final String num = input.next();
// check to see if num is a number
if (NumberUtils.isCreatable(num)) {
System.out.println("Value entered is " + num);
} else {
System.out.println("Value entered is " + num);
System.out.println(num + " is not a number.");
}
}
Note that NumberUtils#isCreatable checks for a wide variety of number formats(integer, float, scientific...)
If you want something equivalent to Integer#parseInt, Long#parseLong, Float#parseFloat or Double#parseDouble. Use instead, NumberUtils#isParsable.
There is an another concise way to do it without throwing any exception, you can use hasNextInt() to pre-validate if the input value is a valid integer before hand, then use nextInt() to read an integer without parsing the string:
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int inputNum;
if(scanner.hasNextInt()){
inputNum = scanner.nextInt();
System.out.println("Value entered is " + inputNum);
}else{
System.out.println(scanner.next() + " is not an integer.");
}
}

how to check and display an error message if the input is not a number in java

How to have a try and catch statement to validate the input in variable odd is a number else print an error message? I am new in java programming. Appreciate any help
import java.util.Scanner;
public class ScenarioB{
public static void main (String[]args){
int odd;
Scanner scan = new Scanner(System.in);
System.out.print("Enter An Odd Number\n");
odd = scan.nextInt();
}
}
The Scanner class has a method for this
Scanner in = new Scanner(System.in);
int num;
if(in.hasNextInt()){
num = in.nextInt();
System.out.println("Valid number");
}else{
System.out.println("Not a valid number");
}
Output 1:
8
Valid number
Output 2:
a
Not a valid number
Your code will like bellow:
try {
int scannedNumber;
Scanner scan = new Scanner(System.in);
System.out.print("Enter An Odd Number\n");
String userInput = scan.nextLine();
System.out.println("You pressed :" + userInput);
scannedNumber = Integer.parseInt(userInput);
if (scannedNumber % 2 == 0) {
throw new Exception("Not an odd number");
}
System.out.println("You pressed odd number");
} catch (Exception e) {
System.out.println("" + e.getMessage());
}
Here after taking input as String. Then cast as integer. If casting failed then it will throw NumberFormatException. If it is a number then check is it odd? If not odd then it is also throwing an exception.
Hope this will help you.
Thanks :)

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

How to loop user input until an integer is inputted?

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

Categories