The Arduino code I use is verified and all correct but the uploading just keeps repeating a error message.
Sketch uses 6850 bytes (2%) of program storage space. Maximum is 253952 bytes.
Global variables use 493 bytes (6%) of dynamic memory, leaving 7699 bytes for local variables. Maximum is 8192 bytes.
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer
Failed uploading: uploading error: exit status 1
This means that the Arduino can't contact your board.
Normally this is caused by not selection the correct board in the tools menu. Note for a mega there is a processor type that needs to be set to the type you have.
It can also be caused by a faulty Mega or USB lead.
This is nothing to do with the code you are trying to upload.
If the correct port is not showing up (something like "/dev/cu.usbmodem142301") you may need to install drivers for the USB-to-Serial chip on your Mega.