Ошибка в делфи is not a valid integer value

0 / 0 / 0

Регистрация: 06.11.2011

Сообщений: 31

1

26.10.2012, 11:39. Показов 21044. Ответов 14


Студворк — интернет-сервис помощи студентам

Делаю конвертер валют и при нажатии на кнопку «Посчитать» появляется ошибка
«is not a valid integer value».
Когда вместо integer ставим тип longint или real то ничего не происходит.
В чём проблема???помогите решить.



0



898 / 345 / 65

Регистрация: 11.02.2012

Сообщений: 1,502

26.10.2012, 11:41

2

Ну значит у тебя несовместимость типов.
Продемонстрируй код.



0



Alkcatras

0 / 0 / 0

Регистрация: 06.11.2011

Сообщений: 31

26.10.2012, 11:52

 [ТС]

3

Delphi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
var   BUR,EUR,USD,RUB,SUMMA:integer;
  Form1: TForm1;
 
implementation
 
{$R *.dfm}
 
procedure TForm1.Button1Click(Sender: TObject);
begin
CLOSE;
end;
 
procedure TForm1.Button2Click(Sender: TObject);
begin
SUMMA:=StrToInt(EDIT1.TEXT);
BUR:=STRTOINT(EDIT2.Text);
RUB:=STRTOINT(EDIT3.Text);
USD:=STRTOINT(EDIT4.Text);
EUR:=STRTOINT(EDIT5.Text);
 
if RADIOBUTTON1.Checked=TRUE AND RADIOBUTTON2.Checked=FALSE AND RADIOBUTTON2.Checked=FALSE then
BEGIN
BUR:=SUMMA*RUB;
EDIT2.Text:=INTTOSTR(BUR);
//SHOWMESSAGE('BUR');
END;
if RADIOBUTTON1.Checked=FALSE AND RADIOBUTTON2.Checked=TRUE AND RADIOBUTTON2.Checked=FALSE then
BEGIN
BUR:=SUMMA*USD;
EDIT2.Text:=INTTOSTR(BUR);
END;
if RADIOBUTTON1.Checked=FALSE AND RADIOBUTTON2.Checked=FALSE AND RADIOBUTTON2.Checked=TRUE then
BEGIN
BUR:=SUMMA*EUR;
EDIT2.Text:=INTTOSTR(BUR);
END;
end;
 
end.

Добавлено через 8 минут

Цитата
Сообщение от HanDi
Посмотреть сообщение

Ну значит у тебя несовместимость типов.
Продемонстрируй код.

Delphi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
var   BUR,EUR,USD,RUB,SUMMA:integer;
  Form1: TForm1;
 
implementation
 
{$R *.dfm}
 
procedure TForm1.Button1Click(Sender: TObject);
begin
CLOSE;
end;
 
procedure TForm1.Button2Click(Sender: TObject);
begin
SUMMA:=StrToInt(EDIT1.TEXT);
BUR:=STRTOINT(EDIT2.Text);
RUB:=STRTOINT(EDIT3.Text);
USD:=STRTOINT(EDIT4.Text);
EUR:=STRTOINT(EDIT5.Text);
 
if RADIOBUTTON1.Checked=TRUE AND RADIOBUTTON2.Checked=FALSE AND RADIOBUTTON2.Checked=FALSE then
BEGIN
BUR:=SUMMA*RUB;
EDIT2.Text:=INTTOSTR(BUR);
//SHOWMESSAGE('BUR');
END;
if RADIOBUTTON1.Checked=FALSE AND RADIOBUTTON2.Checked=TRUE AND RADIOBUTTON2.Checked=FALSE then
BEGIN
BUR:=SUMMA*USD;
EDIT2.Text:=INTTOSTR(BUR);
END;
if RADIOBUTTON1.Checked=FALSE AND RADIOBUTTON2.Checked=FALSE AND RADIOBUTTON2.Checked=TRUE then
BEGIN
BUR:=SUMMA*EUR;
EDIT2.Text:=INTTOSTR(BUR);
END;
end;
 
end.



0



Супер-модератор

