I have written a JAVA program that takes input from the user and check if the user has entered the correct thing or not. I have taken the input from the Scanner class. If the user enters an invalid character like a String, I want to display ‘Invalid Input’.
public class Main {
public static void main(String[] args) {
Scanner takeInteger = new Scanner(System.in);
System.out.println("Enter a number");
int enteredNumber = takeInteger.nextInt();
}
}
jpllosa
2,0661 gold badge28 silver badges28 bronze badges
asked Jul 7, 2021 at 15:37
2
Just ask the Scanner
whether the next input is a valid int value, e.g.
Scanner takeInteger = new Scanner(System.in);
System.out.println("Enter a number");
while(!takeInteger.hasNextInt()) {
System.out.println("Invalid Input: " + takeInteger.next());
}
int enteredNumber = takeInteger.nextInt();
This will retry the operation until the user entered a number. If you just want a single attempt, use something like
Scanner takeInteger = new Scanner(System.in);
System.out.println("Enter a number");
if(!takeInteger.hasNextInt()) {
System.out.println("Invalid Input: " + takeInteger.next());
}
else {
int enteredNumber = takeInteger.nextInt();
// ... proceed with the input
}
answered Jul 7, 2021 at 16:50
HolgerHolger
283k40 gold badges429 silver badges756 bronze badges
You will get an Exception that is InputMismatchException
when an invalid input is passed.(i.e except integer value),you can use a try-catch block to hold the exception and inform the user about the invalid input. Try block , Catch block
import java.util.*;
Scanner takeInteger = new Scanner(System.in);
System.out.println("Enter a number");
try{
int enteredNumber = takeInteger.nextInt();
}
catch(InputMismatchException e) {
System.out.println("Enter a valid input");
}
answered Jul 7, 2021 at 15:52
Ashish MishraAshish Mishra
6941 gold badge6 silver badges20 bronze badges
2
You can use Exception handling for the same.
public class Main {
public static void main(String[] args) {
Scanner takeInteger = new Scanner(System.in);
System.out.println("Enter a number");
try {
int enteredNumber = takeInteger.nextInt();
}
catch (Exception e) {
System.out.println("Invalid Input");
}
}
}
jpllosa
2,0661 gold badge28 silver badges28 bronze badges
answered Jul 7, 2021 at 15:53
Sonam GuptaSonam Gupta
3282 silver badges11 bronze badges
2
You can add a try-catch
block in your program to check if the user’s input is a number or not.
Scanner takeInteger = new Scanner(System.in);
System.out.println("Enter a number");
String input = takeInteger.next();
int enteredNumber;
try
{
enteredNumber = Integer.parseInt(input); // Input is a number
}
catch(NumberFormatException ex)
{
System.out.println("Wrong Input!"); // Invalid input
}
answered Jul 7, 2021 at 15:51
GURU ShreyanshGURU Shreyansh
8711 gold badge6 silver badges18 bronze badges
0
You need to call the .nextLine
method of the Scanner class and then parse to the desired type.
Example:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
String line = sc.nextLine();
try {
int enteredNumber = Integer.parseInt(line);
System.out.println("You have entered: " + enteredNumber);
} catch (Exception e) {
System.out.println("Invalid Input");
}
}
}
Result with a number:
Enter a number
12
You have entered: 12
Result a text:
Enter a number
abcd
Invalid Input
answered Jul 7, 2021 at 15:53
mamadalievmamadaliev
1332 silver badges9 bronze badges
Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article
PHP can be easily embedded in HTML files and HTML codes can also be written in a PHP file. The thing that differentiates PHP from a client-side language like HTML is, PHP codes are executed on the server whereas HTML codes are directly rendered on the browser. To display error for invalid input with HTML and PHP.
Approach:
Display error on invalid error when
- input textbox is left empty.
- input is wrong.
PHP code: The following is the code for “form.php” which is used in the HTML code in the later part.
To show invalid input in PHP, set the name of the input textbox which is in HTML. All the fields are first checked for empty fields and then it is validated for correctness. If all fields are correct then it shows the success message. If the input given by the user is wrong then it will show a message for ” Invalid input!!”.
PHP
<?php
$nameError
=
""
;
$emailError
=
""
;
$passwordError
=
""
;
$mobileError
=
""
;
$success
=
""
;
function
validate_input(
$input
) {
$input
= trim(
$input
);
$input
=
stripslashes
(
$input
);
$input
= htmlspecialchars(
$input
);
return
$input
;
}
if
(isset(
$_POST
[
'form_submit'
])) {
$name
=
$_POST
[
'name'
];
$password
=
$_POST
[
'password'
];
$email
=
$_POST
[
'user_email'
];
$mobile
=
$_POST
[
'mobile'
];
if
(
empty
(
$_POST
[
"name"
])) {
$nameError
=
"Name is required"
;
}
else
{
$name
= validate_input(
$_POST
[
"name"
]);
if
(
$name
==
'chetan'
) {
$success
=
"Thank you "
.
$name
.
", "
;
echo
$success
;
}
}
if
(
empty
(
$_POST
[
"email"
])) {
$emailError
=
"Email is required"
;
}
else
{
$email
= validate_input(
$_POST
[
"email"
]);
if
(
$email
==
'test@email.com'
) {
$success
=
$email
.
" is correct"
;
echo
$success
;
}
}
if
(
empty
(
$_POST
[
"password"
])) {
$passwordError
=
"Password is required"
;
}
else
{
$password
= validate_input(
$_POST
[
"password"
]);
if
(
$password
==
'test@123'
) {
$success
=
$password
.
" is correct"
;
echo
$success
;
}
}
if
(
empty
(
$_POST
[
"mobile"
])) {
$mobileError
=
"Mobile is required"
;
}
else
{
$mobile
= validate_input(
$_POST
[
"mobile"
]);
if
(
$mobile
==
'123456789'
) {
$success
=
$mobile
.
" is correct"
;
echo
$success
;
}
}
if
(
empty
(
$success
))
echo
"Invalid input!!!"
;
}
?>
HTML code: The following code uses the above PHP “form.php” code.
HTML
<!DOCTYPE html>
<
html
lang
=
"en"
dir
=
"ltr"
>
<
head
>
<
meta
charset
=
"utf-8"
>
<
title
>Form</
title
>
</
head
>
<
body
>
<
form
action
=
"form.php"
method
=
"POST"
>
<
input
type
=
"text"
name
=
"name"
placeholder
=
"Enter name"
>
<
input
type
=
"password"
name
=
"password"
placeholder
=
"Password"
>
<
input
type
=
"email"
name
=
"user_email"
placeholder
=
"yourname@gamil.com"
>
<
input
type
=
"tel"
name
=
"mobile"
placeholder
=
"Mobile no"
>
<
button
type
=
"submit"
name
=
"form_submit"
>
Submit
</
button
>
</
form
>
</
body
>
</
html
>
Output:
- Incorrect input by user
Invalid input!!!
- Correct input by user
Thank you chetan, 123456789 is correct
Last Updated :
31 Dec, 2020
Like Article
Save Article
Помогаю со студенческими работами здесь
invalid numeric input
Здравствуйте! Собственно в программе пишет вот такую ошибку. Ввожу данные из текстового файла в…
Invalid numeric input
Выходит ошибка при загрузке массива из файла. Помогите исправить. Так как проект состоит из…
Ошибка: Invalid numeric input
Эта ошибка выходит после ввода данных
program Project1;
{$APPTYPE CONSOLE}
uses
SysUtils;…
Ошибка: Invalid numeric input
unit Unit4;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics,…
Искать еще темы с ответами
Или воспользуйтесь поиском по форуму:
2