is there a utility method for this in commons-lang? - java

I searched for sometime but I couldn't find any
boolean isAlpha(final char character)
{
char c = Character.toUpperCase(character);
switch (c)
{
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
return true;
default:
return false;
}
}

Commons Lang has CharUtils.isAsciiAlpha, but perhaps you could just use java.lang.Character.isLetter(char) (javadoc). Not quite the same (the latter matches more than just A-Z ASCII), but may be enough for your needs.

I know this is not from lang, but how about return (c >= 'A' && c <= 'Z')?

You could use StringUtils.isAlpha
That switch is pretty verbose, if I had to write it myself I'd make something like:
boolean isAlpha(final char c) {
return "abcdefghijklmnopqrstuvwxyz".indexOf(Character.toLowerCase(c)) != -1;
}

You want CharUtils.isAsciiAlpha.
It should be faster than StringUtils.isAlpha(String) because you're not creating a new String object.
You avoid the cost of converting to an uppercase char in your original method.
It's more readable then range checks (which is how it's implemented).
java.lang.Character.isLetter(char) will return true for certain non-Latin characters for which your method returns false.

How about Character.isLetter()?

If you simply want to check whether the given character is somewhere between A-Z, an easier way to do this would be to use regular expressions:
Pattern.matches("[A-Z]", input)
Where input is a CharSequence. More information on the Java Pattern class: http://download.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html
Don't know how this would compare performance wise to the other options though.

Character class provides many useful APIs. You need not convert the character. Few examples are
Character.isLetter(char ch)
Character.isLowerCase(char ch)
Character.isUpperCase(char ch)
Character.isDigit(char ch)
Character.isLetterOrDigit(char ch)

Related

Backtracking Switch Statement With String

So I'm writing a program that randomly generates a maze and then finds a solution for it. Part of my code includes a backtracking algorithm where I move back if I hit a dead end.
Everytime I move, I record the move ("N" for North, "NE" for Northeast, on and on) in a stack. For the backtracking, I pop the top element of the stack and use a switch statement to move the opposite direction of the direction popped.
When I try to compile my code, it gives me an error that the Stack object popped cannot be converted to int, but I have seen String used for switch statements in other programs. I thought the toString method would automatically convert the object to String for the switch statement. I have tried manually using toString with the popped value as the parameter but that didn't work either. Here is the code and error message.
switch(visitStack.pop())
{
// have to backtrack the opposite direction i previously went
case "N": nowR++;
visited[nowR][nowC] = 'N';
break;
case "NE": nowR++;
nowC--;
visited[nowR][nowC] = 'N';
break;
case "E": nowC--;;
visited[nowR][nowC] = 'N';
break;
case "SE": nowR--;
nowC--;
visited[nowR][nowC] = 'N';
break;
case "S": nowC--;
visited[nowR][nowC] = 'N';
break;
case "SW": nowR--;
nowC++;
visited[nowR][nowC] = 'N';
break;
case "W": nowC++;
visited[nowR][nowC] = 'N';
break;
case "NW": nowR++;
nowC++;
visited[nowR][nowC] = 'N';
break;
}
The blued out portion has personal details.
For java versions below 7 it wont support Strings in Switch Case
Alternative would be else if ladder to compare strings using .Equals() method
or
you can Use Enums in Switch Case

Multiple args in a java switch

I am expecting my input to be one of three groups of chars and need to decide what to do with it based on which group it falls in. I'm trying to figure out how to define a switch with multiple cases to do this. Here is what I have so far:
while(in.hasNextChar())
{
char test = in.nextChar();
List<Signal> out = new List<Signal>(0);
switch(test)
{
case '1','0','x','X':
out.add(fromString(test));
break;
case ' ','/t':
break;
default:
throw new ExceptionLogicMalformedSignal;
}
}
return out;
}
You have the syntax wrong. You need to take advantage of fall-through:
switch(test) {
case '1':
case '0':
case 'x':
case 'X':
out.add(fromString(test));
break;
case ' ':
case '\t':
break;
default:
throw new ExceptionLogicMalformedSignal;
}
A case is just a label, very similar to what you'd use with a goto (which is essentially what is happening behind the scenes). It's not a statement, since it does nothing itself — it just names an address. So if test is '0', it can happily continue through the 'x' and 'X' cases to reach the actual statement code since there's not anything being done by those labels. Only break "ends" a case.
You can actually insert code between cases even without a break:
switch(test) {
case '1':
System.out.println("This is printed by case '1'");
case '0':
System.out.println("This is printed by both case '1' and case '0'");
break;
case 'x':
case 'X':
System.out.println("This is only printed by the Xs");
break;
default:
break;
}

