Jumat, 30 April 2021

mencopy text file pada delphi console

program Project12copytxtfile;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;
  //System.BlockRead,System.BlockWrite,System.Close


var
  FromF, ToF: file;
  NumRead, NumWritten: Integer;
  Buf: array[1..2048] of Char;
begin
 try

    AssignFile(FromF, 'fileasal.txt');
    if FileExists('fileasal.txt') then

    Reset(FromF, 1) else rewrite(FromF,1);	{ Record size = 1 }

      AssignFile(ToF, 'filecopy.txt');	{ Open output file. }
      Rewrite(ToF, 1);	{ Record size = 1 }
      writeln( 'Copying ' + IntToStr(FileSize(FromF))
        + ' bytes...');
      repeat
        System.BlockRead(FromF, Buf, SizeOf(Buf), NumRead);
        BlockWrite(ToF, Buf, NumRead, NumWritten);
      until (NumRead = 0) or (NumWritten <> NumRead);
      // Use CloseFile rather than Close;
      // because Close is provided for backward compatibility.
      CloseFile(FromF);
      CloseFile(ToF);
      writeln(' done.');


  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);

  end;
       readln;
end.

menggunakan Tspinwait

program Project11tspinwait;

{$APPTYPE CONSOLE}

{$R *.res}
uses
  SysUtils, SyncObjs, Classes;

var
  Flag: Boolean;

type
  TThreadCause = class(TThread)
  private
    procedure Execute; override;
  end;

procedure TThreadCause.Execute;
begin
  Sleep(100); { 100 milliseconds }
  Flag := True;
end;

var
  LCause: TThreadCause;
  LSpinner: TSpinWait;

begin
  Flag := False;

  LCause := TThreadCause.Create(True);
  LCause.Start;
  LSpinner.Reset;
  while Flag = False do
  begin
    Writeln(IntToStr(LSpinner.Count));
    LSpinner.SpinCycle;
  end;
  Writeln(IntToStr(LSpinner.Count));
  Writeln(Flag); { displays TRUE }
  readln;
end.

memnformat data menggunakan unit Tformat


var 

begin
  { Ask the user to supply a date and place it into ShortDateFormat variable }
  WriteLn('Enter the desired format (ex. dd/mm/yyyy):');
  ReadLn(ShortDateFormat);
 
  { Write the date on the console using the selected short date format }
  WriteLn('Current date is ', DateToStr(Date()));
  
readln;
end.
masih error ini.. maaf ya.. kmu bisa kasih contoh gmn membaca format tanggal?

menampilkan data penjualan dari website yang menggunakan JSON object

program Project9jsonwriter;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,
  System.Classes,
  System.JSON.Types,
  System.JSON.Writers;

var
  Writer: TJsonTextWriter;
  StringWriter: TStringWriter;

begin
  StringWriter := TStringWriter.Create();
  Writer := TJsonTextWriter.Create(StringWriter);
  Writer.Formatting := TJsonFormatting.Indented;

  Writer.WriteStartObject;
  Writer.WritePropertyName('Transaction');
  Writer.WriteStartArray;
  Writer.WriteStartObject;
  Writer.WritePropertyName('id');
  Writer.WriteValue(662713);
  Writer.WritePropertyName('firstName');
  Writer.WriteValue('John');
  Writer.WritePropertyName('lastName');
  Writer.WriteValue('Doe');
  Writer.WritePropertyName('price');
  Writer.WriteValue(2.1);
  Writer.WritePropertyName('parent_id');
  Writer.WriteNull;
  Writer.WritePropertyName('validated');
  Writer.WriteValue(-1);
  Writer.WriteEndObject;
  Writer.WriteStartObject;
  Writer.WritePropertyName('id');
  Writer.WriteValue(662714);
  Writer.WritePropertyName('firstName');
  Writer.WriteValue('Anna');
  Writer.WritePropertyName('lastName');
  Writer.WriteValue('Smith');
  Writer.WritePropertyName('price');
  Writer.WriteValue(4.5);
  Writer.WritePropertyName('parent_id');
  Writer.WriteNull;
  Writer.WritePropertyName('validated');
  Writer.WriteValue(-1);
  Writer.WriteEndObject;
  Writer.WriteStartObject;
  Writer.WritePropertyName('id');
  Writer.WriteValue(662715);
  Writer.WritePropertyName('firstName');
  Writer.WriteValue('Peter');
  Writer.WritePropertyName('lastName');
  Writer.WriteValue('Jones');
  Writer.WritePropertyName('price');
  Writer.WriteValue(3.6);
  Writer.WritePropertyName('parent_id');
  Writer.WriteNull;
  Writer.WritePropertyName('validated');
  Writer.WriteValue(-1);
  Writer.WriteEndObject;
  Writer.WriteEndArray;
  Writer.WriteEndObject;

  WriteLn(StringWriter.ToString);

  readln;
   end.
   

