I am programming a pong game. The following code below:
import javax.swing.*;
import java.awt.event.*;
import java.io.FileWriter;
public class Launcher {
public static void main(String[] args) {
JFrame f = new JFrame("Title");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
FileWriter file = new FileWriter("io.txt");
if(e.getKeyChar() == 's') {
file.write("s");
}
if(e.getKeyChar() == 'w') {
file.write("w");
}
file.close();
}
@Override
public void keyReleased(KeyEvent e) {
FileWriter file = new FileWriter("io.txt");
if(e.getKeyChar() == 's') {
file.write("");
}
if(e.getKeyChar() == 'w') {
file.write("");
}
file.close();
}
});
PongGame mainframe = new PongGame();
f.add(mainframe);
f.setSize(500,500);
f.setVisible(true);
}
}
gives me multiple errors:
Launcher.java:15: error: unreported exception IOException; must be caught or declared to be thrown
FileWriter file = new FileWriter("io.txt");
^
Launcher.java:17: error: unreported exception IOException; must be caught or declared to be thrown
file.write("s");
^
Launcher.java:20: error: unreported exception IOException; must be caught or declared to be thrown
file.write("w");
^
Launcher.java:22: error: unreported exception IOException; must be caught or declared to be thrown
file.close();
^
Launcher.java:26: error: unreported exception IOException; must be caught or declared to be thrown
FileWriter file = new FileWriter("io.txt");
^
Launcher.java:28: error: unreported exception IOException; must be caught or declared to be thrown
file.write("");
^
Launcher.java:31: error: unreported exception IOException; must be caught or declared to be thrown
file.write("");
^
Launcher.java:33: error: unreported exception IOException; must be caught or declared to be thrown
file.close();
^
8 errors
I want to be able to write to the file. I don't know what the problem could possibly be. I have tried defining the file variable outside of the main method and defining it inside of each if statement. Any help is appreciated. Thanks!