Эксперт Pascal/DelphiАвтор FAQ

32592 / 21061 / 8134

Регистрация: 22.10.2011

Сообщений: 36,332

Записей в блоге: 8

26.10.2012, 11:53

4

Во-первых, это не должно даже компилироваться (не хватает скобок в If-ах), а если и скомпилируется, то работать может не так, как подразумевалось, так что исправляй. А во-вторых, покажи скриншот, что именно ты вводишь в эдиты.



0



HanDi

26.10.2012, 11:57

Не по теме:

Цитата
Сообщение от Alkcatras
Посмотреть сообщение

if RADIOBUTTON1.Checked=TRUE AND RADIOBUTTON2.Checked=FALSE AND RADIOBUTTON2.Checked=FALSE then

о мои глаза.. о мой МОЗГ!



0



0 / 0 / 0

Регистрация: 06.11.2011

Сообщений: 31

26.10.2012, 11:58

 [ТС]

6

Это компилируется…

Миниатюры

Ошибка "is not a valid integer value".
 



0



0 / 0 / 0

Регистрация: 06.11.2011

Сообщений: 31

26.10.2012, 12:00

 [ТС]

7

Цитата
Сообщение от HanDi
Посмотреть сообщение

Не по теме:

о мои глаза.. о мой МОЗГ!

просто сначало использовал CheckBox



0



volvo

Супер-модератор

Эксперт Pascal/DelphiАвтор FAQ

32592 / 21061 / 8134

Регистрация: 22.10.2011

Сообщений: 36,332

Записей в блоге: 8

26.10.2012, 12:05

8

Цитата
Сообщение от Alkcatras
Посмотреть сообщение

Это компилируется…

А я предупреждал, что это может работать неправильно. Смотри, как условие

Delphi
1
if RADIOBUTTON1.Checked=FALSE AND RADIOBUTTON2.Checked=TRUE AND RADIOBUTTON2.Checked=FALSE then

видит компилятор (учитывая, что приоритет AND выше приоритета операции сравнения, а все операции сравнения выполняются, как им и положено, слева направо)

Delphi
1
if ((RADIOBUTTON1.Checked=(FALSE AND RADIOBUTTON2.Checked))=(TRUE AND RADIOBUTTON2.Checked))=FALSE then

Чувствуешь разницу? То есть, какой кусок кода выполняется в какой момент времени — совершенно непонятно. Добавь скобки:

Delphi
1
2
3
if (RADIOBUTTON1.Checked=FALSE) AND (RADIOBUTTON2.Checked=TRUE) AND (RADIOBUTTON2.Checked=FALSE) then
// или вот так
if not RADIOBUTTON1.Checked AND RADIOBUTTON2.Checked AND not RADIOBUTTON2.Checked then

— будет ближе к истине (приоритет NOT выше, чем сравнения, так что тут проблем не будет).



0



Alkcatras

0 / 0 / 0

Регистрация: 06.11.2011

Сообщений: 31

26.10.2012, 12:15

 [ТС]

9

поставил так

Delphi
1
if (RADIOBUTTON1.Checked=TRUE) AND (RADIOBUTTON2.Checked=FALSE) AND (RADIOBUTTON2.Checked=FALSE) then

считает только для RUS

Добавлено через 4 минуты
немного не понимаю вот это

Delphi
1
if not RADIOBUTTON1.Checked AND RADIOBUTTON2.Checked AND not RADIOBUTTON2.Checked then

Можешь объяснит??



0



Модератор

3488 / 2611 / 741

Регистрация: 19.09.2012

Сообщений: 7,971

26.10.2012, 12:36

10

not true = false, а RADIOBUTTON1.Checked уже само по себе либо true, либо false, незачем его еще с чем-то сравнивать.



0



Alkcatras

0 / 0 / 0

Регистрация: 06.11.2011

Сообщений: 31

26.10.2012, 17:18

 [ТС]

11

Цитата
Сообщение от UI
Посмотреть сообщение

А я предупреждал, что это может работать неправильно. Смотри, как условие

