2017-04-04 28 views
1

我在codingame.com上做了一些謎題,我在Groovy中做了這些。我遇到了一個令人困惑的問題。這裏是你把你的程序分成(省略了一些不相關的代碼)文件:我不能在Groovy腳本中放置類聲明嗎?

input = new Scanner(System.in); 

/** 
* Auto-generated code below aims at helping you parse 
* the standard input according to the problem statement. 
**/ 

lightX = input.nextInt() // the X position of the light of power 
lightY = input.nextInt() // the Y position of the light of power 
initialTX = input.nextInt() // Thor's starting X position 
initialTY = input.nextInt() // Thor's starting Y position 

fartherThanPossible = 100 

class Point { 
    Integer x 
    Integer y 
    Integer distanceFromTarget = fartherThanPossible 
} 

def currentPos = new Point(x: initialTX, y: initialTY) 

什麼情況是,當我試圖將類實例,一個例外是拋出的最後一行上面的代碼塊。異常本身並不是非常有用,我認爲這是因爲該文件是作爲腳本運行的?

at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:53) 
at Answer.run on line 28 

我不允許在Groovy腳本中放置類聲明嗎?據我所知,文件似乎說我可以。

+0

與上面的代碼,看到'沒有這樣的屬性:fartherThanPossible類:Point' 。順便說一下,這非常有效。 – Rao

+0

Fylke,請看下面是否有幫助 – Rao

回答

1

是的,在一個腳本中有類是有效的。

當你的腳本運行,以下是輸出:

$ groovy testthor.groovy 
7 
8 
8 
9 
Caught: groovy.lang.MissingPropertyException: No such property: fartherThanPossible for class: Point 
groovy.lang.MissingPropertyException: No such property: fartherThanPossible for class: Point 
    at Point.<init>(testthor.groovy) 
    at testthor.run(testthor.groovy:21) 

這是因爲在類定義的最後一行不正確說法。

只需改變腳本下面來解決該問題:

input = new Scanner(System.in) 

/** 
* Auto-generated code below aims at helping you parse 
* the standard input according to the problem statement. 
**/ 

lightX = input.nextInt() // the X position of the light of power 
lightY = input.nextInt() // the Y position of the light of power 
initialTX = input.nextInt() // Thor's starting X position 
initialTY = input.nextInt() // Thor's starting Y position 

fartherThanPossible = 100 
//Added 
@groovy.transform.ToString 
class Point { 
    Integer x 
    Integer y 
    //changed 
    Integer distanceFromTarget 
} 

def currentPos = new Point(x: initialTX, y: initialTY, distanceFromTarget: farther 
ThanPossible) 
//Added 
println currentPos.toString() 

輸出:

$ groovy testthor.groovy 
87 
88 
8 
99 
Point(8, 99, 100) 
+0

謝謝,我會在我回家的時候嘗試一下!我想給distanceFromTarget變量一個默認值,那是不可能的呢? – Fylke

相關問題