membangun struktur data rekaman pelanggan menggunakan JSON pada delphi console

program Project8Jsonstring;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,
  System.Classes,
  System.JSON.Types,
  System.JSON.Writers,
  System.JSON.Builders;

var
  Builder: TJSONObjectBuilder;
  Writer: TJsonTextWriter;
  StringWriter: TStringWriter;
  StringBuilder: TStringBuilder;

begin
  StringBuilder := TStringBuilder.Create;
  StringWriter := TStringWriter.Create(StringBuilder);
  Writer := TJsonTextWriter.Create(StringWriter);
  Writer.Formatting := TJsonFormatting.Indented;
  Builder := TJSONObjectBuilder.Create(Writer);

  Builder
    .BeginObject
      .BeginArray('Transaction')
        .BeginObject.Add('id', 662713)
          .Add('firstName', 'John')
          .Add('lastName', 'Doe')
          .Add('price', 2.1)
          .AddNull('parent_id')
          .Add('validated', true)
        .EndObject
        .BeginObject
          .Add('id', 662714)
          .Add('firstName', 'Anna')
          .Add('lastName', 'Smith')
          .Add('price', 4.5)
          .AddNull('parent_id')
          .Add('validated', false)
        .EndObject
        .BeginObject
          .Add('id', 662715)
          .Add('firstName', 'Peter')
          .Add('lastName', 'Jones')
          .Add('price', 3.6)
          .AddNull('parent_id')
          .Add('validated', true)
        .EndObject
      .EndArray
    .EndObject;

  WriteLn(StringBuilder.ToString);
  readln;
end.

unit math untuk menghitung mean dan sd

Program Project7math;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  Math;

var
  Values: array[0..9] of Double;
  I: Integer;

begin
  Randomize;
  for I:= Low(Values) to High(Values) do
    begin
    Values[I]:= RandG(1.0, 0.5);    // Mean = 1.0, StdDev = 0.5
    Write(Values[I]:4,' ');
    end;
  writeln;
  Writeln('Mean          = ', Mean(Values):6:4);
  Writeln('Std Deviation = ', StdDev(Values):6:4);
  Readln;
end.

Penggunaan unit system Variants dan cara mengetahui jenis variabel

var
  LVar: Variant;
 
begin
  { Assign a byte value to the variant. }
  { Prints out "Byte" to the console. }
  LVar := 100;
  Writeln(VarTypeAsText(VarType(LVar)));
 
  { Multiply the byte value by 1000. This results in an Int64 with a value of 100000. }
  { Prints out "Int64" to the console. }
  LVar := LVar * 1000;
  Writeln(VarTypeAsText(VarType(LVar)));
 
  { Divide the LongWord value by 5.0. This results in a double value. }
  { Prints out "Double" to the console. }
  LVar := LVar / '5.0';
  Writeln(VarTypeAsText(VarType(LVar)));
  Readln;

mengganti variabel global S bertipe string menggunakan fungsi

program Project5string;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  SysUtils;

procedure Foo(var S: Openstring);
begin
  Writeln('S length :',Length(S)); { 5 }
  Writeln('S high ', High(S)); { 10 }
  Writeln('S MEMAKAN MEMORY KOMPUTER SEBESAR ', SizeOf(S)); {  11 bYTES }
  Writeln('S length :',Integer(S[0])); { 5 }
  //Writeln(S[1]); { C }
  S[1] := 'T';    // isi variabel S poisi ke satu diganti T
end;

var
  S: String[10];    // DEFINI VARIABEL s BERTIPE sTRING

begin try
  S := 'Corfu';
  Writeln('sebelum memanggil fungsi Foo berisi ',S[1]);
  Foo(S);    // memanggil fungsi Foo untuk mengubah isi S
  Writeln(' setelahnya berisi ',S[1]); { akan menampilkan huruf T bukan C lagi }
  Readln;

  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

konversi nilai variabel byte dan integer pada delphi 10

copas kode dibawah ini :
uses
  System.SysUtils;

var
  // Declare two of the basic intrinsic types that have helpers.
  // The others are: ShortInt, SmallInt, Word, Cardinal, NativeInt, NativeUInt and Int64.
  // The methods used in this code example apply to all the types mentioned above.
  myByte: Byte;
  myInteger: Integer;

const
  myString: String = '12345678910111211314';

begin
  try
  myByte := myByte.MaxValue; //255
  myInteger := myInteger.MaxValue;  //2147483647

  writeln('Byte value: ', myByte);
  writeln('Byte value as hexadecimal string using four digits: ',
    myByte.ToHexString(Integer(4)));
  writeln('Byte value as string: ', myByte.ToString());

  // Tries to convert myString to an Integer.
  if myInteger.TryParse(myString, myInteger) then
  begin
    writeln('The new value of myInteger is:', myInteger);
  end
  else
  begin
  //In case the conversion does not succeed,
  //the next statement will try to convert the myByte number
  //to a string.
  //The string returned will be converted to an integer value
  //with the Parse function.
    myInteger := myInteger.Parse(myByte.ToString());
    writeln('The new value of myInteger is:', myInteger);
  end;

  readln;


  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.
