我正在尝试从字符变量中填充整数变量。如果发现任何错误,我想显示错误消息并跟踪所有可能的失败案例。
//Defining variable
Define variable char_value as character no-undo initial "kk".
Define variable int_value as integer no-undo.
define variable ix as integer no-undo.
Assign int_value = integer(char_value) no-error.
IF ERROR-STATUS:ERROR OR ERROR-STATUS:NUM-MESSAGES > 0 THEN
DO:
MESSAGE ERROR-STATUS:NUM-MESSAGES
" errors occurred during conversion." SKIP
"Do you want to view them?"
VIEW-AS ALERT-BOX QUESTION BUTTONS YES-NO
UPDATE view-errs AS LOGICAL.
IF view-errs THEN
DO ix = 1 TO ERROR-STATUS:NUM-MESSAGES:
MESSAGE ERROR-
STATUS:GET-NUMBER(ix)
ERROR-STATUS:GET-
MESSAGE(ix).
END.
END.
我想知道两个条件。
答案 0 :(得分:1)
内置的转换例程无法执行您想要的操作。因此,在尝试转换输入之前,您将需要分析您的输入。像这样:
function isDigit returns logical ( input d as character ):
if length( d ) = 1 then
return ( index( "0123456789", d ) > 0 ).
else
return no.
end.
procedure checkInteger:
define input parameter integerString as character no-undo.
define output parameter errorList as character no-undo.
define output parameter ok as logical no-undo.
define variable i as integer no-undo.
define variable n as integer no-undo.
define variable c as character no-undo.
ok = yes.
n = length( integerString ).
do i = 1 to n:
c = substring( integerString, i, 1 ).
if i = 1 and c = "-" then next.
if isDigit( c ) = no then
do:
ok = no.
errorList = errorList + substitute( "The character '&1' at offset &2 is not a valid integer value~n", c, i ).
end.
end.
errorList = trim( errorList, "~n" ). // remove the trailing newline (if any)
return.
end.
define variable ok as logical no-undo.
define variable errorList as character no-undo.
run checkInteger( "12x34y56z789", output errorList, output ok ).
if ok = yes then
message "string is a properly formed integer, go ahead and convert it".
else
message
"string was not correctly formed, do not try to convert it" skip
errorList
view-as alert-box information
.
注释#1如果输入包含不可打印的字符,则errorList字符串将按字面显示它,并且看起来很有趣。当然,您可以对它们进行编码以使其更具可读性。这样做是一项练习。或另一个问题。
注释#2此代码不尝试检查字符串值是否适合整数或int64。这也留作练习。
答案 1 :(得分:0)
虽然您可以根据需要进行复杂的解析,但我只是保持简单并确保为用户提供了足够的信息,在这种情况下,这是完整的输入值:
def var cc as char initial "kk".
def var ii as int.
ii = integer( cc ).
catch e as progress.lang.error:
message quoter( cc, "'" ) e:getMessage(1) view-as alert-box.
end catch.