Delphi
1
if RADIOBUTTON1.Checked=FALSE AND RADIOBUTTON2.Checked=TRUE AND RADIOBUTTON2.Checked=FALSE then

видит компилятор (учитывая, что приоритет AND выше приоритета операции сравнения, а все операции сравнения выполняются, как им и положено, слева направо)

Delphi
1
if ((RADIOBUTTON1.Checked=(FALSE AND RADIOBUTTON2.Checked))=(TRUE AND RADIOBUTTON2.Checked))=FALSE then

Чувствуешь разницу? То есть, какой кусок кода выполняется в какой момент времени — совершенно непонятно. Добавь скобки:

Delphi
1
2
3
if (RADIOBUTTON1.Checked=FALSE) AND (RADIOBUTTON2.Checked=TRUE) AND (RADIOBUTTON2.Checked=FALSE) then
// или вот так
if not RADIOBUTTON1.Checked AND RADIOBUTTON2.Checked AND not RADIOBUTTON2.Checked then

— будет ближе к истине (приоритет NOT выше, чем сравнения, так что тут проблем не будет).

поставил так

Delphi
1
if (RADIOBUTTON1.Checked=TRUE) AND (RADIOBUTTON2.Checked=FALSE) AND (RADIOBUTTON2.Checked=FALSE) then

считает только для RUS, для USD и EUR не считает



0



Супер-модератор

Эксперт Pascal/DelphiАвтор FAQ

32592 / 21061 / 8134

Регистрация: 22.10.2011

Сообщений: 36,332

Записей в блоге: 8

26.10.2012, 17:24

12

Ты все свои условия подобным образом поправил, или только одно какое-то? Исправь все (строки 21, 27, 32 из третьего сообщения), потом скажешь, получилось или нет.



0



0 / 0 / 0

Регистрация: 06.11.2011

Сообщений: 31

26.10.2012, 17:30

 [ТС]

13

Цитата
Сообщение от UI
Посмотреть сообщение

Ты все свои условия подобным образом поправил, или только одно какое-то? Исправь все (строки 21, 27, 32 из третьего сообщения), потом скажешь, получилось или нет.

Да все, и 21 и 27 и 32.Считает только для RUS.В RUS пишу число в сумме 1 в остольных Edit-ах 0(если не писать то появляется ошибка «is not a valid integer value») при выполнении появляется число из RUS.но если делать это для USD или EUR ничего вообще не происходит.



0



volvo

Супер-модератор

Эксперт Pascal/DelphiАвтор FAQ

32592 / 21061 / 8134

Регистрация: 22.10.2011

Сообщений: 36,332

Записей в блоге: 8

26.10.2012, 17:33

14

И вообще, почему нельзя вместо трех независимых RadioButton-ов использовать один RadioGroup с тремя элементами, и проверять:

Delphi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
   case RadioGroup1.ItemIndex of
      0 : // Рубли
      begin
         // переводишь рубли по курсу
      end;
      1 : // Баксы
      begin
         // переводишь баксы по курсу
      end;
      2 : // Евро
      begin
         // переводишь евробаксы по курсу
      end;
   end;

?

Кстати, ошибка твоя — от невнимательности:

Delphi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
procedure TForm1.Button2Click(Sender: TObject);
begin
SUMMA:=StrToInt(EDIT1.TEXT);
 
// Это не надо делать. Возьми только данные для нужной единицы, в соотв. ветке ниже.
//BUR:=STRTOINT(EDIT2.Text);
//RUB:=STRTOINT(EDIT3.Text);
//USD:=STRTOINT(EDIT4.Text);
//EUR:=STRTOINT(EDIT5.Text);
 
if RADIOBUTTON1.Checked AND not RADIOBUTTON2.Checked AND not RADIOBUTTON3.Checked then
BEGIN
RUB:=STRTOINT(EDIT3.Text);
BUR:=SUMMA*RUB;
EDIT2.Text:=INTTOSTR(BUR);
//SHOWMESSAGE('BUR');
END;
if not RADIOBUTTON1.Checked AND RADIOBUTTON2.Checked AND not RADIOBUTTON3.Checked then
BEGIN
USD:=STRTOINT(EDIT4.Text);
BUR:=SUMMA*USD;
EDIT2.Text:=INTTOSTR(BUR);
END;
if not RADIOBUTTON1.Checked AND not RADIOBUTTON2.Checked AND RADIOBUTTON3.Checked then
BEGIN
EUR:=STRTOINT(EDIT5.Text);
BUR:=SUMMA*EUR;
EDIT2.Text:=INTTOSTR(BUR);
END;
end;

