Reputation: 43
I'm trying to make a program that tells me weather the char i put in arguments is uppercase or lowercase or a digit from 0 to 9 or other! I'm having errors in my code:
public class CharsTester {
public static void main(String[] args) {
char input;
if (input.matches("^[a-zA-Z]+$"))
{
if (Character.isLowerCase(input))
{
System.out.println("lower");
}
else
{
System.out.println("upper");
}
}
else if (input.matches("^(0|[1-9][0-9]*)$"))
{
System.out.println("digit");
}
else
{
System.out.println("other");
}
}
}
Upvotes: 1
Views: 2532
Reputation: 300
you can convert String to char array, and then individual char with ascii value as below:-
public class CharsTester {
public static void main(String[] args) {
String input="ASD123asd_-";
char temp[]=input.toCharArray();
for (int i=0;i<temp.length;i++)
{
if(temp[i] >47 && temp[i]<58)
{
System.out.println(temp[i]+": is digit");
}
else if(temp[i] >64 && temp[i]<91)
{
System.out.println(temp[i]+": is CAPS char");
}
else if(temp[i] >96 && temp[i]<123)
{
System.out.println(temp[i]+": is small char");
}
else
System.out.println(temp[i]+"is symbol or spetial char");
}
}
}
Upvotes: 0
Reputation: 5455
Try:
for (String arg : args) {
if (arg.matches("^[A-Z]+$")) {
System.out.println("uppercase");
} else if (arg.matches("^[a-z]+$")) {
System.out.println("lowercase");
} else if (arg.matches("^[0-9]+$")) {
System.out.println("digits");
} else {
System.out.println("other");
}
}
Upvotes: 0
Reputation: 1887
Regex groups solution:
Pattern p = Pattern.compile("([a-z])|([A-Z])|([\\d])");
Matcher m = p.matcher("" + x);
m.matches();
if (m.group(1)!=null)
{
System.out.println("lower");
}
else if (m.group(2)!=null)
{
System.out.println("upper");
}
else if (m.group(3)!=null)
{
System.out.println("digit");
} else
{
System.out.println("other");
}
Upvotes: 0
Reputation: 124235
If your input is in fact one character then you don't need regex but just set of few tests.
char input = 'z';// example character
if (Character.isLowerCase(input)) {
System.out.println("lower");
} else if (Character.isUpperCase(input)) {
System.out.println("upper");
} else if (Character.isDigit(input)) {
System.out.println("digit");
} else {
System.out.println("something is not right :/");
}
Upvotes: 0
Reputation: 21971
Change the type of input
String input;// Change char to String
if (input.matches("[a-zA-Z]+")) // Remove ^ and $
// String.matches don't need symbol ^ $
To test char
you don't need String#matches
,
char input=' ';
if (Character.isLowerCase(input) || Character.isUpperCase(input)) {
if (Character.isLowerCase(input)) {
System.out.println("lower");
} else {
System.out.println("upper");
}
} else if (Character.isDigit(input)) {
System.out.println("digit");
} else {
System.out.println("other");
}
Upvotes: 3