Create a Java program that prompts the user to enter a text (x) and uses a try-catch block to check if the text is a number or not. If it''s a number, display "It''s a number"; otherwise, show "It''s not a number."
try-catch
It''s important to note that there are more suitable ways to validate user input in Java applications.
Juan
It is not a number
import java.util.Scanner; public class NumberWithExceptions { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a text: "); String x = input.nextLine(); try { Integer.parseInt(x); System.out.println("It is a number"); } catch (NumberFormatException e) { System.out.println("It is not a number"); } } }
Click here to view the exercise solution
Share it on your social media and challenge your friends to solve programming problems. Together, we can learn and grow.
The code has been successfully copied to the clipboard.
Continue improving your Java programming skills with our selection of practical exercises from the lesson. Click on Practice and challenge your knowledge!
Create a Java program that prompts the user to enter a text (x) and uses a try-catch block to check if the text is a number or not. If it's a number, display "It's a number"; otherwise, show "It's not a number."
Practice with easy and intermediate Java exercises on different types of text, numeric or boolean data.
Free programming course with practical exercises and solutions in C#. Start learning right now!
Take your Exercises C# lessons everywhere with our Android app. Download it now from Google Play
Own and third party cookies to improve our services. If you go on surfing, we will consider you accepting its use.