How can I make this better

Ok here I have a switch case statement which is falling through and trying every option. Basically I want something that if the user enters the letter A in the textbox the background will change to b! if they dont enter the letter A then I want it to stop executing the code. But what has been happening is if the user enters lets say for example the letter Q when the background is letter A then the background will change to letter R instead of telling the user that they are wrong. basically I would like to know how I can stop the background from changing if the user does not enter the letter they are on here is the code.
public void afterTextChanged(Editable s) {
char ch = words.getText().toString().charAt(0);
switch(ch - 'A') {
case 0:
//A;
gestureViewer.setBackgroundResource(R.drawable.lettersb);
break;
case 1:
gestureViewer.setBackgroundResource(R.drawable.lettersc);
break;
case 2:
gestureViewer.setBackgroundResource(R.drawable.lettersd);
break;
case 3:
gestureViewer.setBackgroundResource(R.drawable.letterse);
break;
case 4:
gestureViewer.setBackgroundResource(R.drawable.lettersf);
break;
case 5:
gestureViewer.setBackgroundResource(R.drawable.lettersg);
break;
case 6:
gestureViewer.setBackgroundResource(R.drawable.lettersh);
break;
case 7:
gestureViewer.setBackgroundResource(R.drawable.lettersi);
break;
case 8:
gestureViewer.setBackgroundResource(R.drawable.lettersj);
break;
case 9:
gestureViewer.setBackgroundResource(R.drawable.lettersk);
break;
case 10:
gestureViewer.setBackgroundResource(R.drawable.lettersl);
break;
case 11:
gestureViewer.setBackgroundResource(R.drawable.lettersm);
break;
case 12:
gestureViewer.setBackgroundResource(R.drawable.lettersn);
break;
case 13:
gestureViewer.setBackgroundResource(R.drawable.letterso);
break;
case 14:
gestureViewer.setBackgroundResource(R.drawable.lettersp);
break;
case 15:
gestureViewer.setBackgroundResource(R.drawable.lettersq);
break;
case 16:
gestureViewer.setBackgroundResource(R.drawable.lettersr);
break;
case 17:
gestureViewer.setBackgroundResource(R.drawable.letterss);
break;
case 19:
gestureViewer.setBackgroundResource(R.drawable.letterst);
break;
case 20:
gestureViewer.setBackgroundResource(R.drawable.lettersu);
break;
case 21:
gestureViewer.setBackgroundResource(R.drawable.lettersv);
break;
case 22:
gestureViewer.setBackgroundResource(R.drawable.lettersw);
break;
case 23:
gestureViewer.setBackgroundResource(R.drawable.lettersx);
break;
case 24:
gestureViewer.setBackgroundResource(R.drawable.lettersy);
break;
case 25:
gestureViewer.setBackgroundResource(R.drawable.lettersz);
break;
would it be better if I set the pictures in an array and then went from there? Ive tried including If switch case, but it didnt work at all....
I'd pre-populae an array and invoke:
gestureViewer.setBackgroundResource(myArray[ch - 'A']);
It will make your code much more readable.
You can also do it with a Map<Character,MyImage> - it might allow you to add more features easily in the future.
If you do that, invokation will be using
gestureViewer.setBackgroundResource(myMap.get(ch));
Note that the array/map needs to be populated only once in the application's runtime.
You could, for example, put all the R.drawable.abc inside an Array and then address its index.
int[] bgImg = {R.drawable.a, ... , R.drawable.z}
char ch = words.getText().toString().toUpperCase().charAt(0);
int index = ch - 'A';
if(index > 0 && index < bgImg.length){
gestureViewer.setBackgroundResource(bgImg[index]);
} else {
gestureViewer.setBackgroundResource(R.drawable.standardImage);
}
Also note, that I'm using toUpperCase() to make sure you can substract the capital 'A'
Try:
public void afterTextChanged(Editable s) {
char ch = words.getText().toString().charAt(0);
int id = getResources().getIdentifier("letters" + ch, "drawable", context.getPackageName())
gestureViewer.setBackgroundResource(id);
}
}

Java Switch Statement - Is "or"/"and" possible?

I implemented a font system that finds out which letter to use via char switch statements. There are only capital letters in my font image. I need to make it so that, for example, 'a' and 'A' both have the same output. Instead of having 2x the amount of cases, could it be something like the following:
char c;
switch(c){
case 'a' & 'A': /*get the 'A' image*/; break;
case 'b' & 'B': /*get the 'B' image*/; break;
...
case 'z' & 'Z': /*get the 'Z' image*/; break;
}
Is this possible in java?
You can use switch-case fall through by omitting the break; statement.
char c = /* whatever */;
switch(c) {
case 'a':
case 'A':
//get the 'A' image;
break;
case 'b':
case 'B':
//get the 'B' image;
break;
// (...)
case 'z':
case 'Z':
//get the 'Z' image;
break;
}
...or you could just normalize to lower case or upper case before switching.
char c = Character.toUpperCase(/* whatever */);
switch(c) {
case 'A':
//get the 'A' image;
break;
case 'B':
//get the 'B' image;
break;
// (...)
case 'Z':
//get the 'Z' image;
break;
}
Above, you mean OR not AND. Example of AND: 110 & 011 == 010 which is neither of the things you're looking for.
For OR, just have 2 cases without the break on the 1st. Eg:
case 'a':
case 'A':
// do stuff
break;
The above are all excellent answers. I just wanted to add that when there are multiple characters to check against, an if-else might turn out better since you could instead write the following.
// switch on vowels, digits, punctuation, or consonants
char c; // assign some character to 'c'
if ("aeiouAEIOU".indexOf(c) != -1) {
// handle vowel case
} else if ("!##$%,.".indexOf(c) != -1) {
// handle punctuation case
} else if ("0123456789".indexOf(c) != -1) {
// handle digit case
} else {
// handle consonant case, assuming other characters are not possible
}
Of course, if this gets any more complicated, I'd recommend a regex matcher.
Observations on an interesting Switch case trap --> fall through of switch
"The break statements are necessary because without them, statements in switch blocks fall through:"
Java Doc's example
Snippet of consecutive case without break:
char c = 'A';/* switch with lower case */;
switch(c) {
case 'a':
System.out.println("a");
case 'A':
System.out.println("A");
break;
}
O/P for this case is:
A
But if you change value of c, i.e., char c = 'a';, then this get interesting.
O/P for this case is:
a
A
Even though the 2nd case test fails, program goes onto print A, due to missing break which causes switch to treat the rest of the code as a block. All statements after the matching case label are executed in sequence.
From what I understand about your question, before passing the character into the switch statement, you can convert it to lowercase. So you don't have to worry about upper cases because they are automatically converted to lower case.
For that you need to use the below function:
Character.toLowerCase(c);
Enhanced switch/ case / Switch with arrows syntax (Since Java 13):
char c;
switch (c) {
case 'A', 'a' -> {} // c is either 'A' or 'a'.
case ...
}

Variable value switch cases in Java

I'm looking to make a switch where 5 of the cases are functionally identical, but then there will be other unique cases. Is there a way to list a case value that handles 5 different values? Thanks
You can compound the labels in the switch
switch (variable) {
case 'a': case 'b' : case 'c' : case 'd' :
do something;
break;
case 'e': case 'f' :
do something else
break;
default:
do something;
}
Thinking of a switch as a jump to a label (possibly coupled with a jump (the break) to the end) will help. That means the switch
switch (variable) {
case 'a': case 'b' : case 'c' : case 'd' :
do something;
// note that there's no break here.
case 'e': case 'f' :
do something else
break;
default:
do something;
}
will "do something" and "do something else" for 'a', 'b', 'c', and 'd'; while it will only "do something else" for 'e' and 'f'. Finally if it's not any of the above it hits the default block of "do something".
switch (value) {
case 1:
case 2:
case 3:
case 4:
doSomethingIdentical();
break;
case 5:
doSomethingDifferent();
break;
default:
break;
}
This is very easy to do. Instead of just having one case value that handles all 5 different values, let the 5 case values fall through to each other, like so:
switch(value)
{
case 1:
case 2:
//case 1 and 2 will both result in this code being executed
doSomething();
break;
case 3:
doSomethingElse();
break;
}
As long as you don't put a break; on a switch it will fall through to the next statement.
In that way, you can have something like this:
String value(int val) {
String out = "";
switch(val) {
case 0:
out = "case 0";
break;
case 1:
out = "case 1";
break;
case 2:
case 3:
case 4:
case 5:
case 6:
out = "case 2, 3, 4, 5 or 6";
break;
case 7:
out = "case 7";
break;
}
return out;
}
Yes, just use a switch like this:
switch(v) {
case 1:
case 2:
case 3:
identicFunctionality();
break;
case 4:
other01();
break;
case 5:
other02();
break;
default:
_default();
}
As of Java 12 I believe it is supported. Check out JEP 354. I have never used the syntax but I think it would run like this for your case.
switch (day) {
case 1, 2, 3, 4, 5 -> System.out.println("1-5");
case 7 -> System.out.println(7);
case 8 -> System.out.println(8);
case 9 -> System.out.println(9);
}
on a related note JEP 325 is also cool.

Categories