Translating chars into keystrokes in java - java

I've seen similar questions about this issue, but what happens to me is a little different;
I am developing a remote control application and I'm sending keystrokes to my computer.
The Robot class in java only accepts VK_CODES for keystrokes, so I have to translate non ascii characters into keystrokes combinations, like this:
public void type(char character) {
switch (character) {
case 'a': doType(KeyEvent.VK_A); break;
case 'á': doType(KeyEvent.VK_A); break;
case 'à': doType(KeyEvent.VK_A); break;
case 'ä': doType(KeyEvent.VK_A); break;
case 'â': doType(KeyEvent.VK_A); break;
case 'b': doType(KeyEvent.VK_B); break;
case 'c': doType(KeyEvent.VK_C); break;
case 'd': doType(KeyEvent.VK_D); break;
case '{': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_OPEN_BRACKET); break;
case '}': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_CLOSE_BRACKET); break;
case '|': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_BACK_SLASH); break;
etc...
}
private void doType(int... keyCodes) {
doType(keyCodes, 0, keyCodes.length);
}
private void doType(int[] keyCodes, int offset, int length) {
if (length == 0) {
return;
}
robot.keyPress(keyCodes[offset]);
doType(keyCodes, offset + 1, length - 1);
robot.keyRelease(keyCodes[offset]);
}
This works well, but when I try to combine ALT+numbers characters (for example to type the '#' character) I do:
case '#': doType(KeyEvent.VK_ALT,KeyEvent.VK_6,KeyEvent.VK_4); break;
It won't type it. If I type it directly with my keyboard, it works.
Is there a reason for this? How can I make a Robot instance to accept all the unicode characters and not just ascii? Is there a better way to do what I am doing?
Thanks for reading and sorry for my English!

I found out that the problem was, I was entering the VK_number directly.
Now it works like a charm using the VK_NUMPAD keys:
case '#': doType(KeyEvent.VK_ALT,KeyEvent.VK_NUMPAD6,KeyEvent.VK_NUMPAD4); break;
case '#': doType(KeyEvent.VK_ALT,KeyEvent.VK_NUMPAD3,KeyEvent.VK_NUMPAD5); break;
etc..

Related

How do you set a value (double, String, int, etc.) of a TextField?