hasil output program bila dijalankan seperti ini :

Cara menggunakan box2D pada delphi console

uses
  System.SysUtils, Box2D.Collision, Box2D.Common,
  Box2D.Dynamics,
  Box2D.Rope, Box2DTypes;

var
  gravity: b2Vec2;
  world: b2WorldWrapper;
  groundBodyDef: b2BodyDef;
  groundBody: b2BodyWrapper;
  groundBox: b2PolygonShapeWrapper;
  bodyDef: b2BodyDef;
  body: b2BodyWrapper;
  dynamicBox: b2PolygonShapeWrapper;
  fixtureDef: b2FixtureDef;
  timeStep, angle: Single;
  velocityIterations, positionIterations, i: Integer;
  position: b2Vec2;
begin
  try
    // Define the gravity vector.
    gravity := b2Vec2.Create(0.0, -10.0);

    // Construct a world object, which will hold and simulate the rigid bodies.
    world := b2WorldWrapper.Create(gravity);

    // Define the ground body.
    groundBodyDef := b2BodyDef.Create;
    groundBodyDef.position.&Set(0.0, -10.0);

    // Call the body factory which allocates memory for the ground body
    // from a pool and creates the ground box shape (also from a pool).
    // The body is also added to the world.
    groundBody := world.CreateBody(@groundBodyDef);

    // Define the ground box shape.
    groundBox := b2PolygonShapeWrapper.Create;

    // The extents are the half-widths of the box.
    groundBox.SetAsBox(50.0, 10.0);

    // Add the ground fixture to the ground body.
    groundBody.CreateFixture(groundBox, 0.0);

    // Define the dynamic body. We set its position and call the body factory.
    bodyDef := b2BodyDef.Create;
    bodyDef.&type := b2_dynamicBody;
    bodyDef.position.&Set(0.0, 4.0);
    body := world.CreateBody(@bodyDef);

    // Define another box shape for our dynamic body.
    dynamicBox := b2PolygonShapeWrapper.Create;
    dynamicBox.SetAsBox(1.0, 1.0);

    // Define the dynamic body fixture.
    fixtureDef := b2FixtureDef.Create;
    fixtureDef.shape := dynamicBox;

    // Set the box density to be non-zero, so it will be dynamic.
    fixtureDef.density := 1.0;

    // Override the default friction.
    fixtureDef.friction := 0.3;

    // Add the shape to the body.
    body.CreateFixture(@fixtureDef);

    // Prepare for simulation. Typically we use a time step of 1/60 of a
    // second (60Hz) and 10 iterations. This provides a high quality simulation
    // in most game scenarios.
    timeStep := 1.0 / 60.0;
    velocityIterations := 6;
    positionIterations := 2;

    // This is our little game loop.
    for I := 0 to 59 do
    begin
      // Instruct the world to perform a single step of simulation.
      // It is generally best to keep the time step and iterations fixed.
      world.Step(timeStep, velocityIterations, positionIterations);

      // Now print the position and angle of the body.
      position := body.GetPosition^;
      angle := body.GetAngle;

      WriteLn(Format('%4.2f %4.2f %4.2f', [position.x, position.y, angle]));
    end;

    // When the world destructor is called, all bodies and joints are freed.
    // This can create orphaned pointers, so be careful about your world
    // management.
    world.Destroy;

    ReadLn;
    
    

Belajar mengisi tipe Trect fungsi bound pada Delphi Console

tambahkan code pada proect anda seperti ini
uses
  System.SysUtils,
  System.Types;

var
  aRectangle:TRect;

begin
  try
    aRectangle := Bounds(4,5,16,25);
    {
    equivalent to:
      aRectangle.Left := 4;
      aRectangle.Top := 5;
      aRectangle.Width := 16;
      aRectangle.Height := 25;
    }

    WriteLn('batas kiri ',aRectangle.Left,' batas atas ', aRectangle.Top,
     ' batas kanan ',aRectangle.Right,' batas bawah ',aRectangle.Bottom);

    readln; 

Menampilkan Hello World di Delphi 10 console

Buka Delphi buat project baru tipe aplikasi console tampilan akan seperti ini :

kemudian ketik dua baris code dibawah perintah try seperti ini :
    writeln('Hello world');
    readln;
    

Kemudian Jalankan maka tampilan klo berhasil harus seperti ini

Belajar bahasa pascal Mode Console di Delphi 10

Tahun 2017 ini saya menginstal delphi vwersi 10, lumayanlah untuk berjalan di laptop Core_i3 ku.