2

I want to make a bot, that reads a sentence from user input and then types it 5 seconds after the user did the input. This is what I came up with:

public class Main {
        static Robot robot;

        public static void main(String[] args) throws AWTException {
            robot = new Robot();
            String text = "";
            Scanner scanner = new Scanner(System.in);
            System.out.println("Enter Text that should be typed....");
            text = scanner.nextLine();
            scanner.close();
            Main.sleep(5);
            writeString(text);
        }
        public static void writeString(String s) {
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (Character.isUpperCase(c)) {
                robot.keyPress(KeyEvent.VK_SHIFT);
            }
            robot.keyPress(Character.toUpperCase(c));
            robot.keyRelease(Character.toUpperCase(c));

            if (Character.isUpperCase(c)) {
                robot.keyRelease(KeyEvent.VK_SHIFT);
            }
            Main.sleep(0.1);
        }
    }
}

Unfortunatley, when I paste in the sentence "Hello, this is a test sentence. Hows your day going?" there is an Exception when robot wants to type "?". How can I fix this and prevent the program from crashing at other punctuation characters like ' " * # etc. ?

I tried to convert the chars of the text into keycode and put the keycode into robot.keyPress(keycode). I converted it like this: int keycode = (int) text.charAt(...) but this caused even more trouble....

I hope someone can help me here because I have a feeling that it's actually quite easy :-)

derpascal
  • 172
  • 1
  • 10

1 Answers1

0

According to the relevant JavaDoc, not all characters have a keycode associated with them. One such character is precisely the question mark, as there is no keyboard for which it appears on the primary layer (i.e. where it can be produced without pressing a modifier key, like shift). That means that, for use with the Robot class, the events you have to simulate depend on the layout of your keyboard. For example, to produce a question mark I would have to press shift and the single quote key (').

JustAnotherDeveloper
  • 2,061
  • 2
  • 10
  • 24