java


How to do scanner exception in Java?


I would like to scan a float and an integer. I want to add an exception, if the scanned number is not a float or int, scan again while the input number is not correct. I tried with hasNextFloat and hasNextInt but I didn't really got it right.
package has_exception;
import java.util.Scanner;
public class Has_Exception {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
System.out.println("Enter a float!");
float fl = scn.nextFloat();
System.out.println("Enter an integer");
int a = scn.nextInt();
}
}
try with a parse of string into a float and do this until the user gives a valid input...
the initial values of the float will depend of your application, and you can repeat this approach for the integer value
Scanner scn = new Scanner(System.in);
float fl = -1.0f;
while (fl < 0) {
System.out.println("Enter a float!");
String x = scn.nextLine();
try {
fl = Float.parseFloat(x);
} catch (NumberFormatException e) {
System.out.println("Not a float");
}
}
You can use do{..}while() with nextLine() instead, for example :
Scanner scn = new Scanner(System.in);
boolean correct = true;
do {
try {
System.out.println("Enter a float!");
float fl = Float.parseFloat(scn.nextLine());
System.out.println("Enter an integer");
int a = Integer.parseInt(scn.nextLine());
} catch (NumberFormatException e) {
correct = false;
}
} while (!correct);
scn.close();//close your scanner

Related Links

What do I do if I want to check for a special character in Java using char?
Spring #ContextHierarchy and transactional service testing
Consuming form Solace queue without using latch or thread
Convert cURL to Java
JSch PAM authentication - “Auth fail” - credentials are correct
(Java) Flatten JSONArray of JSONObject to [[]] with Java8
Replace Time Part in Date Object in Java
Lot of errors Android Studio with ViewGroup file
JPA many-to-many relationship causing infinite recursion and stack overflow error
searching for records from database using Arraylist
Shortest path with ArangoDB & Java
MySQL connection doesn't work with HikariCP
MS Word is not requesting my Controller :Java
Failed to start Nodemanger in hadoop on windows
What are the differences between instance final fields from Java and readonly instance fields from C#?
HashMap key as id and value another entity

Categories

HOME
ionic-framework
atom-editor
listview
proxy
azure-data-factory
react-virtualized
session
read-eval-print-loop
q
routes
jsp-tags
dxl
jxls
onelogin
convolution
cross-validation
synchronization
here-api
spring-kafka
n-gram
usergrid
event-handling
decomposition
dosgi
tostring
emulator
one-hot-encoding
pass-by-reference
wijmo
p-value
pepper
facet
intel-pin
typo3-6.2.x
replaceall
libssl
file-rename
nat
sequential
catalog
android-ble
restlet
serverside-rendering
abstract-class
streamsets
vapor
hilbert-curve
graphenedb
dynamic-reports
quadratic-programming
angular2-meteor
taffy
qsslsocket
rails-routing
dandelion
diagnostics
media-player
pillow
ableton-live
gridpane
ctest
django-debug-toolbar
prettytensor
qgraphicsview
make-install
intel-fortran
lib.web.mvc
marching-cubes
pundit
rgeo
microbenchmark
twirl
ios9.1
sysinternals
angular-local-storage
lustre
codeigniter-routing
project-planning
prettify
flexmojos
bulkloader
ora-00911
sharp-repository
e4x
anonymous-methods
isnullorempty
mt
buildr
semantic-diff
libc++
coredump
radcombobox
sortable-tables
fixed-width
data-driven
nerddinner
putchar

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App