You mustn't let an input "float" (open-circuit) if you want a defined input value, input pins have effectively infinite resistance
and will sense ambient electronic noise quite happily.
So you never connect just a switch to a pin, you always have a resistor pulling one way and a switch the other. Fortunately
all Arduino pins have built-in pull-up resistors (about 30k ohms) that can be activated by calling
digitalWrite (pin, HIGH) ;
when the pin is an INPUT (this is specific to AVR microcontrollers such as in the Uno and Mega).
Or you can use an external resistor (which can be wired to pull-up or pull-down).