private void Button_CalculateActionPerformed(java.awt.event.ActionEvent evt) {
try{ a=Double.parseDouble(TextField_First.getText());
b=Double.parseDouble(TextField_Second.getText());
switch(operation){
case 1:result=a+b;
break;
case 2:result=a-b;
break;
case 3:result=a*b;
break;
case 4:result=a/b;
break;
case 5:result=a%b;
break;
case 6:result=Math.pow(a,b);
break;
case 7:
TextField_Second.setText(""+a);
result=Math.sqrt(a);
TextField_Second.setText(""+a);
break;
case 8:result=Math.abs(a);
default:System.out.println("Please select an operation");
}
TextField_Result.setText(""+result);
}catch(NumberFormatException e){Label_error.setText("Please use your
common sense ;-;");}
}
What I'm trying to do is set the value (and text) of TextField_Second to 0.0, if TextField_Second is null/has no value. So if TextField_First's value is 9, I get the square root, I get an error (NumberFormatException), but I used try and catch, so if that does happen, a label will appear saying, "Please use your common sense ;-;".
P.S. It only works if TextField_Second has a value, and it doesn't affect the answer.
Try something like this;
Note: you have not add break statement to case 8:
try
{
if (!TextField_First.getText().equals(""))
{
if(TextField_Second.getText().equals(""))
{
TextField_Second.setText("0.0");
}
a=Double.parseDouble(TextField_First.getText());
b=Double.parseDouble(TextField_Second.getText());
switch(operation){
case 1:result=a+b;
break;
case 2:result=a-b;
break;
case 3:result=a*b;
break;
case 4:result=a/b;
break;
case 5:result=a%b;
break;
case 6:result=Math.pow(a,b);
break;
case 7:
TextField_Second.setText(""+a);
result=Math.sqrt(a);
TextField_Second.setText(""+a);
break;
case 8:result=Math.abs(a);
break;
default:System.out.println("Please select an operation");
break;
}
}

Switch/case statement- String(first char specific and the rest don't care)

In a switch(string) can i make a case to start with a specific char f.e case('N') and then followed by other characters that i don't care about them? f.e NOC
case("N**"):
case("1**"):
case("0**"):
BalancedTrenary term = new BalancedTrenary(parts[i]);
You can use charAt and use char in the cases
String str = "NOC";
switch (str.charAt(0)) {
case 'N':
// do something here
break;
}
Be aware that the case is case sensitive. To make it ignored case use another case with n
switch (str.charAt(0)) {
case 'N':
case 'n':
// do something here
break;
}

Can we call a "case" inside another case in the same switch statement in Java?

My intention is to call two cases inside another case in the same switch statement,
switch (orderType) {
case 1:
statement 1;
break;
case 2:
statement 2;
break;
case 3:
**call case 1;**
**Call case 2;**
break;
default:
break;`
}
Can we do that in Java?
No, you can't jump to the code snippet in another switch case. You can however extract the code into an own method that can be called from another case:
switch (orderType) {
case 1:
someMethod1();
break;
case 2:
someMethod2();
break;
case 3:
someMethod1();
someMethod2();
break;
default:
break;
}
void someMethod1() { ... }
void someMethod2() { ... }
Although you cannot influence the switch cases directly, you can call switch's parent method from one case and pass different arguments. For example,
void foo(int param1, String param2, ...) {
switch (param1) {
case 0:
foo(1, "some string");
break;
case 1:
//do something
break;
default:
break;
}
}
You can't just call a another case block like this. What you could do, though, is wrap each of these blocks in a method, and reuse them:
private void doSomething() {
// implementation
}
private void doSomethingElse() {
// implementation
}
private void runSwitch(int order) {
switch (orderType) {
case 1:
doSomething();
break;
case 2:
doSomethingElse();
break;
case 3:
doSomething();
doSomethingElse();
break;
default:
break;
}
}
Using methods is the best way to do it as mentioned in the accepted answer but for some reasons if you are unable to create method, Here is one more way to do this without using methods
boolean isBreakTheLoop = false, isCase2Required = false;
while(!isBreakTheLoop){
switch (orderType) {
case 1:
statement 1;
if(isCase2Required){
orderType = 2;
break;
}
isBreakTheLoop = true;
break;
case 2:
statement 2;
isBreakTheLoop = true;
break;
case 3:
orderType = 1;
isCase2Required = true;
break;
default:
isBreakTheLoop = true;
break;
}
}
Just a reminder: while the most suggested case is the best solution, note that if you don't close with a brake; your case:, it will continue executing in the next case.
Then, while it's still best pratice to break your cases, you could still adopt a solution similar to the following:
switch (orderType) {
case 3:
someMethod1();
case 2:
someMethod2();
break;
case 1:
someMethod1();
break;
default:
break;
}
Note that "avoiding breaks" solution can't completely cover OP necessities, because writing:
case 3:
case 1:
someMethod1();
case 2:
someMethod2();
default:
break;
or:
case 3:
case 1:
someMethod1();
break;
case 2:
someMethod2();
break;
default:
break;
would make case: 3 be the same than case: 1, making them execute both methods in first code, or a single method in the second code.
You can use this trick in some case :
switch (orderType) {
case 3:
statement 3;
case 2:
statement 2;
case 1:
statement 1;
break;
default:
break;`
}

Java switch case fall through

I have a switch case in Java like this:
switch(int example)
{
case 1: //Do different
break;
case 2: //Do different
break;
/** For int more than 2, then I need
for it to do something same.
*/
case 3://Do different and case6
break;
case 4://Do different and case6
break;
case 5://Do different and case6
break;
case 6:
break;
}
What is an elegant way to do this, sans having a special case 6 function that case 3-5 calls? (I use int here, but that is an example, so I can't use if(int >2))
A switch can't really do exactly what you are asking out of the box. You can construct something like this with a nested switch though:
outer_switch: switch (example) {
case 1: System.out.println("1");
break;
case 2: System.out.println("2");
break;
default: {
switch (example) {
case 3: System.out.println("3");
break;
case 4: System.out.println("4");
break;
case 5: System.out.println("5");
break;
case 6: System.out.println("6");
break;
default: break outer_switch;
}
System.out.println("not 1 nor 2");
}
}
Note the labeled break on outer_switch which is a way to circumvent the shared code if example does not meet any of the inner cases.
One way I could think of is to move your code to different functions. Something like this.
void case1(){
// do something
}
...
void case3(){
// do something
case6();
}
...
void case6(){
// do something
}
// This switch is in some other method.
switch(int example)
{
case 1: //Do different
case1();
break;
...
case 3://Do different and case6
case3(); //internally calls case 6
break;
...
case 6:
case6();
break;
}
Or you can even have different methods for each case and call case3() and case6() methods in the case 3:. Either way, the methods solutions would work, and IMHO, it would be a bit more elegant and multiple switch statements.
I'm not sure if it's elegant, but one way would be to have two switch blocks:
switch(int example)
{
case 1: //Do different
break;
case 2: //Do different
break;
case 3:
// Do whatever
break;
case 4:
// Do whatever
break;
case 5:
// Do whatever
break;
}
switch(int example)
{
case 3:
case 4:
case 5:
case 6:
// Do whatever (case 3-5 fall through)
break;
}
Although your code is not pretty it's probably going to give you decent performance. Your other obvious option is an if-elseif-else statement. See the accepted answer here for why switch might be the best option, and here to see what performance issues you might run into with large switch statements in Java.
This might also be a solution to what you want to achieve:
switch(example){
case 1:
System.out.println(example);
break;
case 2:
System.out.println(example);
break;
case 3:
System.out.println("I'm case 3");
case 4:
if (example == 4){
System.out.println("I'm case 4");
}
case 5:
if (example == 5){
System.out.println("I'm case 5");
}
case 6:
System.out.println("I'm in extra case " + example);
break;
}
The idea is that you add an extra condition check to let your code fall through all the branches without executing unnecessary ones.

Big Hex to binary

I have looked at a lot of post here on stackoverflow concerning this problem, I have found partial solutions but so far I have yet to find a solution that works for me.
new BigDecimal("3324679375210329505").toString(2);
Seems to work best for me (from: Convert a large 2^63 decimal to binary) but I do need leading and trailing zeros. Is there anyway I can convert a large (bigger than a long) hex to a binary (String) representation?
Thanks in advance.
The BigInteger class handles arbitrarily large numbers.
Trailing zeroes are allready handled. To handle leading zeroes, simply add a "1" at the front, which ensures a leading "1" bit, then strip it back off again:
String bits = new BigInteger("1" + hex, 16).toStting(2).substring(1);
You need leading zeroes? I don't know of a built-in function, but you can easily implement it yourself:
public static String hex2binary(String hex) {
StringBuilder result = new StringBuilder(hex.length() * 4);
for (char c : hex.toUpperCase().toCharArray()) {
switch (c) {
case '0': result.append("0000"); break;
case '1': result.append("0001"); break;
case '2': result.append("0010"); break;
case '3': result.append("0011"); break;
case '4': result.append("0100"); break;
case '5': result.append("0101"); break;
case '6': result.append("0110"); break;
case '7': result.append("0111"); break;
case '8': result.append("1000"); break;
case '9': result.append("1001"); break;
case 'A': result.append("1010"); break;
case 'B': result.append("1011"); break;
case 'C': result.append("1100"); break;
case 'D': result.append("1101"); break;
case 'E': result.append("1110"); break;
case 'F': result.append("1111"); break;
default: throw new IllegalArgumentException("Invalid hex: '" + hex + "'");
}
}
return result.toString();
}

Categories

Resources