Storing user input as a string in Java

Ive been working with my personal pong game and came across a very annoying bug that i haven't been able to fix. If i run the game everything works fine. Once the game is over it is supposed to prompt you to enter your name. The name should then bed stored as a String. Then it tells you your name and your score. But instead of that happening it doesn't store the user input a just stays blank. Some please help me!!!

@SuppressWarnings("resource")
public void replay() {

    JFrame frame = new JFrame("input");
    JOptionPane.showInputDialog(frame, "what is your name player 1? ");
    String playerName1 = new String();
    new Scanner(System.in);

    JOptionPane.showConfirmDialog(null, 
            "Name: " + playerName1 + "  Score: " + scorePlayer1 , "Player scores",
            JOptionPane.DEFAULT_OPTION);

    String playerName2 = new String();
    JOptionPane.showInputDialog(frame, "what is your name player 2? ");

    JOptionPane.showConfirmDialog(null,
            "Name: " + playerName2 + "  Score: " + scorePlayer2 , "Player scores",
            JOptionPane.DEFAULT_OPTION);

    int n = JOptionPane.showConfirmDialog(null,
        "Would you like to play again?",
        "Pong",
        JOptionPane.YES_NO_OPTION);

    if (n == 0){
        setup();
    } else {
        System.exit(0);
    }
}

Upvotes: 0

Views: 91

Answers (2)

John Gardner
John Gardner

Reputation: 25116

you aren't actually using the result of showInputDialog for anything.

playerName1 = JOptionPane.showInputDialog(...);
playerName2 = JOptionPane.showInputDialog(...);

Upvotes: 0

aryn.galadar
aryn.galadar

Reputation: 736

You're setting 'playerName' to an empty string, then discarding the players's input:

String playerName2 = new String();
JOptionPane.showInputDialog(frame, "what is your name player 2? ");

Instead, save the player's input to the playerName string:

String playerName2 = JOptionPane.showInputDialog(frame, "what is your name player 2? ");

(This is an example for player 2; just do the same thing with a different variable (probably playerName1) for player 1)

Upvotes: 2

Related Questions