2013-11-26 111 views
1

我不明白爲什麼日食希望我刪除「;」並用「,」替換它。變量聲明問題

numberOfTimes1 = numberOfTimes + numberOfDelayTimes; 

我猜這是一些簡單的語法,我忘了。你能否解釋一下爲什麼這樣做以及如何解決這個問題。 整個程序

public class Spam { 


    public static void main(String[] args) { 
     //1- Taking an instance of Timer class. 
     Timer timer = new Timer("Printer"); 

     //2- Taking an instance of class contains your repeated method. 
     timeso t = new timeso(); 

     timer.schedule(t, 0, 10); 
    } 

} 
class timeso extends TimerTask { 
    //times member represent calling times. 
    private int times = 0; 
    int time = 6; //How long do you wish for the spamming to run? 
    int numberOfTimes = time * 100; 
    int delayTime = 5; //How long do you wish for the program to wait before spamming? 
    int numberOfDelayTimes = delayTime * 100; 
    numberOfTimes = numberOfTimes + numberOfDelayTimes; 
    String spam; 
    Random randomGenerator = new Random(); 

    public void run() { 
     times++; 
     if (times >= numberOfDelayTimes && times <= numberOfTimes+numberOfDelayTimes) { 

      try { 
       Robot typer = new Robot(); 
       //for(int x = 1;x <=randomGenerator.nextInt(5); x++){ 
       // spam = spam + randomGenerator.nextInt(10); 
       //} 
       byte[] bytes = "spam".getBytes(); 
       //byte[] bytes = spam.getBytes(); 
       for (byte b : bytes){ 
        int code = b; 
        // key code only handles [A-Z] (which is ASCII decimal [65-90]) 
        if (code > 96 && code < 123) code = code - 32; 
        typer.delay(10/bytes.length+1); 
        typer.keyPress(code); 
        typer.keyRelease(code); 
       } 
       if(times % (randomGenerator.nextInt(25)+1) == 0){ 
        typer.delay(10/bytes.length+1); 
        typer.keyPress(KeyEvent.VK_ENTER); 
        typer.keyRelease(KeyEvent.VK_ENTER); 
       } 
      } 
      catch (AWTException e){ 
      } 
     } else { 
      if (times >= numberOfTimes){ 
       try{ 
        Robot typer = new Robot(); 
        typer.delay(10); 
        typer.keyPress(KeyEvent.VK_ENTER); 
        typer.keyRelease(KeyEvent.VK_ENTER); 
       } catch(Exception e){ 

       } 
       //Stop Timer. 
       this.cancel(); 
      } 
     } 
} 
    } 

回答

3

你試圖調用的代碼行的方法或構造之外,這就是爲什麼Java編譯器(不蝕)抱怨。在構造函數或方法中做這樣的代碼,而不是在類中裸體。事實上,你的timeso類中的所有代碼都是不正確的,需要在方法或構造函數中。

注意:您需要學習Java命名約定並堅持使用它,包括以大寫字母開頭的類名和使用小寫字母的方法和變量名。這樣做會幫助其他人(我們!)更好地理解你的代碼。

+0

我不能把聲明代碼放入運行,因爲它會將numberOfTimes保留爲1.我會在哪裏放置代碼? –

+0

@Cammy_the_block:在你尚未但需要創建的構造函數中。 –

+0

如果我在構造函數中有這些聲明run()會如何訪問它? –