Soloway's recurring rainfall: Difference between revisions

m
No edit summary
 
(7 intermediate revisions by 6 users not shown)
Line 399:
 
To get the TMemo to behave like a console application, I've created an object that captures keyboard into to the TMemo and can return the keystrokes a chars, integers or reals. The object, which is called "TKeyWaiter," is simply created and attached to a TMemo component. While the object is alive, it will capture key stroke and return chars, integers or reals. It can be destroyed as soon as it is no longer needed. In fact, in this code, I create and destroy it for every input. The creation overhead is so low that there is no reason to create a global copy and keep it alive while the program is operating.
 
 
<syntaxhighlight lang="Delphi">
{ TMemoWaiter }
 
{This code would normally be in a library somewhere, but it is included here for clarity}
type TControlHack = class(TWinControl) end;
 
{TKeywaiter interface}
constructor TKeyWaiter.Create(Control: TWinControl);
{Save the control we want to wait on}
begin
FControl:=Control;
FControlCAbort:=False;
end;
 
procedure TKeyWaiter.HandleKeyPress(Sender: TObject; var Key: Char);
{Handle captured key press}
begin
KeyChar:=Key;
ValidKey:=True;
if ControlCAbort then AbortWait:=KeyChar = #$03;
end;
 
 
function TKeyWaiter.WaitForKey: char;
{Capture keypress event and wait for key press control}
{Spends most of its time sleep and aborts if the user}
{sets the abort flag or the program terminates}
begin
ValidKey:=False;
AbortWait:=False;
TControlHack(FControl).OnKeyPress:=HandleKeyPress;
repeat
begin
Application.ProcessMessages;
Sleep(100);
end
until ValidKey or Application.Terminated or AbortWait;
Result:=KeyChar;
end;
 
 
function TKeyWaiter.WaitForInteger: integer;
var C: char;
var S: string;
begin
Result:=0;
S:='';
{Wait for first numeric characters}
repeat
begin
C:=WaitForKey;
if AbortWait or Application.Terminated then exit;
end
until C in ['+','-','0'..'9'];
{Read characters and convert to}
{integer until non-integer arrives}
repeat
begin
S:=S+C;
C:=WaitForKey;
if AbortWait or Application.Terminated then exit;
end
until not (C in ['+','-','0'..'9']);
Result:=StrToInt(S);
end;
 
 
type TCharSet = set of char;
 
function TKeyWaiter.WaitForReal: double;
var C: char;
var S: string;
const RealSet: TCharSet = ['-','+','.','0'..'9'];
begin
Result:=0;
S:='';
{Wait for first numeric characters}
repeat
begin
C:=WaitForKey;
if AbortWait or Application.Terminated then exit;
end
until C in RealSet;
{Read characters and convert to}
{integer until non-integer arrives}
repeat
begin
S:=S+C;
C:=WaitForKey;
if AbortWait or Application.Terminated then exit;
end
until not (C in RealSet);
Result:=StrToFloat(S);
end;
 
type TKeyWaiter = class(TObject)
private
FControl: TWinControl;
FControlCAbort: boolean;
protected
procedure HandleKeyPress(Sender: TObject; var Key: Char);
public
KeyChar: Char;
ValidKey: boolean;
AbortWait: boolean;
constructor Create(Control: TWinControl);
function WaitForKey: char;
function WaitForInteger: integer;
function WaitForReal: double;
property ControlCAbort: boolean read FControlCAbort write FControlCAbort;
end;
 
 
{ TMemoWaiter implementation }
 
type TControlHack = class(TWinControl) end;
Line 662 ⟶ 590:
</pre>
 
=={{header|EasyLang}}==
{{trans|BASIC256}}
<syntaxhighlight>
repeat
print "Enter integral rainfall (99999 to quit): "
i = number input
until i = 99999
if error = 1 or i < 0 or i mod 1 <> 0
print "Must be an integer no less than 0, try again."
else
n += 1
sum += i
print " The current average rainfall is " & sum / n
.
.
</syntaxhighlight>
 
=={{header|Fortran}}==
Line 1,184 ⟶ 1,128:
Integer units of rainfall in this time period? (999999 to finalize and exit)>: 999999
Average rainfall 0.00 units over 0 time periods.</pre>
 
=={{header|RPL}}==
{{works with|HP|28}}
{| class="wikitable" ≪
! RPL code
! Comment
|-
|
≪ "Enter rainfall, then ENTER" 1 DISP
"" "0123456789"
'''DO DO UNTIL''' KEY '''END'''
'''IF''' DUP2 POS '''THEN'''
ROT OVER + DUP 2 DISP ROT ROT
'''END'''
'''UNTIL''' "ENTER" == '''END'''
DROP STR→
≫ '<span style="color:blue">READB</span>' STO
≪ "Enter 9999 to end" 4 DISP
(0,0) 1 CF CLLCD
DO READB
'''IF''' DUP 9999 == '''THEN''' 1 SF
'''ELSE'''
1 R→C +
"Average = " OVER RE LAST IM / →STR +
3 DISP
'''END'''
'''UNTIL''' 1 FS? '''END'''
SWAP DROP CLMF
'''IFERR''' RE LAST IM / '''THEN''' DROP2 '''END'''
≫ '<span style="color:blue">RFALL</span>' STO
|
<span style="color:blue">READB</span> ''( → n )''
Initialize variables
Loop
if keystroke is an accepted char
add char to output and display it
until ENTER is pressed
clean stack and convert to integer
<span style="color:blue">RFALL</span> ''( → ) ''
initialize counters and flag, clear screen
loop
get rainfall
if break value then set flag
otherwise
accumulate rainfall and increment count
display average rainfall
until flag set
clean stack, unfreeze display
put average rainfall in stack if count ≠ 0
|}
 
 
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">QUIT = 99999
num = nil
count = 0
avg = 0.0
 
loop do
begin
print "Enter rainfall int, #{QUIT} to quit: "
input = gets
num = Integer(input)
rescue ArgumentError
puts "Invalid input #{input}"
redo
end
break if num == QUIT
count += 1
inv_count = 1.0/count
avg = avg + inv_count*num - inv_count*avg
end
 
puts "#{count} numbers entered, averaging #{average}"
</syntaxhighlight>
 
=={{header|Rust}}==
Line 1,218 ⟶ 1,243:
}
}
}
</syntaxhighlight>
=={{header|Swift}}==
<syntaxhighlight lang="swift">
import Foundation
 
var mean: Double = 0
var count: Int = 0
var prompt = "Enter integer rainfall or 99999 to exit:"
var term = " "
print(prompt, terminator: term)
while let input = readLine() {
defer {
print("count: \(count), mean: \(mean.formatted())\n\(prompt)", terminator: term)
}
guard let val = Int(input) else {
print("Integer values only")
continue
}
if val == 99999 {
(prompt, term) = ("Done","\n")
break
}
count += 1
mean += Double(val)/Double(count) - mean/Double(count)
}
</syntaxhighlight>
Line 1,223 ⟶ 1,273:
=={{header|Wren}}==
{{libheader|Wren-ioutil}}
<syntaxhighlight lang="ecmascriptwren">import "./ioutil" for Input
 
var n = 0
2,063

edits