, и потом, у тебя вообще не присутствовал RADIOBUTTON3, зато RADIOBUTTON2 везде проверялся по 2 раза…



0



Alkcatras

0 / 0 / 0

Регистрация: 06.11.2011

Сообщений: 31

26.10.2012, 17:59

 [ТС]

15

Цитата
Сообщение от UI
Посмотреть сообщение

И вообще, почему нельзя вместо трех независимых RadioButton-ов использовать один RadioGroup с тремя элементами, и проверять:

Delphi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
   case RadioGroup1.ItemIndex of
      0 : // Рубли
      begin
         // переводишь рубли по курсу
      end;
      1 : // Баксы
      begin
         // переводишь баксы по курсу
      end;
      2 : // Евро
      begin
         // переводишь евробаксы по курсу
      end;
   end;

?

Кстати, ошибка твоя — от невнимательности:

Delphi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
procedure TForm1.Button2Click(Sender: TObject);
begin
SUMMA:=StrToInt(EDIT1.TEXT);
 
// Это не надо делать. Возьми только данные для нужной единицы, в соотв. ветке ниже.
//BUR:=STRTOINT(EDIT2.Text);
//RUB:=STRTOINT(EDIT3.Text);
//USD:=STRTOINT(EDIT4.Text);
//EUR:=STRTOINT(EDIT5.Text);
 
if RADIOBUTTON1.Checked AND not RADIOBUTTON2.Checked AND not RADIOBUTTON3.Checked then
BEGIN
RUB:=STRTOINT(EDIT3.Text);
BUR:=SUMMA*RUB;
EDIT2.Text:=INTTOSTR(BUR);
//SHOWMESSAGE('BUR');
END;
if not RADIOBUTTON1.Checked AND RADIOBUTTON2.Checked AND not RADIOBUTTON3.Checked then
BEGIN
USD:=STRTOINT(EDIT4.Text);
BUR:=SUMMA*USD;
EDIT2.Text:=INTTOSTR(BUR);
END;
if not RADIOBUTTON1.Checked AND not RADIOBUTTON2.Checked AND RADIOBUTTON3.Checked then
BEGIN
EUR:=STRTOINT(EDIT5.Text);
BUR:=SUMMA*EUR;
EDIT2.Text:=INTTOSTR(BUR);
END;
end;

, и потом, у тебя вообще не присутствовал RADIOBUTTON3, зато RADIOBUTTON2 везде проверялся по 2 раза…

ахахахах глупая ошибка спасибо, следующий раз буду повнимательнее



0



Либо проверяйте тип возбуждаемого исключения:

try
    L.CustomSort(MySort);
  except
    on E:EConvertError do ShowMessage('Ошибка, неправильно введены значения') // ошибка конвертации
    else raise; // прочие ошибки
end;

Либо контролируйте данные на этапе сортировки (или другом этапе):

function MySort(L: TStringList; ind1, ind2: integer): integer;
var i1, i2: integer;
begin
 if (not (TryStrToInt(L.ValueFromIndex[ind1], i1) and TryStrToInt(L.ValueFromIndex[ind2], i2))) or // Если не удалось конвертировать
  (i1 = i2) then // или результаты конвертаций равны, то
    result := 0
  else if i1 > i2 then result := 1
        else result := -1;
end;

В вашем примере возбуждать исключение вообще не вариант, так как оно прервет выполнение метода Button2Click и динамически созданный TStringList не уничтожится. Если вы не выполните этого в секции except. Ну или так:

