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

$project is not working in mongo query [duplicate]
SWT CCOMBO not reposnding correctly to accessibility events(Screen Reader)
fetching data from ArrayList [duplicate]
Unable to run Unix Commands using ProcessBuilder
BroadcastReceiver comparing action names
Issues scheduling alarms when getting the time to set the AlarmManger for using a TimePicker because of AM/PM
Asking user input for an integer in java
Handle Toggle States in onResume() using Intent and SharedPreferences
Correct approach to secure the back end service - oAuth
Passing generic event to Guava EventBus?
Java Casting in Method Overloading
Call a java web service method from java client (HTTPPost)
How do you change the label text in java using eclipse and scene builder?
How to retrieve field values by passing field name using JPOS ISO8583 message format
What is the best format for Heapdump file to analyze? Is it hprof?
Android studio java.lang.NoClassDefFoundError: android.support.v4.app.NavUtilsJB

Categories

HOME
ibm-bluemix
hook
blogger
debugging
deezer
push-notification
plone
relay
youtube-dl
q
spring-cloud-stream
elm
infragistics
alpha
fingerprint
serverspec
swagger-ui
slurm
correlation
google-cloud-spanner
flask-wtforms
iolanguage
serverless-framework
progressive-web-apps
nhibernate-envers
introduction
ml
physics-engine
numerical-methods
underflow
unboundid
tinymce-4
xquery-3.0
karaf
xmlreader
mozilla
http-referer
wixsharp
main
jquery-bootgrid
retina-display
x11-forwarding
uft-api
greenrobot-eventbus
cookiecutter-django
graphenedb
awt
preconditions
grid.mvc
reportingservices-2005
node-gyp
botbuilder
hibernate-tools
pnotify
carrot
pillow
memory-alignment
crosswalk-runtime
google-cdn
removechild
qcustomplot
apachebench
ios4
separator
ora-00900
feedback
responsive-images
fscommand
operator-precedence
cctv
eol
navigationservice
funcunit
wp-query
ember-charts
ivyde
aqtime
cos
orchardcms-1.7
factory-method
simba
javaspaces
custom-backend
window-management
hirefire
invite
locate
sql-server-profiler
site.master
revisions
castle-monorail
sef
eqatec
temporal-database
spec#
defensive-programming
lzh

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