如何在 Groovy 中做到这一点?

sri*_*ram 3 groovy

假设有两个变量,变量的值取自用户。那是:

a=0
b=1
c=a-b
Run Code Online (Sandbox Code Playgroud)

在某些情况下,我需要变量c始终为正数,Groovy 中是否有任何方法可以做到这一点?

Gar*_*vis 5

几个选项,具体取决于您在c否定时实际想要的行为:

c = Math.abs(c) // -1 will become 1

c = Math.max(0,c) // -1 will become 0

// or it's an error condition
if( c < 0 ){
    tellUserToStopMessingAroundAndEnterTheCorrectValues()
    return
}
Run Code Online (Sandbox Code Playgroud)