How does Diffie-Hellman prevent a man-in-the-middle attack?
Answer: Diffie-Hellman does not prevent a man-in-the-middle attack.
If you're using Diffie-Hellman without any sort of authentication, then Oscar can certainly change the keys. When he does that, what's effectively happen is that Alice and Bob aren't actually negotiating keys; Alice is negotiating with Oscar (and generating one set of keys), and Oscar is negotiating with Bob (and generating another set of keys). If Oscar wants, he can proceed to allow Alice and Bob to communicate (by decrypting any traffic from Alice, and then re-encrypting it with Bob's keys; of course, he can record and/or modify the traffic at whim).
Because of this, it is considered fundamental that whenever you use Diffie-Hellman, you include something that performs authentication; that is, something that allows Alice to confirm that Bob is on the other end of the encrypted connection. Some schemes that have actually been used in practice:
Bob signs his Diffie-Hellman public value; if Alice has Bob's public key (or alternatively, Bob has a certificate that Alice can validate), Oscar is unable to duplicate that.
Alice and Bob share a secret value that is used to generate a MAC of the Diffie-Hellman public value (or the shared secret), and nothing else.
Now, the obvious question is: Alice and Bob can share a key using either public keys, or a preexisting shared secret; what does Diffie-Hellman bring to the table? The answer to that is Perfect Shared Secrecy: If Alice and Bob used Diffie-Hellman (and zeroized the private exponents and the shared secret when they are done with them) then Oscar cannot decrypt the transcript, even if he later discovers all of Alice's and Bob's secret values.
In contrast, you could use public key encryption to transport a shared key from one side to the other, however if someone later discovers the private key (e.g. it gets leaked), then he can go back, and decrypt a transcript of the connection.