+ 1

Exceptions

If i asked users to input something int and they wrote it as a String And i want to make an Exception Try&Catch to send for them a massage how could i do it in Java ? Could you wrote the code under

3rd Feb 2021, 3:36 AM
ANAS ADEL FAISAL AL-KAMEL
5 Respostas
3rd Feb 2021, 3:37 AM
Alphin K Sajan
Alphin K Sajan - avatar
+ 3
Anas Al-kamel You need to put everything inside try block if you want to catch them. Copy this code on Sololearn playground and see the effect import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner sc = new Scanner (System.in); try { int n = sc.nextInt(); System.out.println("Hello " + n); } catch (Exception e) { System.out.println("Enter only numeric value => " + e); } } }
3rd Feb 2021, 5:38 AM
A͢J
A͢J - avatar
0
Alphin K Sajan well my code is about send some int and i will repeat it , but if there is something wrong as i mentioned above it will send an message like (“Hey you made somthing wrong!”) could you help me with that ? int s = read.nextInt(); try{ }catch(Exception e){ System.out.print (“Hey you made somthing wrong!”); }
3rd Feb 2021, 3:41 AM
ANAS ADEL FAISAL AL-KAMEL
0
if you can complate the code above and i’ll understand :)
3rd Feb 2021, 3:42 AM
ANAS ADEL FAISAL AL-KAMEL
0
You can use a while true loop and break after getting a correct input. Note that you have to use scanner.next() in catch or the program will use your last input instead of asking you for a new one. https://code.sololearn.com/cae77mMGy50H/?ref=app
3rd Feb 2021, 9:21 PM
David
David - avatar