Hello Friends,
This article will describe how can we check whether a data is number or String in java.
Algorithm :-
1). First Break the string into characterArray. 2) Now to check for number use Integer.Parseint() 3) Use Character.isDigit() to check whether character is number or not.
Example :-
import java.util.*;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
public class PojorunExample
{
static boolean isnumber(String x)
{
boolean flag = false;
try
{
int num = Integer.parseInt(x);
flag = true;
}
catch(Exception e)
{
}
return flag;
}
@Test
public void g()
{
String x = "Chandan";
String y = "chandan30";
if(isnumber(x))
{
System.out.println("its a number");
}
else
{
System.out.println("its not a number");
}
char[] ch = y.toCharArray();
for(int i = 0; i<ch.length; i++)
{
if(Character.isDigit(ch[i]))
{
System.out.println(ch[i] + " " + "this is number");
}
else
{
System.out.println(ch[i] + " " + "this is letter");
}
}
}
}
its not a number
c this is letter
h this is letter
a this is letter
n this is letter
d this is letter
a this is letter
n this is letter
3 this is number
0 this is number
No comments:
Post a Comment