How to keep the pin's last state and return it after new loop??

Hi guy,
At first, take a look at my code:

//pin define
void setup{
     pinMode(2, INPUT);
     pinMode(3, OUTPUT);
}
void loop{
     if (digitalRead(2)==HIGH){ //read from an ON/OFF switch
          digitalWrite(3,HIGH);    //then output on a pin
     } else digitalWrite(3,LOW);
}

It’s ok if I hookup pin 3 with the LED, but I’m using a 5V relay. After compiled and uploaded the code, I switched ON the switch, but the relay on pin 3 keep up and down very fast. And I think the problem is: after each loop, the state of the pin return to default, so if Pin 2 is read as HIGH, the Pin 3 will be HIGH, and then LOW when returning for new loop.
How can I keep the state of the pin unchange after each void loop?

And I think the problem is: after each loop, the state of the pin return to default

No, it does not.

How is your switch wired?

No, that's not the problem. The output will keep its state.

Show us how you have the switch wired. Do you have a pull up or pull down resistor? Or could the input pin be floating?

How is the relay wired? You're not driving it directly off the Arduino are you?

@Delta_G:
No, the relay is a "8 relays module" with opto-isolators, and I just use the 5V signal of the arduino to control the isolator to control the relay, and the relay has it's own power source.

Pauls
The Switch is 3 pins switch. I hook the 5V to middle pin and output into the pin on arduino.

https://drive.google.com/file/d/0BzUT3sSXp6Jsa0I1bHpkdTAxNms/view?usp=sharing

Sorry for using goodle drive.

The Switch is 3 pins switch. I hook the 5V to middle pin and output into the pin on arduino.

So, when the switch is on, the pin gets 5V. When the switch is off, the pin gets what? Without a pulldown resistor, the pin floats. That sounds like exactly what you are seeing.

Connect the common leg to ground. Connect (one of) the other legs to digital pins with type INPUT_PULLUP. No more floating pins.

Of course, then LOW means on and HIGH means off, but that is a simple change to implement in the code.

Thanks PaulS, I'll try