procedure TForm1.Button2Click(Sender: TObject);
var L: TStringList;
begin
 L := TStringList.Create;
 try
   L.Text := Memo1.Text;
   try
     L.CustomSort(MySort);
   except
    ... обработка исключения ...
   end;
   Memo2.Text := L.Text;
 finally
   L.Free;
 end;
end;

30K

22 марта 2010 года

Morphling

74 / / 17.01.2010

может я вам не так объяснил, кароч я хотел создать типо калькулятор, к каждой кнопке присвоил caption 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 соответственно. Также есть кнопка «/», «*», «-«, «+» и «=» (без кавычек конечно), которые должны выполнять действие caption. Вот когда я нажимаю на одну из кнопок то в edit1.text появляется собственно caption нажатой кнопки. Например нажал на кнопку «2» «+» «3», в edit1.text появился текст 2 + 3, а потом нажимаю на «=». Вот он должен был мне возвратить 2+3=5, потому что, как я описал выше сначала edit1.text преобразуется в число strtoint(edit1.text), а это в свою очередь присваивается к result, у нас уже это выглядит так
result := strtoint(edit1.text), после этого, result должен посчитать и присвоить значение от 2+3 и вывести на edit1.text (преобразовать целое в строку я не забыл), а он этого не делает и вместо выходит ошибка… Кто понимает, в чем тут проблема?

  • Prev
  • 1
  • 2
  • Next
  • Page 1 of 2  

Recommended Posts

I’ve got a program that asks the user to enter a value (in an Edit box) and then when he clicks on the Show Value button, the Label should say «The value of x is » plus whatever value he entered in the Edit box.

But Delphi is complaining saying «x is not a valid integer value.»

I don’t know what’s wrong with my code but here is what I’ve got:

var
  FormSimpleVariable: TFormSimpleVariable;
  x : integer;

implementation

{$R *.dfm}

procedure TFormSimpleVariable.ButtonQuitClick(Sender: TObject);
begin
  Application.Terminate;
end;

procedure TFormSimpleVariable.ButtonShowValueClick(Sender: TObject);
begin
  x := StrToInt('x');
  LabelResult.Caption := 'The value of x is ' + IntToStr(x);
end;

end.

Share this post


Link to post

Do you understand what StrToInt() actually does?  What do you think StrToInt(‘x’) should do, and why do you think it should NOT throw an error (hint: it SHOULD)?  The string ‘x’ is not representative of a valid integer value, so of course it can’t be converted into an actual integer.

You said the user is entering a value in an Edit box, but this code is not accessing that Edit box at all.

You need something more like this instead:

procedure TFormSimpleVariable.ButtonShowValueClick(Sender: TObject);
var
  x: Integer;
begin
  x := StrToInt(EditValue.Text);
  LabelResult.Caption := 'The value of x is ' + IntToStr(x);
end;

Alternatively, for numeric input, consider using a more appropriate UI control, like TSpinEdit or TNumberBox, which provide the input as actual integers rather than as strings.


Edited April 28 by Remy Lebeau

Share this post


Link to post

considere (too) alternative «Def» function to: StrToxxxDef(…, …)

Quote

    StrToIntDef(‘your number here’, 0);
    StrToInt64Def(‘your number here’, 0);
    StrToFloat()
    StrToUInt64()
    StrToUInt64Def()
    StrToFloatDef()

Share this post


Link to post

I had to read this question x times before I understood it


  • Haha


    1

Share this post


Link to post

How come you can’t assign a value to a variable in the same section you declared it? You gotta assign the value underneath the begin keyword instead.

Share this post


Link to post

1 hour ago, David Heffernan said:

before I understood it

your CPU it’s very fast… there is a delay time… it’s ok!  😂

…1, 2, 3, 5, 8… ops! starting again…  bip! bip! 


Edited April 28 by programmerdelphi2k

Share this post


Link to post

Are you Roman?

What do you expect from «StrToInt(‘x’)» ? 10 ?


  • Haha


    1

Share this post


Link to post

You guys are acting like jerks. I’m talking about a different piece of code now. If you can’t or don’t know how to be nice and respectful, then please go to bed.

Share this post


Link to post

49 minutes ago, 357mag said:

