0 / 0 / 0 Регистрация: 06.11.2011 Сообщений: 31 |
|
1 |
|
26.10.2012, 11:39. Показов 21044. Ответов 14
Делаю конвертер валют и при нажатии на кнопку «Посчитать» появляется ошибка
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 |
|||||||
Добавлено через 8 минут
Ну значит у тебя несовместимость типов.
0 |
Супер-модератор 32592 / 21061 / 8134 Регистрация: 22.10.2011 Сообщений: 36,332 Записей в блоге: 8 |
|
26.10.2012, 11:53 |
4 |
Во-первых, это не должно даже компилироваться (не хватает скобок в If-ах), а если и скомпилируется, то работать может не так, как подразумевалось, так что исправляй. А во-вторых, покажи скриншот, что именно ты вводишь в эдиты.
0 |
HanDi |
26.10.2012, 11:57
|
Не по теме:
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 |
Это компилируется… Миниатюры
0 |
0 / 0 / 0 Регистрация: 06.11.2011 Сообщений: 31 |
|
26.10.2012, 12:00 [ТС] |
7 |
Не по теме: о мои глаза.. о мой МОЗГ! просто сначало использовал CheckBox
0 |
volvo Супер-модератор 32592 / 21061 / 8134 Регистрация: 22.10.2011 Сообщений: 36,332 Записей в блоге: 8 |
||||||||||||
26.10.2012, 12:05 |
8 |
|||||||||||
Это компилируется… А я предупреждал, что это может работать неправильно. Смотри, как условие
видит компилятор (учитывая, что приоритет AND выше приоритета операции сравнения, а все операции сравнения выполняются, как им и положено, слева направо)
Чувствуешь разницу? То есть, какой кусок кода выполняется в какой момент времени — совершенно непонятно. Добавь скобки:
— будет ближе к истине (приоритет NOT выше, чем сравнения, так что тут проблем не будет).
0 |
Alkcatras 0 / 0 / 0 Регистрация: 06.11.2011 Сообщений: 31 |
||||||||
26.10.2012, 12:15 [ТС] |
9 |
|||||||
поставил так
считает только для RUS Добавлено через 4 минуты
Можешь объяснит??
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 |
|||||||||||||||
А я предупреждал, что это может работать неправильно. Смотри, как условие
видит компилятор (учитывая, что приоритет AND выше приоритета операции сравнения, а все операции сравнения выполняются, как им и положено, слева направо)
Чувствуешь разницу? То есть, какой кусок кода выполняется в какой момент времени — совершенно непонятно. Добавь скобки:
— будет ближе к истине (приоритет NOT выше, чем сравнения, так что тут проблем не будет). поставил так
считает только для RUS, для USD и EUR не считает
0 |
Супер-модератор 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 |
Ты все свои условия подобным образом поправил, или только одно какое-то? Исправь все (строки 21, 27, 32 из третьего сообщения), потом скажешь, получилось или нет. Да все, и 21 и 27 и 32.Считает только для RUS.В RUS пишу число в сумме 1 в остольных Edit-ах 0(если не писать то появляется ошибка «is not a valid integer value») при выполнении появляется число из RUS.но если делать это для USD или EUR ничего вообще не происходит.
0 |
volvo Супер-модератор 32592 / 21061 / 8134 Регистрация: 22.10.2011 Сообщений: 36,332 Записей в блоге: 8 |
||||||||
26.10.2012, 17:33 |
14 |
|||||||
И вообще, почему нельзя вместо трех независимых RadioButton-ов использовать один RadioGroup с тремя элементами, и проверять:
? Кстати, ошибка твоя — от невнимательности:
, и потом, у тебя вообще не присутствовал RADIOBUTTON3, зато RADIOBUTTON2 везде проверялся по 2 раза…
0 |
Alkcatras 0 / 0 / 0 Регистрация: 06.11.2011 Сообщений: 31 |
||||||||
26.10.2012, 17:59 [ТС] |
15 |
|||||||
И вообще, почему нельзя вместо трех независимых RadioButton-ов использовать один RadioGroup с тремя элементами, и проверять:
? Кстати, ошибка твоя — от невнимательности:
, и потом, у тебя вообще не присутствовал 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
-
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 ?
-
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.
-
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.
-
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!!!!
-
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:
- returns a boolean;
- 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
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