- /*
- Check if string contains valid number example.
- This example shows how to check if string contains valid number
- or not using parseDouble and parseInteger methods of
- Double and Integer wrapper classes.
- */
- public class CheckValidNumberExample {
- public static void main(String[] args) {
- String[] str = new String[]{"10.20", "123456", "12.invalid"};
- for(int i=0 ; i < str.length ; i ++)
- {
- if( str[i].indexOf(".") > 0 )
- {
- try
- {
- /*
- * To check if the number is valid decimal number, use
- * double parseDouble(String str) method of
- * Double wrapper class.
- *
- * This method throws NumberFormatException if the
- * argument string is not a valid decimal number.
- */
- Double.parseDouble(str[i]);
- System.out.println(str[i] + " is a valid decimal number");
- }
- catch(NumberFormatException nme)
- {
- System.out.println(str[i] + " is not a valid decimal number");
- }
- }
- else
- {
- try
- {
- /*
- * To check if the number is valid integer number, use
- * int parseInt(String str) method of
- * Integer wrapper class.
- *
- * This method throws NumberFormatException if the
- * argument string is not a valid integer number.
- */
- Integer.parseInt(str[i]);
- System.out.println(str[i] + " is valid integer number");
- }
- catch(NumberFormatException nme)
- {
- System.out.println(str[i] + " is not a valid integer number");
- }
- }
- }
- }
- }
- /*
- Output would be
- 10.20 is a valid decimal number
- 123456 is valid integer number
- 12.invalid is not a valid decimal number
- */
Welcome to the world of Java examples, organized by categories and Java packages. Java examples (Java sample source code) help to understand functionality of various Java classes and methods as well as various programming techniques in a simple way, which is otherwise very hard to learn by reading tutorials or Java API. So start exploring...
Tuesday, November 29, 2011
Check if string contains valid number example.
Subscribe to:
Post Comments (Atom)
How to find the most appropriate Keywords?
🔍 Step 1: Understand Your Business and Audience Define your products, services, or content . Identify your target audien...
-
/* Pause Thread Using Sleep Method Example This Java example shows how to pause currently running thread using sleep method of Jav...
-
/* Java String split example. This Java String split example describes how Java String is split into multiple Java String objects. */ ...
-
// File Name GreetingClient.java import java.net.*; import java.io.*; public class GreetingClient { public static void main(String [] ...
No comments:
Post a Comment