0

我有这个代码:

static def parseString(String inputRow, Particle particle) {
        //input row is:
        //static final inputRow = "1 -5.2 3.8"
        def map = inputRow.split()
        particle.mass = Integer.parseInt(map[0])
        particle.x = Integer.parseInt(map[1])
        particle.y = Integer.parseInt(map[2])
}

此代码引发此错误:

java.lang.NumberFormatException: For input string: "-5.2"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:492)
    at java.lang.Integer.valueOf(Integer.java:582)
    at RepulsionForce.parseString(RepulsionForce.groovy:13)
    at RepulsionForceTest.string should be parsed into particles(RepulsionForceTest.groovy:27)

如何避免此异常?

4

4 回答 4

3

您可以减少冗余线,如下所示,particle地图在哪里:

def arr = inputRow.split()
def mass, x, y
(mass, x, y) = arr*.toDouble()
def particle = [:] << [mass: mass, x: x, y: y]

错过了Particle替代课程的部分。

于 2013-09-23T15:23:28.330 回答
2

哎呀,想通了... 5.2 不是整数。

static def parseString(String inputRow, Particle particle) {
    def map = inputRow.split()
    particle.mass = Double.parseDouble(map[0])
    particle.x = Double.parseDouble(map[1])
    particle.y = Double.parseDouble(map[2])
}
于 2013-09-23T15:00:25.767 回答
1

这是一种方法......在完整的解决方案中回答:

// setup
class Particle {
    def mass
    def x
    def y
}

def particle = new Particle()
def inputRow = "1 -5.2 3.8"
def fieldsByIndex = [0: "mass", 1: "x", 2: "y"]

// answer
inputRow.split().eachWithIndex { val, index ->
    def field = fieldsByIndex.get(index)
    particle."${field}" = val.toDouble()
}

// output
println "mass :  " + particle.mass
println "x :  " + particle.x
println "y :  " + particle.y
于 2013-09-24T02:04:10.787 回答
0

说明:您错误地尝试将Double数解析为Integer数并且它不适用,不共享相同的类型(整数!= double),并且不会工作 - 因此您会收到java.lang.NumberFormatException: For input string明确通知您类型问题的异常。

解决方案Double:使用Class将其转换为 double 。

Double.parseDouble(map[i])
于 2020-05-18T13:43:11.943 回答