How come you can’t assign a value to a variable in the same section you declared it? You gotta assign the value underneath the begin keyword instead.

where do you assign it in c++/pick one ? before the «{«/pick one ?

Share this post


Link to post

5 hours ago, programmerdelphi2k said:

considere (too) alternative «Def» function to: StrToxxxDef(…, …)

And alternatively, the TryStrToxxx() functions.

Share this post


Link to post

@Remy Lebeau

right!  but «StrToxxxxxxDEF(….)» it’s more flexible (it dont needs a «var» to receive «out param…»)

var
  v: integer; // mandatory to TryStrToxxxx(...)
begin
  TryStrToInt('x', v); // more conservadore
  (*
    function TryStrToInt(const S: string; out Value: Integer): Boolean;
    var
    E: Integer;
    begin
	    Val(S, Value, E);
	    Result := E = 0;    // exchanging 6 for half a dozen
    end;
  *)
  //
  StrToIntDef('x', 0); // more flexible
  (*
    function StrToIntDef(const S: string; Default: Integer): Integer;
    var
    E: Integer;
    begin
	    Val(S, Result, E);
	    if E <> 0 then
        	Result := Default;  // exchanging 6 for half a dozen
    end;
  *)

  // at end, if works it's good too!

Share this post


Link to post

5 hours ago, Attila Kovacs said:

where do you assign it in c++/pick one ? before the «{«/pick one ?

5 hours ago, Attila Kovacs said:

where do you assign it in c++/pick one ? before the «{«/pick one ?

You guys are acting like jerks. I’m talking about a different piece of code now. If you can’t or don’t know how to be nice and respectful, then please go to bed.

In C++ you can assign a value to a variable immediately after declaring it. Delphi would not let me do that. I had to assign the values to the variables further down underneath the begin keyword.


  • Like


    1

Share this post


Link to post

1 hour ago, 357mag said:

In C++ you can assign a value to a variable immediately after declaring it. Delphi would not let me do that. I had to assign the values to the variables further down underneath the begin keyword.

This is not true. You can use an inline variable declaration. 

https://docwiki.embarcadero.com/RADStudio/en/Inline_Variable_Declaration

Please don’t tell us we are jerks. That’s just offensive and rude. 


  • Like


    3

Share this post


Link to post

4 hours ago, 357mag said:

I had to assign the values to the variables further down underneath the begin keyword.

In c++, you are also assigning it after the «begin».

Share this post


Link to post

yahooo!!!! :classic_cheerleader:


  • Like


    1

Share this post


Link to post

If StrToInt says a string is not a number thus it can not be converted, trust it, it’s true.

If you are really interested, you can use the function «Val» which will even tell you which character is causing it to fail.

You might want to sanitize your input first for spaces or other non-printable characters which get there easily if you copy-paste from documents / websites.

Also, consider what @Remy Lebeau said, and use a TSpinEdit or TNumberBox instead (you can check NumbersOnly in TEdit as well). This way the input won’t even be accepted if the pasted string / typed character is not a number.

Share this post


Link to post

I’m guessing what happened here is that asker put the variable name into a string and imagined it would be interpreted in the context of the variable namespace. 

Share this post


Link to post

19 hours ago, programmerdelphi2k said:

but «StrToxxxxxxDEF(….)» it’s more flexible (it dont needs a «var» to receive «out param…»)

On the other hand, the StrToxxxDef() functions don’t let you differentiate whether valid vs invalid input was entered unless you use a sentinel value that can’t appear in any valid input.  The TryStrToxxx() functions let you differentiate very easily.  Besides, what is the point of converting a string to an integer/floating type if you are not going to use the converted value anyway?

var
  v: integer;
begin
  // don't ignore the return value!
  // TryStrToInt('...', v);
  if TryStrToInt('...', v) then begin
    // use v as needed ...
  end else begin
    // error converting ...
  end;

  // don't ignore the return value!
  // StrToIntDef('...', 0);  
  v := StrToIntDef('...', 0);
  if v <> 0 then begin
    // use v as needed ...
  end else begin
    // was the input actually '0', or did an error occur ???
  end;
end;

Share this post


Link to post

59 minutes ago, aehimself said:

Also, consider what @Remy Lebeau said, and use a TSpinEdit or TNumberBox instead (you can check NumbersOnly in TEdit as well). This way the input won’t even be accepted if the pasted string / typed character is not a number.

Do note that setting TEdit.NumbersOnly=true merely tells the TEdit to accept only digit characters and no others (so, no negatives, no decimals, etc) , but it will not validate that the text as a whole will convert to a valid integer. So you still have to handle that conversion yourself, if you don’t use a UI control that does it for you.

Share this post


Link to post

34 minutes ago, Remy Lebeau said:

if you are not going to use the converted value anyway?

The excence of the alternative functions in question is the same!

  •   Val(S, Value, E);

What distinguishes the two is just how the return is reported to the user:

  1. returns a boolean;
  2. the other an integer;

however, the «out» parameter has the same function: capture the value, a value «pre-defined» by the user, and use it: either through a variable informed by the user, or through the return of the function.

  • they are two flavors of the same fruit!
// none error at all, just "is valid or not?"
var
  LResult: integer;
begin
  if StrToIntDef('hello', 0) = 0 then
    ShowMessage('bye bye');
  //
  LResult := StrToIntDef('hello', 0);
  //
  if (LResult = 0) then
    ShowMessage('bye bye');
  //
  //
  if TryStrToInt('hello', LResult) then { ... };
  //
  if (LResult = 0) then
    ShowMessage('bye bye');

Share this post


Link to post

The point about return value vs out param is that the former can be composed directly in chained function calls. 

Share this post


Link to post

if TryStrToInt('hello', LResult) and (LResult >0) then
	ShowMessage(' it,s good for us :) ');

Share this post


Link to post

I don’t recall adding those single quotes around x (like (‘x’)). Don’t know what happened there. Mistakes and being human I guess.

Share this post


Link to post

7 hours ago, 357mag said:

I don’t recall adding those single quotes around x (like (‘x’)). Don’t know what happened there. Mistakes and being human I guess.

Without those quotes the code would not compile…

Share this post


Link to post

On 4/28/2023 at 7:10 PM, 357mag said:

I’ve got a program that asks the user to enter a value (in an Edit box) and then when he clicks on the Show Value button, the Label should say «The value of x is » plus whatever value he entered in the Edit box.

But Delphi is complaining saying «x is not a valid integer value.»

I don’t know what’s wrong with my code but here is what I’ve got:

var
  FormSimpleVariable: TFormSimpleVariable;
  x : integer;

implementation

{$R *.dfm}

procedure TFormSimpleVariable.ButtonQuitClick(Sender: TObject);
begin
  Application.Terminate;
end;

procedure TFormSimpleVariable.ButtonShowValueClick(Sender: TObject);
begin
  x := StrToInt('x');
  LabelResult.Caption := 'The value of x is ' + IntToStr(x);
end;

end.

simply change your line from

  x := StrToInt('x');

to

  x := StrToInt(inttostr(x));

crazy, but will work. But I do not understand why someone would do this :classic_biggrin:

Share this post


Link to post

  • Prev
  • 1
  • 2
  • Next
  • Page 1 of 2  

Create an account or sign in to comment

You need to be a member in order to leave a comment

Sign in

Already have an account? Sign in here.

Sign In Now

delphi

Hi experts,
i have a data field called studentID.
StudentID has a data type of number and value/length of 8
In my delphi form i have an edit box where its max length is 8
When i insert number start from 1 as example below
e.g: 12345678 or 13564978 or 16459780 i can insert the value to database
but if i insert number start from 2 or 3 — 9 as example below
e.g: 26453156 or 89764569 or 65465978 i will received an error message note me that «26453156 is not a valid integer value.

problem: why 26453156 is not a valid integer value.

Delphi

Понравилась статья? Поделить с друзьями:
  • Ошибка в делфи access violation at address
  • Ошибка в делении скачок в делении
  • Ошибка в делении на абзацы
  • Ошибка в делении какой падеж
  • Ошибка в гугл 403 that s an error