简体   繁体   中英

java try/catch problems with JOptionPane, need to catch incorrect ints

Kind of stuck with this question but how I can I make my try catch to only allow strings into the input box. (the relevant code is towards the bottom here sorry about the messy format still quite new to graphical programming)

I thought my code below would work however I guess it doesn't and I am not quite sure on now to make it catch for all ints in the sting input as the ints there are being entered as strings. I tried to use a boolean but that did not really work. Also if you could look at the email try/catch as well pop up the error box as well if a @ sign is up in since it is somewhat similar. Thanks

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.InputMismatchException;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;


public class MainPanel extends JPanel {

    Player myPlayer;
    Player myOtherPlayer;
    private int WIDTH = 1000;
    private int HEIGHT = 1000;
    private int WALLWIDTH = 100;
    private int WALLHEIGHT = 100;
    private ArrayList<Wall> walls = new ArrayList<Wall>();
    String Name;
    String Email;
    int favNum;

    Timer myTimer = new Timer(500, new timerListener());    
    JLabel myTimeLabel;
    int time =1;

    public MainPanel()
    {
        setPreferredSize(new Dimension(WIDTH,HEIGHT));
        JLabel myLabel= new JLabel ("Game ends once 30 seconds is receahed:");
        myLabel.setFont(new Font("Serif", Font.BOLD,32));
        myLabel.setForeground(Color.WHITE);
        myTimeLabel= new JLabel (Integer.toString(time));
        myTimeLabel.setFont(new Font("Serif", Font.BOLD,32));
        myTimer.start();

        add(myLabel);
        add(myTimeLabel);
        myPlayer = new Player(0,100, "toad.png", KeyEvent.VK_UP, KeyEvent.VK_DOWN, KeyEvent.VK_LEFT, KeyEvent.VK_RIGHT,this, 50, 38);
        myOtherPlayer = new Player(200,200, "toad.png", KeyEvent.VK_W, KeyEvent.VK_S, KeyEvent.VK_A, KeyEvent.VK_D,this, 50, 38);
        createWalls();
 }

    public ArrayList<Wall> getWalls() {
        return walls;
    }

    public void createWalls()
    {
        int j = 0;
        for(int i = 0; i < HEIGHT/WALLHEIGHT; i++)
        {
            for(int k = 0; k < WIDTH/WALLWIDTH; k++)
            {
                if(i == 0 || i == (HEIGHT/WALLHEIGHT-1))
                {
                    walls.add(new Wall(k*WALLWIDTH,j,"road.png", 100, 100));
                }

            }
            j+=WALLHEIGHT;
        }
    }


    private class timerListener implements ActionListener
    {


        public void actionPerformed(ActionEvent e) {
            time++;
            myTimeLabel.setText(Integer.toString(time));
            myTimeLabel.setForeground(Color.WHITE);
            if(time == 31)
            {
                myTimer.stop();
            }
            repaint();
        }

    }


    public void paintComponent(Graphics page)
    {
        super.paintComponent(page);

        page.drawImage(myPlayer.getImageIcon().getImage(), myPlayer.getX(), myPlayer.getY(), null);
        page.drawImage(myOtherPlayer.getImageIcon().getImage(), myOtherPlayer.getX(), myOtherPlayer.getY(), null);


        for(int i = 0; i < walls.size(); i++)
        {
            page.drawImage(walls.get(i).getImageIcon().getImage(), walls.get(i).getX(), walls.get(i).getY(), null);


        }

        page.setFont(new Font("Arial", Font.PLAIN,32)); 
        page.drawString("Player 1 Score: " + myPlayer.getScore(), 100, 800);
        page.drawString("Player 2 Score: " + myOtherPlayer.getScore(), 100, 850);
        myPlayer.checkOffScreen();

        if(time == 5)
        {
            page.drawString("GAME OVER", WIDTH/2-100, HEIGHT/2);

            try{
                Name = JOptionPane.showInputDialog("What is your name?");
                }catch (NumberFormatException  e) {
                    if (!Name.matches("^[a-z][a-z ]*[a-z]?$")){
                    JOptionPane.showInputDialog("You entered a number, this only accepts alphabetical letters. Please enter your name");}
                }

            try{
                favNum= Integer.parseInt(JOptionPane.showInputDialog("What is your favorite number?")); 
                }catch (NumberFormatException  e) {

                JOptionPane.showInputDialog("You entered a text, this only accepts numbers . Please enter your  favorite number");}

            try{
                Email =JOptionPane.showInputDialog("Please enter your email");
                }catch (InputMismatchException  e) {
                JOptionPane.showInputDialog("You enter your email incorrectly. Please include an @ sign with it");}
                }

            }

    }

You should use regular expressions to do this, rather than catching exceptions. It is good to have try catches, but you should not treat user input as exceptions since you should be checking it anyway, like:

String regex = "\\d+";
String input = JOptionPane.showInputDialog("What is your favorite number?");
if (!input.matches(regex)) {
   JOptionPane.showInputDialog("You entered a text, this only accepts numbers . Please enter your  favorite number");}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM