how to check whether the input is integer or not - java

I a making a program that will ask an int input from user and check whether user input is an integer or not. If no the program asks for an input tile it gets a integer.
Scanner in = new Scanner(System.in);
System.out.println("Eneter a nuber here:");
int num;
if (in.hasNextInt()){
num =in.nextInt();
if(num % 2 == 0){
System.out.print("this is even!!");
} else{
System.out.println("this is odd!!");
}
} else {
System.out.print("pleas enter an integer only!!!");
num = in.nextInt();
if(num % 2 == 0){
System.out.print("this is even second check!!");
} else{
System.out.println("this is odd second check!!");
}
}
here is the code but i have some mistakes in there. it brings an error when input is not an int. pleas help with this, thanks in advance!

Try the below code, it will end only if its a valid Integer otherwise it will keep asking for Integer and I think you are looking for the same.
public void checkInt() {
Scanner scanner = new Scanner(System.in);
System.out.println("Eneter a nuber here:");
try {
int num = scanner.nextInt();
if (num % 2 == 0) {
System.out.print("this is even!!");
} else {
System.out.println("this is odd!!");
}
} catch (InputMismatchException e) {
System.out.println("pleas enter an integer only!!!");
checkInt();
}
}

You must read user input as String. Then, inside a try/catch block, make a casting to integer (Integer.parseInt()), if throws a exception is because is not a number.

May be a stupid way but this can solve your problem:
String x;
x = "5";//or get it from user
int y;
try{
y = Integer.parseInt(x);
System.out.println("INTEGER");
}catch(NumberFormatException ex){
System.out.println("NOT INTEGER");
}
Edited:
The program will try to convert the string to integer. If it is integer it will succeed else it will get exception and be caught.
Another way is to check the ASCII value.
To continue till integer is encountered:
String x;
Scanner sc = new Scanner(System.in);
boolean notOk;
do{
x = sc.next();
notOk = check(x);
}while(notOk);
System.out.println("Integer found");
}
private static boolean check(String x){
int y;
try{
y = Integer.parseInt(x);
return false;
}catch(NumberFormatException ex){
return true;
}
}

import java.util.Scanner;
public class Test {
public static void main(String args[] ) throws Exception {
Scanner sc=new Scanner(System.in);
if(sc.hasNextInt())
System.out.println("Input is of int type");
else
System.out.println("This is something else");
}
}

Related

Loop when incorrect input is given?

So basically I've been trying to get this small simple code to work but I'm running into the problem of making a loop. What I want to happen is basically this: User enters an Integer, if its not an integer it will display an error and ask for an Integer until and Integer is given. I'm having a difficult time setting up a loop cause I don't quite know what to do. Im pretty new and dumb so this is probably really easy but I'm kind of an idiot and suck at this but I'm learning.
Here's what I have.
import java.util.Scanner;
public class Loop{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter an Integer: ");
if (scan.hasNextInt()) {
int Index = scan.nextInt();
scan.nextLine();
System.out.println("Index = " + Index);
}
else if (scan.hasNextDouble()) {
System.out.println("Error: Index is Double not Integer.");
}
else {
System.out.println("Error: Index is not Integer.");
}
}
}
You can use while loop for that.
while (true) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter an Integer: ");
if (scan.hasNextInt()) {
int Index = scan.nextInt();
scan.nextLine();
System.out.println("Index = " + Index);
break;
} else if (scan.hasNextDouble()) {
System.out.println("Error: Index is Double not Integer.");
} else {
System.out.println("Error: Index is not Integer.");
}
}
You need to use a loop (for or while) to your code. You can do it like this.
import java.util.Scanner;
public class Loop {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Enter an Integer: ");
if (scan.hasNextInt()) {
int Index = scan.nextInt();
scan.nextLine();
System.out.println("Index = " + Index);
} else if (scan.hasNextDouble()) {
System.out.println("Error: Index is Double not Integer.");
} else {
System.out.println("Error: Index is not Integer.");
}
// add same condition to break the loop
}
// close the scanner
scan.close()
}
}

do while loop and user input issue

I'm trying to make a program where a user needs to input a random integer. If the user inputs a String I want an error message to pop out: "This is not a number" and after that restart the program until the user inputs a number. I got this so far and I'm stuck. I just get an error message if I input a string and program crashes.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = 0;
do {
System.out.println("Input a number!");
number = scanner.nextInt();
if (!scanner.hasNextInt()) {
System.err.println("This is not a number");
}
} while (!scanner.hasNextInt());
System.out.println("You entered: " + number);
}
You're getting an InputMisMatchException because if you input a string into a scanner.nextInt(), it will immediately give an error and stop the program before it does anything else, so it won't reach your if statement. One way to get around this issue is to instead receive user input as a string, try to parse it for an int, and end the loop if it doesn't throw an exception. This is my implementation:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = "";
int number = 0;
boolean end = true;
do {
System.out.println("Input a number!");
input = scanner.nextLine();
try {
number = Integer.parseInt(input);
end = true;
} catch(Exception e) {
System.err.println("This is not a number");
end = false;
}
} while (!end);
System.out.println("You entered: " + number);
}
See if the below code can help achieve what you want to do.
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String number;
do {
System.out.println("Input a number!");
number = scanner.next();
} while (!isNumeric(number));
System.out.println("You entered: " + number);
}
public static boolean isNumeric(final String str) {
// null or empty
if (str == null || str.length() == 0) {
return false;
}
return str.chars().allMatch(Character::isDigit);
}
}

Ask user to input a double instead of a String without making the program shutdown

Hy, I wrote this piece of code where I'm asking the user to input a number:
public static double[] getscores()
{
int numscores=8;
double score[] = new double[numscores];
for (int a=0;a<numscores;a++)
{
Scanner ip=new Scanner(System.in);
System.out.println("Enter a score");
score[a]=ip.nextDouble();
}
return score;
}
In the eventuality where the user accidentally enters a String, how am I supposed to tell him to input a number without making the program shut down? Thanks You
You should catch the exception thrown when the user doesn't input a double, ask the user to try again, and keep looping there until the user inputs a double. Alternatively, you can use while(true) and a break statement instea of a do { ... } while. Perhaps that is a bit shorter, but this is more readable.
Use a BufferedReader instead, because Scanner does not consume the input if it fails to parse it, so you'll get stuck in an infinite loop.
public static double[] getScores() throws IOException {
final int NUM_SCORES = 8;
double[] score = new double[NUM_SCORES];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for (int i = 0; i < NUM_SCORES; i++) {
System.out.println("Enter a score:");
boolean isDouble = false;
do {
try {
score[i] = Double.parseDouble(br.readLine());
isDouble = true;
} catch (NumberFormatException e) {
System.out.println("You didn't enter a double. Please try again!");
}
} while (!isDouble);
}
br.close();
return score;
}
The user is always entering a String; Scanner#nextDouble() is a convenience method to interpret String input as a double.
Write a method that keeps reading input until a double is entered:
static double readDouble(Scanner scanner) {
double score;
while (true) {
System.out.println("Enter a score");
String input = scanner.nextLine();
try {
score = Double.parseDouble(input);
break;
} catch (NumberFormatException e) {
System.out.println("'" + input + "' is not a valid score");
}
}
return score;
}
then call it from your loop:
score[a] = readDouble(ip);
A quick but "dirty" solution would be by using try-catch:
public static double[] getscores() {
int numscores = 8;
double score[] = new double[numscores];
for (int a = 0; a < numscores; a++) {
Scanner ip = new Scanner(System.in);
System.out.println("Enter a score");
try{
score[a] = ip.nextDouble();
} catch(InputMismatchException ime) {
System.out.println("Wrong input");
a--;
}
}
return score;
}

How to resolve InputMismatchException?

package exercises;
import java.util.*;
public class Try_and_catch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x=1;
do
{
System.out.println("Enter first number");
int n1 = input.nextInt();
System.out.println("Enter second number");
int n2 = input.nextInt();
int sum= n1/n2;
System.out.println(sum);
} while(x==1);
}
}
The code above requires input only integers, my question is how to handle the error whenever the user input a character?
Use a try block:
boolean again = true;
int n1;
while (again) {
try {
System.out.println("Enter first number");
input.nextInt();
again=false;
}
catch(InputMismatchException ime)
{
// do nothing!
}
}
What happens here is pretty simple: if we get an exception, then "again" is not set to true and we go back around in the loop. If we get out of the try block without an exception, then again is toggled and we go merrily on our way.

How to implement int validation, so the input can only be an int and between a min and max?

I'm wondering how do I go about validating this code so the input can only be an int and between a min and max? So far I can only stop the input being less than 1 and whatever maximum is used. But I cant seem to create a scenario where if the user inputs anything other than between the max and min (e.g. "AAA") it loops. I keep getting an Input Mismatch error. Any help would be greatly appreciated!
private static int getUserOption(String prompt, int max) {
int h;
do {
Scanner sc = new Scanner(System.in);
System.out.print(prompt);
h=sc.nextInt();
if(!sc.hasNextInt()) {
System.out.println("Invalid option. Try again!:");
}
} while(h<1 || h>max);
return h;
}
The loop is breaking because the nextInt() method is throwing an exception, which terminates the method early.
One option would be to use a try / catch block to trap the exception:
private static int getUserOption(String prompt, int max) {
int h = 0;
do {
Scanner sc = new Scanner(System.in);
System.out.print(prompt);
try {
h=sc.nextInt();
} catch (InputMismatchException e) {
System.out.println("Invalid option. Try again!:");
}
}while(h<1 || h>max);
return h;
}
You Can try this Code !
Scanner sc = new Scanner(System.in);
int number;
do {
System.out.println("Please enter a valid number: ");
while (!sc.hasNextInt()) {
System.out.println("Error. Please enter a valid number: ");
sc.next();
}
number = sc.nextInt();
} while (!checkChoice(number));
private static boolean checkChoice(int choice){
if (choice <MIN || choice > MAX) { //Where MIN = 0 and MAX = 20
System.out.print("Error. ");
return false;
}
return true;
}
Ref. Validating input with while loop and scanner
a few points:
1. to check if the input is less than a min value just add int min to the method signature.
2. to check if input is an int, catch InputMismatchException.
The revised code would be:
private static int getUserOption(String prompt, int max, int min) {
int h;
do {
Scanner sc = new Scanner(System.in);
System.out.print(prompt);
try {
h=sc.nextInt();
} catch (InputMismatchException e) {
System.out.println("Invalid option. Try again!:");
}
} while(h<min || h>max);
return h;
}
I couldn't understand if you want to keep asking until the user types a valid answer or just ask once. The while block suggests to keep asking until is a valid input.
Here is a small snippet that what you request. I suggest that you read some books, there a plenty of suggestions at SO.
public static class InvalidUserException extends Exception {
public InvalidUserException(String message) {
super(message);
}
public InvalidUserException(String message, Throwable cause) {
super(message, cause);
}
}
private static int getIntFromScanner(int max) throws InvalidUserException {
int nextInt = 0;
Scanner sc = new Scanner(System.in);
try {
nextInt = sc.nextInt();
} catch (InputMismatchException e) {
throw new InvalidUserException("Input must be a valid Integer", e);
}
if (nextInt > max) {
throw new InvalidUserException(
"Input is bigger than allowed! Max: " + max + " Input: "
+ nextInt);
}
return nextInt;
}
public static int getUserOption(String prompt, int max) {
System.out.println(prompt);
do {
try {
return getIntFromScanner(max);
} catch (InvalidUserException e) {
System.out.println("Invalid option. Try again ("
+ e.getMessage() + ")");
}
} while (true);
}
public static void main(String[] args) {
int userOption = getUserOption("Gimme less than or equal 6!", 6);
System.out.println("You gave me " + userOption);
}

Categories