2017-04-04 41 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