机器人r无法解决

时间:2014-04-25 09:51:55

标签: java if-statement robot

public void method1 (int x) {
    if (x == 1) {
        try {
            Robot r = new Robot();
        } catch (AWTException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        r.mouseMove(50,50);

但是这给r无法解决。有任何想法吗? = /非常感谢

2 个答案:

答案 0 :(得分:4)

public void method1 (int x) {
if (x == 1) {
    try {
        Robot r = new Robot(); // R is defined in the try block. It is not visible outside of this block.
    } catch (AWTException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    r.mouseMove(50,50); // R is not defined anymore here

将其替换为

public void method1 (int x) {
if (x == 1) {
    try {
        Robot r = new Robot();
        r.mouseMove(50,50);
    } catch (AWTException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

答案 1 :(得分:2)

应该是:

public void method1 (int x) {
 Robot r = null;
if (x == 1) {

    try {
         r = new Robot();
    } catch (AWTException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
       return;
    }
    r.mouseMove(50,50);