我在codingame.com上做的谜题,我在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 :(得分: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)