1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
/* 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 */ |
I like your ex:-
nyc…
my question is how to find out largest number in string input {10 20 30} o/p- is 30.
please give me a examples on that
import java.io.*;
import java.util.*;
class largest
{
public static void main(String[] args)
{
int large=0,a;
Scanner in=new Scanner(System.in);
System.out.println(“Enter the input and type zero”0″ to end”);
int a=in.nextInt();
while(a!=0)
{
if(a>large)
{large=a;}
a=in.nextInt();
}
System.out.println(“The largest number is”+large);
}}
It didn’t work at my end.
Wrong logic so it will not work.
17. if( str[i].indexOf(“.”) > 0 )
i have a doubt about this line of code.
if i will take an string as “.20”, will it work ?. Because index of “.” here is equal to 0.
So it will show the output as .20 is not a valid integer number.
Isn’t this a better version
public class CheckNumber {
public static void main(String[] args) throws IOException {
System.out.println(“Enter a valid number:”);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
try {
Double numD = Double.parseDouble(input);
System.out.println(numD + ” is a valid number.”);
} catch (NumberFormatException nme) {
// TODO Auto-generated catch block
System.out.println(input + ” is not a valid number.”);
}
}
}